Pass tags as parameters in clouldformation

Viewed 108

I have created a simple template which i am going to use to create s3 buckets. My template looks like this.

Parameters:
  Environment:
    Type: String
    Default: prod
    AllowedPattern: '[a-z\-]+'
  BucketName:
    Type: String
    AllowedPattern: '[a-z\-]+'

Resources:
  Bucket:
    Type: AWS::S3::Bucket
    Properties: 
      BucketName: !Sub foo-${Environment}-${BucketName}
      Tags: 
        - Key: key_1
          Value: foo
        - Key: key_2
          Value: foo
    DeletionPolicy: Retain

I want to make a generic template and not create a different template each time a i create an s3 bucket. Only thing that will vary between my s3 buckets is the # of tags i add to it. Some S3 buckets may have 2 tags and others may have more. At the most i will have 5 tags to my s3 bucket. So i am wondering if there is a way to pass tags through parameter such that if i pass 3 tags , 3 tags get created, if i pass 2 tags 2 tags get created.

1 Answers

At the most i will have 5 tags

Then you need 5 parameters:

  Tag1:
    Type: CommaDelimitedList
    Default: ""
  # ....
  Tag5:
    Type: CommaDelimitedList
    Default: ""

and 5 conditions:

Conditions:
  HasTag1:
   !Not [!Equals [!Ref Tag1, ""] ]
  # ...
  HasTag5:
   !Not [!Equals [!Ref Tag5, ""] ]

End then you use the conditions to populate your tags:

      Tags: 
        - !If 
          - HasTag1
          - Key: !Select [0, !Ref Tag1]
            Value: !Select [1, !Ref Tag1]
          - !Ref "AWS::NoValue"
        # ...  
        - !If 
          - HasTag5
          - Key: !Select [0, !Ref Tag5]
            Value: !Select [1, !Ref Tag5]
          - !Ref "AWS::NoValue"
Related