pythonaws-cloudformationtroposphere

Is there any workaround to use if statement in troposphere templates?


I'm trying to add an if statement in add_resource of troposphere, but I can't. Is there any workaround to do so?

s3_bucket = t.add_resource(Bucket(
    "MyBucket",
    if 2>1:
       BucketName="bucket1",
    else:
       BucketName="bucket2",
    CorsConfiguration=CorsConfiguration(
        "CorsConfiguration",
        CorsRules=[CorsRules(
            "AllowOrganization",
            AllowedMethods=["GET"],
            AllowedOrigins=["*"],
        )]
    ),
    Tags=Tags(
        Environment="aa",
    )
))

Edit:

I tried to use ternary operators as well, but it didn't work.

BucketName= if 2 > 1: "bucket2" else: "bucket3",

Solution

  • if you want to control the parameters, then you can do your if-statement before the function.

    if 2 > 1:
        BucketName="bucket1"
    else:
        BucketName="bucket2"
    
    s3_bucket = t.add_resource(Bucket(
            "MyBucket",
            BucketName,
            ...
        ))
    

    Or you can use ternary operators:

    s3_bucket = t.add_resource(Bucket(
            "MyBucket",
            "bucket1" if 2 > 1 else "bucket2",
            ...
        ))
    

    Note: 2 > 1 will always be true. But I guess you will replace 2 with a variable?