CloudFormation Syntax and Templates
Introduction
CloudFormation uses YAML or JSON templates to define infrastructure. This chapter covers the syntax in detail and provides practical examples of templates.
Structure of a Template
# Complete structure of a CloudFormation template
AWSTemplateFormatVersion: "2010-09-09"
Description: >
Description of what the template does
(optional but recommended)
Metadata:
# Additional information (optional)
Parameters:
# Customizable input values (optional)
Mappings:
# Static key-value mappings (optional)
Conditions:
# Conditional logic (optional)
Transform:
# Macros or SAM (optional)
Resources:
# AWS resources to create (REQUIRED)
Outputs:
# Output values (optional)
Parameters Section
Basic Syntax
Parameters:
EnvironmentType:
Type: String
Default: dev
AllowedValues:
- dev
- staging
- prod
Description: Type of environment
InstanceType:
Type: String
Default: t3.micro
AllowedValues:
- t3.micro
- t3.small
- t3.medium
Description: EC2 instance type
KeyPairName:
Type: AWS::EC2::KeyPair::KeyName
Description: Name of the SSH key pair
VpcCidr:
Type: String
Default: 10.0.0.0/16
AllowedPattern: ^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\/([0-9]|[1-2][0-9]|3[0-2]))$
Description: VPC CIDR
AWS Parameter Types
Parameters:
# Basic types
StringParam:
Type: String
NumberParam:
Type: Number
MinValue: 1
MaxValue: 100
ListParam:
Type: List<Number>
CommaListParam:
Type: CommaDelimitedList
# Specific AWS types
EC2KeyPair:
Type: AWS::EC2::KeyPair::KeyName
SecurityGroupId:
Type: AWS::EC2::SecurityGroup::Id
SubnetId:
Type: AWS::EC2::Subnet::Id
VpcId:
Type: AWS::EC2::VPC::Id
AMIId:
Type: AWS::EC2::Image::Id
AvailabilityZone:
Type: AWS::EC2::AvailabilityZone::Name
# AWS lists
SubnetIds:
Type: List<AWS::EC2::Subnet::Id>
SecurityGroupIds:
Type: List<AWS::EC2::SecurityGroup::Id>
Resources Section
Resource Syntax
Resources:
LogicalResourceName:
Type: AWS::Service::Resource
Properties:
Property1: Value1
Property2: Value2
DependsOn:
- AnotherResource
DeletionPolicy: Retain | Delete | Snapshot
UpdateReplacePolicy: Retain | Delete | Snapshot
Condition: MyCondition
Common Resource Examples
VPC
Resources:
MyVPC:
Type: AWS::EC2::VPC
Properties:
CidrBlock: 10.0.0.0/16
EnableDnsHostnames: true
EnableDnsSupport: true
Tags:
- Key: Name
Value: MyVPC-Production
Subnet
PublicSubnet1:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref MyVPC
CidrBlock: 10.0.1.0/24
AvailabilityZone: !Select [0, !GetAZs '']
MapPublicIpOnLaunch: true
Tags:
- Key: Name
Value: Public-Subnet-1
Internet Gateway
InternetGateway:
Type: AWS::EC2::InternetGateway
Properties:
Tags:
- Key: Name
Value: MyIGW
AttachGateway:
Type: AWS::EC2::VPCGatewayAttachment
Properties:
VpcId: !Ref MyVPC
InternetGatewayId: !Ref InternetGateway
Security Group
WebSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Security group for web server
VpcId: !Ref MyVPC
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 80
ToPort: 80
CidrIp: 0.0.0.0/0
- IpProtocol: tcp
FromPort: 443
ToPort: 443
CidrIp: 0.0.0.0/0
- IpProtocol: tcp
FromPort: 22
ToPort: 22
CidrIp: 10.0.0.0/8
Tags:
- Key: Name
Value: Web-SG
EC2 Instance
WebServer:
Type: AWS::EC2::Instance
Properties:
InstanceType: !Ref InstanceType
ImageId: !Ref AMIId
KeyName: !Ref KeyPairName
SubnetId: !Ref PublicSubnet1
SecurityGroupIds:
- !Ref WebSecurityGroup
Tags:
- Key: Name
Value: WebServer-1
UserData:
Fn::Base64: !Sub |
#!/bin/bash
yum update -y
yum install -y httpd
systemctl start httpd
systemctl enable httpd
echo "Hello from ${AWS::StackName}" > /var/www/html/index.html
Intrinsic Functions
Ref
# Reference a parameter or resource
VpcId: !Ref MyVPC
InstanceType: !Ref ParameterInstanceType
# Long syntax
VpcId:
Ref: MyVPC
GetAtt
# Get an attribute of a resource
Outputs:
InstancePublicIP:
Value: !GetAtt WebServer.PublicIp
SecurityGroupId:
Value: !GetAtt WebSecurityGroup.GroupId
# Long syntax
Value:
Fn::GetAtt:
- WebServer
- PublicIp
Sub (Substitution)
# Variable substitution
UserData:
Fn::Base64: !Sub |
#!/bin/bash
echo "Region: ${AWS::Region}"
echo "Stack: ${AWS::StackName}"
echo "Instance: ${WebServer}"
# With custom variables
Value: !Sub
- "arn:aws:s3:::${BucketName}/*"
- BucketName: !Ref MyBucket
Join
# Join elements with a separator
Value: !Join
- ","
- - subnet-12345
- subnet-67890
- subnet-abcde
# Result: "subnet-12345,subnet-67890,subnet-abcde"
# Short syntax
Value: !Join [",", [!Ref Subnet1, !Ref Subnet2]]
Select
# Select an element from a list
AvailabilityZone: !Select
- 0
- !GetAZs ''
# Selects the first AZ of the region
Split
# Split a string
Value: !Select
- 0
- !Split [",", "a,b,c"]
# Result: "a"
If (Condition)
Conditions:
IsProd: !Equals [!Ref Environment, prod]
Resources:
MyInstance:
Type: AWS::EC2::Instance
Properties:
InstanceType: !If
- IsProd
- m5.large
- t3.micro
GetAZs
# Get the AZs of a region
AvailabilityZones: !GetAZs '' # Current region
AvailabilityZones: !GetAZs 'us-east-1' # Specific region
Conditions Section
Parameters:
Environment:
Type: String
AllowedValues: [dev, staging, prod]
Conditions:
IsProd: !Equals [!Ref Environment, prod]
IsNotProd: !Not [!Equals [!Ref Environment, prod]]
IsProdOrStaging: !Or
- !Equals [!Ref Environment, prod]
- !Equals [!Ref Environment, staging]
IsProdAndMultiAZ: !And
- !Equals [!Ref Environment, prod]
- !Equals [!Ref MultiAZ, true]
Resources:
ProdOnlyResource:
Type: AWS::EC2::Instance
Condition: IsProd # Created only if IsProd is true
Properties:
# ...
Mappings Section
Mappings:
RegionAMI:
us-east-1:
HVM64: ami-0123456789abcdef0
HVM32: ami-0123456789abcdef1
us-west-2:
HVM64: ami-abcdef0123456789a
HVM32: ami-abcdef0123456789b
eu-west-1:
HVM64: ami-fedcba9876543210f
HVM32: ami-fedcba9876543210e
EnvironmentConfig:
dev:
InstanceType: t3.micro
MinSize: 1
MaxSize: 2
prod:
InstanceType: m5.large
MinSize: 2
MaxSize: 10
Resources:
MyInstance:
Type: AWS::EC2::Instance
Properties:
ImageId: !FindInMap [RegionAMI, !Ref "AWS::Region", HVM64]
InstanceType: !FindInMap [EnvironmentConfig, !Ref Environment, InstanceType]
Outputs Section
Outputs:
VpcId:
Description: ID of the created VPC
Value: !Ref MyVPC
Export:
Name: !Sub "${AWS::StackName}-VpcId"
PublicSubnetId:
Description: ID of the public subnet
Value: !Ref PublicSubnet1
Export:
Name: !Sub "${AWS::StackName}-PublicSubnetId"
WebServerPublicIP:
Description: Public IP of the web server
Value: !GetAtt WebServer.PublicIp
Condition: IsProd # Conditional output
WebsiteURL:
Description: Website URL
Value: !Sub "http://${WebServer.PublicDnsName}"
Complete Example Template
AWSTemplateFormatVersion: "2010-09-09"
Description: Simple web infrastructure with VPC, EC2, and Security Group
Parameters:
Environment:
Type: String
Default: dev
AllowedValues: [dev, staging, prod]
Description: Deployment environment
InstanceType:
Type: String
Default: t3.micro
AllowedValues: [t3.micro, t3.small, t3.medium]
KeyName:
Type: AWS::EC2::KeyPair::KeyName
Description: SSH key pair
Mappings:
RegionAMI:
us-east-1:
AMI: ami-0123456789abcdef0
ca-central-1:
AMI: ami-0abcdef1234567890
Conditions:
IsProd: !Equals [!Ref Environment, prod]
Resources:
VPC:
Type: AWS::EC2::VPC
Properties:
CidrBlock: 10.0.0.0/16
EnableDnsHostnames: true
Tags:
- Key: Name
Value: !Sub "${Environment}-VPC"
PublicSubnet:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref VPC
CidrBlock: 10.0.1.0/24
MapPublicIpOnLaunch: true
Tags:
- Key: Name
Value: !Sub "${Environment}-Public-Subnet"
InternetGateway:
Type: AWS::EC2::InternetGateway
AttachGateway:
Type: AWS::EC2::VPCGatewayAttachment
Properties:
VpcId: !Ref VPC
InternetGatewayId: !Ref InternetGateway
RouteTable:
Type: AWS::EC2::RouteTable
Properties:
VpcId: !Ref VPC
PublicRoute:
Type: AWS::EC2::Route
DependsOn: AttachGateway
Properties:
RouteTableId: !Ref RouteTable
DestinationCidrBlock: 0.0.0.0/0
GatewayId: !Ref InternetGateway
SubnetRouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
SubnetId: !Ref PublicSubnet
RouteTableId: !Ref RouteTable
SecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Web Server Security Group
VpcId: !Ref VPC
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 80
ToPort: 80
CidrIp: 0.0.0.0/0
- IpProtocol: tcp
FromPort: 22
ToPort: 22
CidrIp: 0.0.0.0/0
WebServer:
Type: AWS::EC2::Instance
Properties:
InstanceType: !If [IsProd, t3.small, !Ref InstanceType]
ImageId: !FindInMap [RegionAMI, !Ref "AWS::Region", AMI]
KeyName: !Ref KeyName
SubnetId: !Ref PublicSubnet
SecurityGroupIds:
- !Ref SecurityGroup
Tags:
- Key: Name
Value: !Sub "${Environment}-WebServer"
UserData:
Fn::Base64: !Sub |
#!/bin/bash
yum update -y
yum install -y httpd
systemctl start httpd
echo "<h1>Env: ${Environment}</h1>" > /var/www/html/index.html
Outputs:
VpcId:
Value: !Ref VPC
Export:
Name: !Sub "${AWS::StackName}-VpcId"
WebServerIP:
Value: !GetAtt WebServer.PublicIp
Description: Public IP of the server
WebsiteURL:
Value: !Sub "http://${WebServer.PublicDnsName}"
Description: Website URL
Summary
- A template has a defined structure with mandatory Resources
- Parameters allow customization at deployment
- Intrinsic functions (!Ref, !GetAtt, !Sub, etc.) for referencing
- Conditions to create resources conditionally
- Mappings for static values by region/environment
- Outputs to export values
Next section: Validation Quiz