How to Get the AWS AccountID in Terraform

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"
}