Terraform: retrieve AWS information

2 min read | by Jordi Prats

When running terraform on an AWS account we might need to have some context information such as it's account ID or the region we are in. Instead of having to set them as variables we can use the aws_caller_identity, aws_partition and aws_region datasources to retrieve this information

It's usage can't possibly be more straightforward:

data "aws_caller_identity" "current" {}

data "aws_partition" "current" {} 

data "aws_region" "current" {}

Retrieve current's account ID

With the aws_caller_identity we can retrieve the account ID as follows:

data "aws_caller_identity" "current" {}

module "example" {
  source = "./modules/example"

  account_id = data.aws_caller_identity.current.account_id

  tags = var.tags
}

AWS partition

With aws_partition we can check what's the partition we are using, for example, the commercial AWS, the government AWS or AWS CN. Depending on the partition AWS used a different DNS domain which can also be retrieved using the dns_suffix and reverse_dns_prefix attributes.

We can use it to adjust DNS names if we are using AWS China, or enable/disable some services on it

AWS region

Finally, using aws_region we can get the region we are currently using:

data "aws_region" "current" {}

module "example" {
  source = "./modules/example"

  region_name = data.aws_region.current.name

  tags = var.tags
}

Posted on 19/01/2022