terraform, aws,

Get AWS Region Name in Terraform

Oct 06, 2021 · 1 min read · Post a comment
Get AWS Region Name in Terraform

The following tutorial will be a step by step guide on how to get the current AWS region name in Terraform.

Prerequisites

  • Terraform

Solution

Step 1. Create a file called data.tf and add the following line:

data "aws_region" "current" {}

Step 2. Assuming you have the region specified in a provider.tf file:

provider "aws" {
  region = "us-west-1"
}

Step 3. Now, you could assign the aws_region data source as a variable, or as an argument value. Let’s add the AWS region name as a local variable in main.tf:

locals {
  region = "${data.aws_region.current.name}"
}

Or, another example:

resource "aws_cloudfront_distribution" "s3_distribution" {
  origin {
    domain_name = "test-cdn.s3.amazonaws.com"
    origin_id   = "test-cdn.s3.${data.aws_region.current.name}.amazonaws.com"

    ...
  }
  ...
}

Or, even better, refence the local variable region as origin_id value:

origin_id   = "test-cdn.s3.${local.region}.amazonaws.com"

Step 4. If you need to use the region name in multiple environments, you could make the code a bit DRY-er, by adding data.tf to the root of Terraform directory, and create a soft link in every subdirectory environment, or use Terragrunt instead, depending on how you are handling TF environments.

Conclusion

This tutorial is aimed to provide you with a quick and safe path of getting the AWS region name in Terraform.
Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on telegram.