6
votes

Can I define tags as a parameter in parameters section AWS CloudFormation template and use it in each created resource?

My current template:

AWSTemplateFormatVersion: 2010-09-09
Description: "Some information"
Parameters:
  Test1:
    Type: String
    Description: Test1
    Default: t1
  Test2:
    Type: String
    Description: Test2
    Default: t2

...

LBSecurityGroup:
Type: "AWS::EC2::SecurityGroup"
Properties:
  GroupDescription: "Enable access to app loadbalancer"
  Tags:
    - Key: Name
      Value: !Join
        - ""
        - - !Ref Test1
          - !Ref Test2
    - Key: Test1
      Value: !Ref Test1
    - Key: Test2
      Value: !Ref Test2

I use the same tags for any other resourses(AWS::ElasticLoadBalancing::LoadBalancer, AWS::AutoScaling::AutoScalingGroup etc.), and it seems like duplicated code (each time when I create a new resource). Can I craft something like this?:

AWSTemplateFormatVersion: 2010-09-09
Description: "Some information"
Parameters:
  Test1:
    Type: String
    Description: Test1
    Default: t1
  Test2:
    Type: String
    Description: Test2
    Default: t2
  Tag:
    #define all tags, which I created above 

...

LBSecurityGroup:
Type: "AWS::EC2::SecurityGroup"
Properties:
  GroupDescription: "Enable access to app loadbalancer"
  Tags: !Ref Tag

...

Unfortunately, I didn't find any information about it on https://docs.aws.amazon.com/

1
You could perhaps use an include transform to do this. But I think that's an ugly solution, so not an answer. - kdgregory

1 Answers

5
votes

You could apply your tags to the stack instead and they will propagate to the resources.

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html

All stack-level tags, including automatically created tags, are propagated to resources that AWS CloudFormation supports. Currently, tags are not propagated to Amazon EBS volumes that are created from block device mappings.

For example:

aws cloudformation create-stack --stack-name my-stack
                                --template-url <template>
                                --parameters ParameterKey=Param1,ParameterValue=Value1
                                --tags Key=Tag1,Value=Value1