Sub topic 8
Conditional resources and properties
This chapter assumes you can read a YAML template, know the Parameters section and Ref, and have deployed a stack with the AWS CLI. It covers the Conditions section, the functions that build conditions, and the three places a condition can be used.
Why conditions exist
One template often serves several environments. A production bucket needs versioning and a development bucket does not. A production stack may need an alarm that a test stack would only make noisy. Conditions let you decide at deploy time whether a resource is created, or which value a property gets, without keeping two copies of the template.
A condition is a named Boolean. CloudFormation evaluates every condition when you create or update a stack, using the parameter values (and pseudo parameters) you supply. It then uses the results to include or skip parts of the template.
Declaring conditions
Conditions live in the Conditions section. Each entry has a name and an expression built from condition functions.
| Function | True when |
|---|---|
| `Fn::Equals` | Two values are equal |
| `Fn::Not` | The wrapped condition is false |
| `Fn::And` | All listed conditions are true (2 to 10 conditions) |
| `Fn::Or` | At least one listed condition is true (2 to 10 conditions) |
| `Fn::If` | Not a condition function. It picks one of two values, and is used in properties |
The following template declares three conditions.
Parameters:
EnvName:
Type: String
Default: dev
AllowedValues: [dev, staging, prod]
AlarmEmail:
Type: String
Default: ""
Conditions:
IsProd: !Equals [!Ref EnvName, prod]
NotProd: !Not [!Condition IsProd]
HasAlarmEmail: !Not [!Equals [!Ref AlarmEmail, ""]]
IsProdWithEmail: !And
- !Condition IsProd
- !Condition HasAlarmEmail!Condition refers to another condition by name. It works only inside the Conditions section and inside Fn::And, Fn::Or and Fn::Not. There is no Fn::NotEquals, so inequality is written as Fn::Not around Fn::Equals, as HasAlarmEmail shows.
Inside a condition you can use Ref to parameters and pseudo parameters, Fn::FindInMap, and other condition functions. You cannot reference a resource or use Fn::GetAtt, because conditions are evaluated before any resource exists.
Three places to use a condition
1. Whole resources and outputs
Put Condition: Name on a resource, and CloudFormation creates it only when the condition is true.
Resources:
AppBucket:
Type: AWS::S3::Bucket
AlarmTopic:
Type: AWS::SNS::Topic
Condition: HasAlarmEmail
Properties:
Subscription:
- Endpoint: !Ref AlarmEmail
Protocol: email
Outputs:
AlarmTopicArn:
Condition: HasAlarmEmail
Value: !Ref AlarmTopicThe output carries the same condition as the resource. Without it, the output would refer to a resource that may not exist, and the stack would fail validation.
2. Property values with Fn::If
Fn::If takes three items: a condition name, the value if true, the value if false. The condition name is written as a plain string, not with !Condition.
Resources:
AppBucket:
Type: AWS::S3::Bucket
Properties:
VersioningConfiguration:
Status: !If [IsProd, Enabled, Suspended]3. Removing a property with AWS::NoValue
Sometimes the false branch should mean "do not set this property at all". The pseudo parameter AWS::NoValue does that.
Resources:
AppTopic:
Type: AWS::SNS::Topic
Properties:
KmsMasterKeyId: !If [IsProd, alias/aws/sns, !Ref "AWS::NoValue"]When IsProd is false, CloudFormation behaves as if KmsMasterKeyId were absent from the template. This matters when an empty string would be invalid, or when the property has a default that you want to keep.
Dependencies on conditional resources
A resource that is not created cannot be referenced. If AlarmTopic is skipped, any !Ref AlarmTopic elsewhere has nothing to point to. The rule is that a resource may refer to a conditional resource only if it is created under the same condition, or if the reference sits inside an Fn::If branch that is chosen only when the target exists.
Resources:
QueueAlarm:
Type: AWS::CloudWatch::Alarm
Condition: HasAlarmEmail
Properties:
AlarmName: !Sub "${AWS::StackName}-queue-depth"
Namespace: AWS/SQS
MetricName: ApproximateNumberOfMessagesVisible
Statistic: Maximum
Period: 300
EvaluationPeriods: 1
Threshold: 100
ComparisonOperator: GreaterThanThreshold
AlarmActions:
- !Ref AlarmTopicQueueAlarm and AlarmTopic share HasAlarmEmail, so the reference is safe. If QueueAlarm had no condition, template validation would not necessarily fail. The stack would fail at deploy time when the topic was skipped.
Update behavior
Conditions are re-evaluated on every update. If a parameter change flips a condition from true to false:
- A resource guarded by that condition is deleted, subject to its
DeletionPolicy. - A property wrapped in
Fn::Ifchanges value, and the usual update behavior for that property applies (no interruption, some interruption, or replacement). - A property switched to
AWS::NoValueis removed, and the resource returns to the default for that property.
A flip from true to false can therefore destroy data. Preview with a change set before you apply it, and set DeletionPolicy: Retain or Snapshot on stateful conditional resources.
aws cloudformation create-change-set \
--stack-name demo \
--change-set-name drop-alarm \
--template-body file://template.yaml \
--parameters ParameterKey=AlarmEmail,ParameterValue=""
aws cloudformation describe-change-set \
--stack-name demo \
--change-set-name drop-alarmThe change set should list AlarmTopic and QueueAlarm with Action: Remove.
Common errors
- Referencing a skipped resource. Fix it by putting the same
Conditionon the referencing resource, or by wrapping the reference inFn::If. - Using
!Conditionin a property. It is not valid there. UseFn::Ifwith the condition name as a string. - Using a resource attribute in a condition. Conditions can only depend on parameters, mappings and pseudo parameters.
- Too many condition flags. Many stacked conditions make templates hard to read. If a template has a dozen, consider splitting it into separate stacks.
- Forgetting that parameters are strings. A
Numberparameter compared withFn::Equalsagainst a quoted value works, but write the value the same way each time to avoid surprises.
How it fits together
Exercise
A template has the condition HasKey: !Not [!Equals [!Ref KeyName, ""]]. An EC2 instance should set KeyName only when the parameter is non-empty, and otherwise leave the property out. Write the property line.
Show answer
KeyName: !If [HasKey, !Ref KeyName, !Ref "AWS::NoValue"]. When HasKey is false, AWS::NoValue removes the property, so CloudFormation does not send an empty key name.
Exercise
Why must an output that returns !Ref AlarmTopic carry the same Condition as the AlarmTopic resource?
Show answer
When the condition is false the topic is not created, so the output would refer to a resource that does not exist. Giving the output the same condition makes CloudFormation skip it too.