How can I verify which AWS account CDKTF/Terraform is targeting during plan?

I’m using CDK for Terraform (CDKTF) with multiple stacks, each typically configured with its own AWS provider.

However, if a stack is created without explicitly passing a provider, Terraform defaults to the currently logged-in AWS account, which can cause resources to be created or updated in the wrong account.

Is there a way to:

  • Display or log the AWS account ID that Terraform/CDKTF is targeting during the plan/diff phase, and

  • Optionally, fail or warn if the account doesn’t match an expected one?

Looking for best practices or patterns to make account visibility safer in multi-account CDKTF setups.

Hi @CodegeassBala,

The hashicorp/aws provider has a configuration option allowed_account_ids where you can specify one or more AWS account ids that a specific instance of the provider is allowed to interact with. If someone provides credentials for a different account then the initialization of the provider will fail with an error.

Depending on which CDK for Terraform language you are using, you might need to spell that option as allowedAccountIds instead.

But if we do not specify an allowedAccountIds it simply applies them to the current logged in account right?
In either of the cases it would be nice if we can show the accountId to which the changes are being applied to for better clarity ig.

If you want to do something more complex than the feature built in to the hashicorp/aws provider then a different approach is to use the aws_caller_identity data source. This gives your module access to the account id so you can use it in whichever way you like, within the bounds of the Terraform language.

For example, to mention the account id as part of the plan output you could declare an output value for it:

data "aws_caller_identity" "current" {}

output "account_id" {
  value = data.aws_caller_identity.current.account_id
}

Or you can reimplement something like the “allowed account ids” feature from the provider using a postcondition:

data "aws_caller_identity" "current" {
  lifecycle {
    postcondition {
      condition     = contains([123456], self.account_id)
      error_message = "Unacceptable AWS account id."
    }
  }
}

…though to make this truly equivalent to the provider feature you’d need to make sure that your resources all depend directly or indirectly on this data source result, so that Terraform understands that it needs to perform this check before attempting to plan any other resources.

I’ve written this in native Terraform syntax because I’m afraid I’m not very familiar with the CDK for Terraform conventions. Hopefully you can adapt these examples into your chosen CDK for Terraform language if you’d like to try these techniques.