Using Conditions within CloudFormation Templates for property overrides

Overriding properties within CloudFormation Templates using Conditions & Defaults

Table Of Contents

Today I Explained

CloudFormation doesn’t support any mechanisms that allows for modifying individual properties of resources in a deployed stack within AWS, which is why in the case of hotfixes you’ll often see a CloudFormation Template modified using the CloudFormation Web Designer. This constraint is why you’ll often see CloudFormation Templates with blank parameters (or a constant like None) for things like (Min|Max)Size, InstanceType, or naming parameters such as fully qualified domain names (FQDNs).

This works by having a CloudFormation Parameter which has a default value, and if that parameter is ever set, it is used in-place of the default configuration. In some cases, the default value is something guaranteed to fail a deployment if used.

Parameters:
  MinSize:
    Description: Override the default minimum autoscaling size.
    Type: String
    Default: ""
  # ...

Conditions:
  IsMinSizeDefault:
    Fn::Equals:
      - Ref: InstanceType
      - ""

The condition for the parameter, typically named Is{Param}Default or Is{Param}Empty, is used with the CloudFormation Fn::If for the properties to override.

Outputs:
  MinSize:
    Value:
      Fn::If:
        - IsMinSizeDefault
        - 1
        - Ref: InstanceType

A note on naming

A pattern where this excels is when working with on-demand testing (sometimes called preview) environments & fully qualified domain names (FQDN) in Route53. These environments will need unique names for the services they are provisioning, otherwise it wouldn’t be possible to deploy multiple environments in the same AWS Account.

Rather than requiring the framework responsible for creating the on-demand testing environments to specify the domain, the default behaviour of the CloudFormation Template can be a unique value. When the parameter is specified with a domain, that will be used instead of the uniquely generated one.

This is sometimes called flavour naming, vanity naming or production naming.

A note on Usability

Typically this isn’t done using handwritten CloudFormation Templates, but using a framework like AWS Cloud Development Kit (CDK), which makes auto-constructing the Condition, Parameter, and conditional usages less error prone.