I have created the following vpc class using python aws cdk, I need help understanding how to dynamicaly set the env variable through self.node.try_get_context('env') to represent the environment where the stack will be deployed, for example prod,dev,stg etc. since I'm reusing it in my logic to formulate naming convention for the stack.
I have assigned env variables in the cdk.json as "env_stg": "stg", "env_prd": "prd",
I can call them individually but lack understanding calling them dynamically to affect my environments on the fly.
I really appreciate any help
class VPC(Stack):
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)
env = self.node.try_get_context('env')
self.vpc =ec2.Vpc(self, "Stg",
cidr = '10.0.0.0/16',
max_azs = 2,
enable_dns_support = True,
enable_dns_hostnames = True,
subnet_configuration = [
ec2.SubnetConfiguration(
name = 'Public',
subnet_type = ec2.SubnetType.PUBLIC,
cidr_mask = 24
),
ec2.SubnetConfiguration(
name = 'Isolated',
subnet_type = ec2.SubnetType.PRIVATE_ISOLATED,
cidr_mask = 24
)
]
)
# Store all private subnets in Parameter store
private_subnets = [subnet.subnet_id for subnet in self.vpc.private_subnets]
# public_subnets = [subnet.subnet_id for subnet in self.vpc.public_subnets]
count = 1
for subnets in private_subnets:
ssm.StringParameter(self, 'private-subnet-' str(count),
string_value = subnets,
parameter_name = '/' env '/pivate-subnet-' str(count)
)
count = 1
CodePudding user response:
You don't need new env vars or context. Stacks can introspect their Environment (= account region) at synth-time. Use Python's language features to derive account-specific labels from the Stack's account.
# vpc_stack.py
env_label = "stg"
if self.account == "123456789012":
env_label = "prod"
Even better, lift the label logic up to the app level, using the CDK-provided CDK_DEFAULT_ACCOUNT environment variable. Its value is set at synth-time based on the cli --profile flag value. Pass the labels down to the stacks in the stack props (kwargs). This way, configuration is more central, visible and resusable across stacks.
# app.py
account = os.environ["CDK_DEFAULT_ACCOUNT"]
env_label = "stg"
if account == "123456789012":
env_label = "prod"
You can get even fancier than this, but these are some basic patterns.
