Terraform projects that span multiple AWS accounts, environments, and credential sets require a reliable way to reference the effective AWS identity without hardcoding values. The aws_caller_identity data source provides a dynamic mechanism to query the current caller using the AWS Security Token Service and expose the account ID, ARN, and user ID for use throughout configuration. This approach removes manual maintenance of account identifiers and supports cleaner, more portable infrastructure code.
The data source is read-only and has no arguments. It relies on the AWS provider establishing an STS connection and calling GetCallerIdentity. When the provider is configured with skip_requesting_account_id set, the data source will return an error because an Account ID is only available if that flag is not set. The implementation reads the caller identity and sets the resource ID to the account value, then populates account_id, arn, and user_id attributes from the STS response.
Data Source Definition
Defining the data source is a single block with a local name. The conventional name used in examples is current.
hcl
data "aws_caller_identity" "current" {}
This block creates a data source named current that fetches the caller's identity information. No arguments are available for this data source. Once defined, the attributes can be referenced as data.aws_caller_identity.current.account_id, data.aws_caller_identity.current.arn, and data.aws_caller_identity.current.user_id.
A common pattern is to expose the values as outputs for visibility during planning and apply.
hcl
output "account_id" {
value = data.aws_caller_identity.current.account_id
}
The same pattern is also expressed with interpolation syntax in older examples:
hcl
output "account_id" {
value = "${data.aws_caller_identity.current.account_id}"
}
Additional outputs can be added for ARN and user ID.
```hcl
output "callerarn" {
value = data.awscaller_identity.current.arn
}
output "calleruser" {
value = data.awscalleridentity.current.userid
}
```
Attributes Reference
The data source exposes three attributes populated from the STS GetCallerIdentity response.
| Attribute | Description | Source |
|---|---|---|
| account_id | The AWS Account ID number of the account that owns or contains the calling entity | STS GetCallerIdentity |
| arn | The AWS ARN associated with the calling entity | STS GetCallerIdentity |
| user_id | The unique identifier of the calling entity | STS GetCallerIdentity |
The account_id attribute is set to the ID of the AWS account. The arn attribute is the AWS ARN associated with the calling entity. The user_id attribute is the unique identifier of the calling entity.
Example Usage
Using the account ID dynamically avoids hardcoding and enables resource naming and conditional logic that follows the credentials in use.
hcl
resource "aws_s3_bucket" "my_bucket" {
bucket = "my-bucket-${data.aws_caller_identity.current.account_id}"
# ... other configurations
}
This ensures the Terraform code always uses the correct account ID, even if AWS credentials or environments are switched. The data source can be used in resource names, configurations, conditional logic based on caller identity, constructing IAM policies dynamically for the calling user or role, and filtering resources based on the account ID.
The provider configuration is not required in the data source block itself. The data source uses the effective AWS provider configuration to establish the STS connection.
Benefits of Dynamic Account ID Retrieval
Avoiding hardcoding provides reliability and flexibility across environments.
- Accuracy: Ensures the correct account ID is used, even when switching credentials or environments.
- Flexibility: Eliminates the need to manually update the account ID in multiple places.
- Best practice: Promotes cleaner and more maintainable Terraform code.
Dynamic usage of data.aws_caller_identity.current.account_id throughout Terraform code reduces drift risk when moving between development, staging, and production accounts. It also simplifies module design because modules no longer require an explicit account ID input.
Security and Operational Considerations
While convenient, directly embedding the aws_caller_identity output into publicly accessible resources like bucket names may expose the account ID. In use cases that demand stricter security, consider fetching the account ID from secure sources like AWS Secrets Manager or environment variables.
Alternatives exist for sensitive contexts. For parsing ARNs and extracting specific components beyond the account ID, the aws_arn data source can be explored.
Troubleshooting should start with credential verification. Ensure AWS credentials are correctly configured and have the necessary permissions to access the sts:GetCallerIdentity API action. The terraform console can be used to experiment with the aws_caller_identity data source and debug issues.
The data source depends on the AWS provider's STS connection. The provider implementation calls GetCallerIdentity through the AWS Client's STS connection and retrieves the caller's account_id, arn, and user_id from there.
go
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
}
The code sets the resource ID to the account value and populates the three attributes for use in configuration.
Best Practices
Meaningful naming improves readability. Use descriptive names for data sources and output variables.
Comments should explain the purpose and usage of the aws_caller_identity data source within the codebase.
When writing Terraform code, referencing the AWS account ID should be done via the data source rather than manual entry. This approach provides a more reliable and dynamic way to fetch the account ID within Terraform scripts.
Use cases beyond resource naming include conditional logic based on the caller's identity and constructing IAM policies dynamically for the calling user or role.
Implementation and Provider Behavior
The aws_caller_identity data source is implemented using the AWS STS API. The provider's STS-related functionality is defined in terraform-provider-aws and the read function calls GetCallerIdentity via the STS connection.
A note on behavior: an Account ID is only available if skip_requesting_account_id is not set on the AWS provider. In such cases, the data source will return an error.
The data source has no arguments available. The attributes are populated directly from the STS response.
Conclusion
The aws_caller_identity data source provides a stable, provider-managed method to surface the effective AWS identity within Terraform. By querying STS at plan time, it eliminates hardcoding, supports credential portability, and enables dynamic naming and policy generation that adapts to the account and principal actually executing the plan. Operational hygiene around credential permissions for sts:GetCallerIdentity, careful handling of public exposure of account IDs in names, and clear naming conventions ensure the pattern remains robust as infrastructure scales across multiple accounts and teams. Continued reliance on the STS-backed data source aligns Terraform configurations with real-time AWS authorization context rather than static assumptions.