1

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",
cosmos-1905-14
  • 783
  • 2
  • 12
  • 23
  • @mkrieger1 unfortunately not. I'm basically trying to do this inside of add_resource function parameters. I get this "if" is not definedPylancereportUndefinedVariable https://github.com/cloudtools/troposphere/blob/master/troposphere/s3.py#L475 – cosmos-1905-14 Jun 25 '21 at 14:49
  • That's because you didn't use it correctly. `BucketName="bucket1" if 2>1 else "bucket2"` would be the correct syntax. – mkrieger1 Jun 25 '21 at 16:08

1 Answers1

2

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?

Florian Fasmeyer
  • 795
  • 5
  • 18