This is a brief guide on how to retrieve the current AWS account ID in Terraform.
Introduction
When writing Terraform, there are times when you need to retrieve and set the AWS account ID, such as when specifying ARNs.
This article serves as a reference for how to do this, and also takes a look at the related source code.
Note: This article was translated from my original post.
Getting AWS Account ID in Terraform
How to Do It
You can retrieve the AWS account ID using the aws_caller_identity data source.
data "aws_caller_identity" "current" {} # You can retrieve the account ID with # data.aws_caller_identity.current.account_id
As a usage example, you can embed the account ID in an ARN like this:
source_arn = "arn:aws:events:eu-west-1:${data.aws_caller_identity.current.account_id}:rule/RunDaily"
※ Reference: terraform-aws-lambda/examples/complete/main.tf at master · terraform-aws-modules/terraform-aws-lambda · GitHub
Since data.aws_caller_identity.current.account_id is quite long to access every time, it's recommended to store it in a local variable as needed.
locals { account_id = data.aws_caller_identity.current.account_id }
Bonus: Reading the Terraform Source Code
Let's take a look at the source code where the aws_caller_identity data source is implemented.
The aws_caller_identity should be using the AWS STS API, so let's find where STS-related functionality is defined in terraform-provider-aws.
Here it is:
Here's an excerpt from the most relevant part:
func dataSourceCallerIdentityRead(d *schema.ResourceData, meta interface{}) error { client := meta.(*conns.AWSClient).STSConn log.Printf("[DEBUG] Reading Caller Identity") res, err := client.GetCallerIdentity(&sts.GetCallerIdentityInput{}) if err != nil { return fmt.Errorf("getting Caller Identity: %w", err) } log.Printf("[DEBUG] Received Caller Identity: %s", res) d.SetId(aws.StringValue(res.Account)) d.Set("account_id", res.Account) d.Set("arn", res.Arn) d.Set("user_id", res.UserId) return nil }
It calls GetCallerIdentity through the AWS Client's STS connection, and retrieves the caller's account_id, arn, and user_id from there.
Conclusion
That's it for this quick note on how to retrieve the current AWS account ID in Terraform.
Since Terraform is based on AWS APIs (unlike CloudFormation), it's nice that you can trace through these kinds of implementations in an intuitive way.
[Related Articles]