Amazon Web Services (AWS) - Return AWS Account ID using Terraform

by
Jeremy Canfield |
Updated: August 31 2023
| Amazon Web Services (AWS) articles
Let's say you have the following files on your Terraform server.
├── required_providers.tf
├── iam (directory)
│ ├── data.tf
│ ├── outputs.tf
│ ├── provider.tf
required_providers.tf will almost always have this.
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
}
}
}
Let's say provider.tf has the following. In this example, the "default" profile in /home/username/.aws/config and /home/username/.aws/credentials is being used. This assumes you have setup Terraform as described in Amazon Web Services (AWS) - Getting Started with Terraform.
provider "aws" {
alias = "default"
profile = "default"
region = "default"
}
And data.tf could have something like this.
data "aws_caller_identity" "caller-identity" {}
And outputs.tf could have something like this.
output "caller_identity" {
value = data.aws_caller_identity.caller-identity
}
The terraform refresh command should output something like this.
caller_identity = {
"account_id" = "123456789012"
"arn" = "arn:aws:iam::123456789012:user/johndoe"
"id" = "123456789012"
"user_id" = "AIABDEFG76GL123456RP"
}
Did you find this article helpful?
If so, consider buying me a coffee over at