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" {}
Code language: JavaScript (javascript)

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

data.aws_caller_identity.current.account_id
Code language: CSS (css)

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" }
Code language: JavaScript (javascript)

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments