A quick reference for how to get the AWS region in Terraform.
Introduction
When working with AWS resources in Terraform, there are times when you need to retrieve the account ID or region name, such as when specifying ARNs.
Previously, I wrote about how to get the AWS account ID in Terraform, but I always had to search for the method to get the region each time, so I'm documenting it here.
Note: This article was translated from my original post.
Getting AWS Region in Terraform
How to do it
You can retrieve the AWS region name using the aws_region data source.
data "aws_region" "current" {}
Once you've defined the data source like this, you can retrieve the region name using the following format:
data.aws_region.current.name
# Usage example source_arn = "arn:aws:events:${data.aws_region.current.name}:123456789012:rule/RunDaily"
If needed, storing the region name in a local variable is also a good practice as it improves readability and makes changes easier.
locals { region = data.aws_region.current.name }
Bonus: Reading the Terraform Source Code
As a bonus, let's take a look at the implementation of the aws_region data source from the source code.
The code below implements the aws_region data source.
Inside this, the actual implementation of the aws_region data source is in the Read function.
Here's an excerpt of the code that retrieves the provider's current region:
// Default to provider current region if no other filters matched if region == nil { matchingRegion, err := FindRegionByName(d.Meta().Region) if err != nil { response.Diagnostics.AddError("finding Region by name", err.Error()) return } region = matchingRegion }
When no arguments are specified for the aws_region data source, you can see that the provider's current region is retrieved from the metadata.
Conclusion
This wraps up on how to get the AWS region in Terraform, along with a look at the source code.
Hope you find this useful!
[Related Articles]
References
- Terraform Registry
- terraform-provider-aws/internal/service/meta at be9d5ac322736b8c599459a755cb3d63be051e6c · hashicorp/terraform-provider-aws · GitHub
- terraform-provider-aws/internal/service/meta/region_data_source.go at be9d5ac322736b8c599459a755cb3d63be051e6c · hashicorp/terraform-provider-aws · GitHub
- terraform-provider-aws/internal/service/meta/region_data_source_test.go at be9d5ac322736b8c599459a755cb3d63be051e6c · hashicorp/terraform-provider-aws · GitHub
- Access instance metadata for an EC2 instance - Amazon Elastic Compute Cloud