在 Cloudformation 模板中删除 "Fn::join" 之前的空项

Remove empty item before "Fn::join" in Cloudformation template

我想用参数列表中的 Fn::Join 创建一个字符串,但我不知道如何忽略空参数。

如何忽略空参数以使用“application-dev”而不是“application---dev”?

比如我的参数是:

Parameters:
  AppName:
    Description: "Application name:"
    Type: String
    Default: "application"

  AppType:
    Description: "Application type:"
    Type: String
    Default: "" <----------------------------- This one can be empty !

  AppEnv:
    Description: "Application environment:"
    Type: String
    Default: "dev"

在我的资源中,我尝试:

Resources:
  S3BucketTest:
    Type: "AWS::S3::Bucket"
    Properties:
      BucketName: !Sub '${AppName}-${AppType}-${AppEnv}'
      Tags: 
        - Key: "Name"
          Value: !Join ['-', [!Ref AppName, !Ref AppType, !Ref AppEnv]]

顺便说一句,BucketName 是“application--dev”... Tag Name 是“application--dev”...

谢谢

您可以使用 !If!Equals 的组合:

Resources:
  S3BucketTest:
    Type: "AWS::S3::Bucket"
    Properties:
      BucketName: !If [!Equals ["", !Ref AppType], !Sub '${AppName}-${AppEnv}', !Sub '${AppName}-${AppType}-${AppEnv}']
      Tags: 
        - Key: "Name"
          Value: !If [!Equals ["", !Ref AppType], !Join ['-', [!Ref AppName, !Ref AppEnv], !Join ['-', [!Ref AppName, !Ref AppType, !Ref AppEnv]]