以下の内容はhttps://en.bioerrorlog.work/entry/get-tf-aws-regionより取得しました。


Getting AWS Region in Terraform

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.

github.com

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]

en.bioerrorlog.work

References




以上の内容はhttps://en.bioerrorlog.work/entry/get-tf-aws-regionより取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14