Conditional If and ENUM AWS CDK (Python)

Viewed 119

I just use CDK v2 for template generation. When I try to recreate Conditions with Enums I get an error.

Expected enum value, got {"$jsii.byref":"aws-cdk-lib.Intrinsic@10012"}

Example code:

    param_enableDeletionProtection = CfnParameter(self, "EnableDeletionProtection", 
        type="String",
        allowed_values=['True','False'],
        description="Whether critical services (like RDS) get provisioned with deletion protection or not")
condition_enable_deletion_protection = CfnCondition(self, "DeletionProtectionEnabled",
            expression=Fn.condition_equals(param_enableDeletionProtection.value_as_string, 'True')
    )
    cond_removal_policy=Fn.condition_if(condition_enable_deletion_protection.logical_id,
        RemovalPolicy.RETAIN,
        RemovalPolicy.DESTROY
    )
    s3_Bucket = s3.Bucket(self, "MyBucket",
        bucket_name="my-bucket-name",
        removal_policy=cond_removal_policy
    )

Am I doing something wrong? Or is this not supported?

1 Answers

Fn.condition_if is for digging into the guts of the cloudformation template, and will return a statement - not the RETAIN or DESTROY enum that this property is expecting. As you are using python, you can litterally just do this:

   cond_removal_policy=RemovalPolicy.RETAIN if some_condition_true else RemovalPolicy.DESTROY

This does mean that the condition needs to be set during synth which takes place before deployment. However, it seems you are already using parameter store for other things, you can continue to make use of that here and either use context variables (cdk deploy Stack\* -c a_variable_name=someValue) or other methods to determine what this should be at deployment time.

remember, CDK doesn't actually do anything with deployment. It ONLY synthesizes a CloudFormation template, then passes template off to cloudformation to deploy. So your code is never in effect during the deployment, only in creating the infrastructure. Anything you need to happen during the deployment should be handled either by a custom resource lambda or better yet a Pipeline. Anything after has to be a custom resource. Anything that can occur before beginning deployment can be handled inside CDK stacks (such as discovering information to set up the properties of given resources)

Related