AWS Cloudformation将条件函数解释为资源属性

时间:2018-04-27 02:14:24

标签: amazon-web-services amazon-cloudformation

我对cloudformation模板有一种奇怪的行为。这是我的模板,我在其中创建了一个存储桶,并希望根据条件进行通知配置:

AWSTemplateFormatVersion: '2010-09-09'
Description: "Setup Artifacts Bucket"
Parameters:
  BucketName:
    Description: Name of the pipeline setup arctifact bucket
    Type: String 
    Default: "s3-pipeline-setup"
  NotificationCondition:
    Description: Conditionally add Notification configuration to the artifact bucket
    Type: String
    Default: false
Conditions:
  AddNotificationConfiguration: !Equals [ !Ref NotificationCondition, true ]

Resources:
  ArtifactBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Ref BucketName
      Fn::If:
        - AddNotificationConfiguration
        -
          NotificationConfiguration:
            LambdaConfigurations:
              -
                Function: "arn:aws:lambda:eu-west-1:341292222222227:function:lambda-ops-trigger-pipeline-setup"
                Event: "s3:ObjectCreated:*"
                Filter:
                  S3Key:
                    Rules:
                      -
                        Name: prefix
                        Value: "appstackcodes/"
                      -
                        Name: suffix
                        Value: "txt"
        - !Ref AWS::NoValue

当我尝试部署时,它会因此错误而失败:

  

0时28分10秒   UTC + 0200 CREATE_FAILED AWS :: S3 :: Bucket ArtifactBucket遭遇   不支持的属性Fn :: If

我真的不明白这件事..有人可以尝试让我知道那里的错误吗?

由于

1 个答案:

答案 0 :(得分:1)

不幸的是,你不能在cloudformation中做你想做的事。

Fn::If基本上只能用作三元表达式。 E.g。

key: Fn::If: [condition_name, value_if_true, value_if_false]

它不能像编程语言那样用作逻辑流程。有办法解决它。您实际上似乎已经发现了AWS::NoValue,因此只需将NotificationConfiguration分配移至if之外。

Resources:
  ArtifactBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Ref BucketName
      NotificationConfiguration:
        Fn::If:
          - AddNotificationConfiguration
          - LambdaConfigurations:
              -
                Function: "arn:aws:lambda:eu-west-1:341294322147:function:lambda-itops-trigger-pipeline-setup"
                Event: "s3:ObjectCreated:*"
                Filter:
                  S3Key:
                    Rules:
                      -
                        Name: prefix
                        Value: "appstackcodes/"
                      -
                        Name: suffix
                        Value: "txt"
          - !Ref AWS::NoValue

实际上,您始终会为NotificationConfiguration分配一些内容,但有时它会成为神奇的AWS::NoValue。这在大多数情况下都有效,尽管有时候这还不够,需要更多的创造力!