【问题标题】:Is there any workaround to use if statement in troposphere templates? [duplicate]是否有任何解决方法可以在对流层模板中使用 if 语句? [复制]
【发布时间】:2021-09-08 22:45:12
【问题描述】:

我正在尝试在对流层的add_resource 中添加一个if 语句,但我不能。有什么解决办法吗?

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",
    )
))

编辑:

我也尝试过使用三元运算符,但是没有用。

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

【问题讨论】:

  • @mkrieger1 不幸的是没有。我基本上是在 add_resource 函数参数中尝试这样做。我得到这个“如果”没有定义PylancereportUndefinedVariable github.com/cloudtools/troposphere/blob/master/troposphere/…
  • 那是因为你没有正确使用它。 BucketName="bucket1" if 2>1 else "bucket2" 是正确的语法。

标签: python amazon-cloudformation troposphere


【解决方案1】:

如果你想控制参数,那么你可以在函数之前做你的if语句。

if 2 > 1:
    BucketName="bucket1"
else:
    BucketName="bucket2"

s3_bucket = t.add_resource(Bucket(
        "MyBucket",
        BucketName,
        ...
    ))

或者你可以使用三元运算符:

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

注意:2 > 1 将始终为真。但我猜你会把 2 换成一个变量?

【讨论】:

  • 它没有用。我得到这个“如果”没有定义PylancereportUndefinedVariable
  • 删除您的代码(将其放在临时 txt 中)。运行打印('你好世界')。如果可行,只需编写一个简单的 if 语句并打印: if True: Print('hello world')。
  • 什么是 Pylancereport?我不认为存储桶是 Pylancereport。您的设置可能有问题
  • 我认为这是因为我试图在参数的 add.resource 函数中运行 if 语句。你知道对流层吗? github.com/cloudtools/troposphere/blob/master/troposphere/…
  • 你没有写对三元运算符:A if [condition] else B, you did if[condition] A else B. ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-17
  • 2012-10-10
  • 2020-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-26
相关资源
最近更新 更多