A CloudFormation template is a JSON or YAML description of the AWS infrastructure you want. It is declarative: you specify the desired resources and configuration, rather than scripting each action or its order. CloudFormation handles dependencies and uses the template to create a stack—the running infrastructure described by that template. You can create multiple stacks from one template. section 4.5 section 4.5.2
A basic template has five parts:
- AWSTemplateFormatVersion identifies the format; Description records the template’s purpose. section 4.5.1
- Parameters accept values such as an instance type or database password, so one template can serve different needs. section 4.5.1
- Resources define what to create. Each resource has a name, type, and properties—for example, an EC2 instance and its instance type. section 4.5.1
- Outputs return useful details about created resources, such as an instance ID or public DNS name. section 4.5.1
Create and change a virtual machine
Define an EC2 instance whose InstanceType refers to a parameter, then create a stack from the template. If the team later needs more CPU power, change the instance type in the template and update the stack. This replaces the manual sequence of stopping the instance, waiting, changing its type, and starting it again with a desired-configuration change. section 4.5.2
Listing 4.16 A template to create an EC2 instance with CloudFormation
---
AWSTemplateFormatVersion: '2010-09-09'
Description: 'AWS in Action: chapter 4'
Parameters:
VPC: #1
Type: 'AWS::EC2::VPC::Id'
Subnet: #1
Type: 'AWS::EC2::Subnet::Id'
InstanceType: #2
Description: 'Select one of the possible instance types'
Type: String
Default: 't2.micro'
AllowedValues: ['t2.micro', 't2.small', 't2.medium']
Resources:
SecurityGroup: #1
Type: 'AWS::EC2::SecurityGroup'
Properties:
# [...]
VM: #3
Type: 'AWS::EC2::Instance'
Properties:
ImageId: 'ami-061ac2e015473fbe2'
InstanceType: !Ref InstanceType
IamInstanceProfile: 'ec2-ssm-core'
SecurityGroupIds: [!Ref SecurityGroup] #4
SubnetId: !Ref Subnet
Outputs:
InstanceId: #5
Value: !Ref VM
Description: 'Instance id (connect via Session Manager)'
Inspect the YAML EC2 example to see parameters, a security-group resource, and an instance whose type uses !Ref InstanceType. section 4.5.2
Templates also describe larger applications. A WordPress stack can create blogging infrastructure from a template selected in the AWS console. A Discourse template brings together a network, cache, database, and virtual machine; its stack can be created with the AWS CLI and checked through an output. Templates make repeatable test environments possible, but creating a stack provisions real resources: shut down temporary test infrastructure when finished. section 2.1 section 11.4 section 11.4.5 section 4.5
