How to get the AWS AccountID in Terraform

0 min read 112 words

If you are automating AWS resources in Terraform, then you will want to not hardcode things as much as possible.

Terraform makes it possible to pull the account_id from the local credentials.

How to get the AccountID data attributes

Create a data.tf file and place the following item in it:

data "aws_caller_identity" "current" {}

Now the account_id will be available to you within your standard code as follows:

data.aws_caller_identity.current.account_id

How to use the AccountID data attributes

This can now be used in a module, or wherever you need to reference the account id:

module "my_custom_module" {
  tags        = var.tags
  vpcid       = var.vpcid
  subnetids   = var.subnetid
  account_id  = data.aws_caller_identity.current.account_id
  source      = "./modules/some_module"
}
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags