Hello,
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.
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 imports.aws import AwsProvider
from imports.terraform_aws_modules.aws 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 ["10.0.0.0/24"] for 'vpc-dev' and
# ["10.0.0.0/24", "10.0.1.0/24", "10.0.2.0/24"] for 'vpc-prod'
Vpc(self, 'CustomVpc',
name='custom-vpc',
cidr='10.0.0.0/16',
azs=azs,
public_subnets=subnets
)
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(","))
app.synth()
Hope that helps!
Ansgar