重用CloudFormation标记列表

时间:2017-09-26 11:29:47

标签: amazon-web-services amazon-cloudformation

我有一套相当复杂的CloudFormation模板,用于配置我们基础架构的不同环境。但是,我最近收到了使用相当广泛的标记列表(如15)标记创建的资源的请求。

将标签硬编码到每个模板文件中对我来说似乎不是一个好主意。我宁愿创建一次标记列表,并为每个可标记资源引用它们。问题是:我甚至不确定这是可能的。您知道可以实现可重复使用的标签列表吗?

我想写这个:

ECSAutoScalingGroup:
    Type: AWS::AutoScaling::AutoScalingGroup
    Properties: 
        ...
        Tags: !Ref ElTags

而不是

ECSAutoScalingGroup:
    Type: AWS::AutoScaling::AutoScalingGroup
    Properties: 
        ...
        Tags: !Ref ElTags
            - Key: Name
              Value: !Join ["-", [!Ref EnvironmentName, 'ecs-as-group'] ]
              PropagateAtLaunch: true
            - Key: TEAM
              Value: !Ref TeamName
              PropagateAtLaunch: true

2 个答案:

答案 0 :(得分:1)

如果不将标签传递给模板,而是在部署期间引用它们,则可以轻松地重用标签。标签将传播到堆栈的所有资源。与以下命令类似的命令可能会满足您的需求:

aws cloudformation create-stack --stack-name mystack \
--template-body file://my_template.yaml --tags file://my_tags.json

my_tags.json文件的格式为

[
    {"Key": "mytag", "Value": "val"},
    ...
]

或者,您可以通过CodePipeline部署堆栈,并在template configuration

中定义标签

答案 1 :(得分:0)

可以使用Fn::Transform函数和AWS宏AWS::Include来实现。

  

Fn::Transform指定用于对零件执行自定义处理的宏   堆栈模板

有关https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-transform.html上的Fn::Transform的更多信息

AWS::Include是一个AWS CloudFormation宏,可在模板中的任何位置插入代码段。

有关https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/create-reusable-transform-function-snippets-and-add-to-your-template-with-aws-include-transform.html上的AWS::Include的更多信息

您可以通过以下方式重复使用标签:

Resources:
  TestSG:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: 'SG for testing'
      GroupName: testSG
      SecurityGroupIngress:
        - CidrIp: '0.0.0.0/0'
          FromPort: 80
          IpProtocol: tcp
          ToPort: 80
      'Fn::Transform': 
        Name: AWS::Include 
        Parameters: 
          Location: 's3://bucket-name/tags.yaml'

  TestRole:
    Type: AWS::IAM::Role
    Properties: 
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action: sts:AssumeRole
      ManagedPolicyArns: 
        - 'arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess'
      RoleName: testRole
      'Fn::Transform': 
        Name: AWS::Include 
        Parameters: 
          Location: 's3://bucket-name/tags.yaml'

您的标签将位于不同的模板中,该模板将放置在S3存储桶上。 这是tags.yaml文件的内容:

Tags: 
  - Key: tag1
    Value: value1
  - Key: tag2
    Value: value2
  - Key: tag3
    Value: value3
  - Key: tag4
    Value: value4
  - Key: tag5
    Value: value5
  - Key: tag6
    Value: value6
  - Key: tag7
    Value: value7
  - Key: tag8
    Value: value8
  - Key: tag19
    Value: value9
  - Key: tag10
    Value: value10