CloudFormation : Conditions

Conditions in CF template allows control of resource condition based on certain conditions. Example: create resource based on region (us-east-1/ap-southeast-2) or some input parameter (test/prod)

In the below template, the resource is created only if the region is equal to "us-east-1"

AWSTemplateFormatVersion: 2010-09-09
Description: Conditions Demo - CF Template

Conditions: 

  USAResource: !Equals 
    - !Ref "AWS::Region"
    - "us-east-1"

Resources: 
  AppServer001:
    Type: 'AWS::EC2::Instance'
    Condition: USAResource
    Properties:
       ImageId: "ami-0022f774911c1d690"
       InstanceType: "t2.micro"
       Tags:
         -  Key: "Name"
            Value: "AppServer01"

Outputs:
  PublicIp:
    Condition: USAResource
    Description: Server Public IP
    Value: !GetAtt AppServer001.PublicIp

We could use the below functions for condition evaluation:

  • Fn::And
  • Fn::Equals
  • Fn::If
  • Fn::Not
  • Fn::Or

Now, if the above script is executed in any other region than us-east-1, the resource is not created as the condition fails.

2022-06-10 08_52_20-54.66.203.169 (ec2-user).png

The ec2 resource is created only if the region is equals us-east-1 as below.

2022-06-10 08_55_40-54.66.203.169 (ec2-user).png

2022-06-10 07_03_02-CloudFormation - Stack conditionstack.png