DEV Community

derek lawless
derek lawless

Posted on • Updated on • Originally published at dereklawless.ie

Conditionally tagging resources in CloudFormation

While tagging resources in CloudFormation is straightforward, conditionally tagging them is a little non-obvious and requires use of conditions.

Use case: tagging a release version

I wanted the ability to conditionally tag a Secrets Manager secret with a release version when the secret was deployed into production. For lower environments, I didn't care / want to specify a release version.

First, we define a parameter that will contain the release version:

Parameters:
    ReleaseVersion:
        Type: String
        Description: The release version e.g. 1.2.3
        Default: ''
Enter fullscreen mode Exit fullscreen mode

Next, we define a condition to easily check whether a non-default value was provided for the parameter:

Conditions:
    HasNoReleaseVersion:
        !Equals [!Ref ReleaseVersion, '']
Enter fullscreen mode Exit fullscreen mode

Finally, we tie it all together on the resource by conditionally setting the release tag depending on the evaluation of HasNoReleaseVersion:

Resources:
    MySecret:
        Properties:
            Tags:
                - Fn::If:
                    - HasNoReleaseVersion
                    - !Ref AWS::NoValue
                    - Key: release
                    - Value: !Ref ReleaseVersion
Enter fullscreen mode Exit fullscreen mode

The AWS::NoValue pseudo parameter will ensure the tag is not created unless a non-default value for the release version was provided.

Top comments (0)