动态将标签应用于AWS CloudFormation堆栈

时间:2019-10-28 15:26:22

标签: amazon-web-services amazon-cloudformation devops

我一直在寻找一种将标签动态应用到AWS CloudFormation Stack资源的方法。我找不到正确的答案。以下是我的CloudFormation堆栈资源。

AWSTemplateFormatVersion: '2010-09-09' 
Parameters: 
 ami:
  Type: String
 instanceType:
  Type: String
 blockdevice:
  Type: String
Resources: 
 ec2Stack: 
  Type: AWS::CloudFormation::Stack 
  Properties: 
   TemplateURL: !Sub "${s3ArtifactPath}/ec2/ec2-base-app.yml"
   Parameters:
     ami: !Ref ami
     instanceType: !Ref instanceType
     blockdevice: !Ref blockdevice
   Tags:
     - Key: sampleKey
       Value: sampleValue

我一直在尝试找到一种方法,该方法仅传递列表或仅引用 Tags 部分中的参数。这是我所做的

AWSTemplateFormatVersion: '2010-09-09' 
Parameters: 
 ami:
   Type: String
 instanceType:
   Type: String
   Default: nbs
   MinLength: 3
   MaxLength: 5
 blockdevice:
   Type: String
 tagsJsonList:
   Type: String
   Default: '[{"key1":"value1"}, {"key2":"value2"}]'
Resources: 
 ec2Stack: 
     Type: AWS::CloudFormation::Stack 
     Properties: 
       TemplateURL: !Sub "${s3ArtifactPath}/ec2/ec2-base-app.yml"
       Parameters:
         ami: !Ref ami
         instanceType: !Ref instanceType
         blockdevice: !Ref blockdevice
       Tags: !Ref tagsJsonList

我期望CloudFormation从变量中制定标签列表。其目的在于,我们将能够在列表中进行缩放,并且新标签的键值对将自动添加。这种方法行不通。

我还尝试了以下方法

AWSTemplateFormatVersion: '2010-09-09' 
Parameters: 
  ami:
    Type: String
  instanceType:
    Type: String
    Default: nbs
    MinLength: 3
    MaxLength: 5
  blockdevice:
    Type: String
Resources: 
  ec2Stack: 
      Type: AWS::CloudFormation::Stack 
      Properties: 
        TemplateURL: !Sub "${s3ArtifactPath}/ec2/ec2-base-app.yml"
        Parameters:
          ami: !Ref ami
          instanceType: !Ref instanceType
          blockdevice: !Ref blockdevice
        Tags:
          - Key: !Select [0, !Split ["=", !Select [0, !Split [",", !ImportValue someExport] ] ] ]
            Value: !Select [1, !Split ["=", !Select [0, !Split [",", !ImportValue someExport] ] ] ]

# someExport -->  k1=v1,k2=v2,k3=v3

  1. 这种方法的一个问题是我不能使用Sub内部函数使someExport变量动态化。
  2. 另一个问题是我必须为Key,Value语句编写多个语句以应用多个标签

1 个答案:

答案 0 :(得分:0)

我知道您已经开始使用它了,但是您可以尝试使用以下标记字符串:

'{"key1":"value1", "key2":"value2"}'