CDK python aws - Global variables for all stacks


Can someone provide me with an example of global variables distributed through all stacks ? For example a region. I cannot find an easy and clean way to do this. For now i can only use variables that are declared inside the constructor of a stack

Hi @victorangelov1!

Which language are you using the CDKTF with? Depending on your use-case (when is the region determined? At synth time / at run time?) you could either use whatever your language offers or use Terraform Variables and build your constructs in a way that re-uses them.

If you have a small example of e.g. two stacks (some mock code) that would help to understand the problem a bit better.

  • Ansgar

Hey @ansgarm. Thank you for the reply. I am using Python and wanted to understand if TerraformVariable is the only and best way to go, but i guess i can just use some pure python console input.
I was wondering what is the best approach to do some conditional resources. For example if you chose 3 az’s instead of 2 and now you need 6 (3 private, 3 public) subnets instead of 4 (2 private, 2 public). TerraformVariable is not a good way to approach that because the value of it is not usable in pythonic if statements until terraform populates it on apply or plan. I am just playing arround trying to see if the python cdk is good enough to start a project on it without hitting a wall somewhere.

Hi @victorangelov1,

using what Python offers is perfectly fine – you could also read some environment variable to ensure that it also works without user input (e.g. in CI systems).

Regarding the AZ question: That depends if they are in the same stack or not. For AZs and subnets I’d assume that they live usually in the same “VPC” stack.

If you want to use different sets of availability zones that could for example differ between dev and prod environments, you could use standard Python control flow (i.e. mapping over a list of az’s) to instantiate a different amount of resources depending on how many AZ’s you got.

Some example code below that should work (my Python is a bit rusty):

#!/usr/bin/env python
from constructs import Construct
from cdktf import App, TerraformStack
from import AwsProvider
from import Vpc

class VpcStack(TerraformStack):
    def __init__(self, scope: Construct, ns: str, azs: list[str]):
        super().__init__(scope, ns)

        AwsProvider(self, 'Aws', region='eu-central-1')

        subnets = [f"10.0.{x}.0/24" for x in range(len(azs))]
        # will return [""] for 'vpc-dev' and
        # ["", "", ""] for 'vpc-prod'
        Vpc(self, 'CustomVpc',

app = App()
VpcStack(app, "vpc-dev", ["us-east-1a"])
VpcStack(app, "vpc-prod", ["us-east-1a", "us-east-1b", "us-east-1c"])

# could also be (to read from env)
VpcStack(app, "vpc", os.environ("VPC_AVAILABILITY_ZONES").split(","))


Hope that helps!