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: ''
Next, we define a condition to easily check whether a non-default value was provided for the parameter:
Conditions: HasNoReleaseVersion: !Equals [!Ref ReleaseVersion, '']
Finally, we tie it all together on the resource by conditionally setting the
release tag depending on
Resources: MySecret: Properties: Tags: - Fn::If: - HasNoReleaseVersion - !Ref AWS::NoValue - Key: release - Value: !Ref ReleaseVersion
AWS::NoValue pseudo parameter will ensure the tag is not created unless a non-default value for the release version was provided.