Introduction to CloudFormation
- CloudFormation is a service that allows you to manager, configure, and provision your AWS infrastructure as code.
- Resources are defined using a CloudFormation template.
- CloudFormation interprets the template and makes the appropriate API calls to create the resources you have defined.
- Supports YAML or JSON
Benefits of CloudFormation
- Infrastructure is provisioned consistently, with fewer mistakes
- Less time and effort than configuring things manually
- You can version control and peer review your templates
- Free to use (charged for what you create)
- Can be used to manage updates and dependencies
- Can be used to rollback and delete the entire stack as well.
CloudFormation Template
- YAML or JSON template used to describe the endstate of infrastructure you are either provisioning or changing.
- After creating the template, you upload it to CloudFormation using S3.
- CloudFormation reads the template and makes the API calls on your behalf.
- The resulting resources are called a stack.
Example Template
AWSTemplateFormatVersion: "2010-09-09"
Description: "Template to create an EC2 instance"
Metadata:
Instances:
Description: "Web Server Instance"
Parameters: #input values
EnvType:
Description: "Environment type"
Type: String
AllowedValues:
- prod
- test
Conditions:
CreateProdResources: !Equals [ !Ref EnvType, prod ]
Mappings: #e.g. set values based on region
RegionMap:
eu-west-1:
"ami":"ami-394534954395e"
Transform: # include snippets of code outside the main template
Name: 'AWS::Include'
Parameters:
Location: "s3://MyAmazonS3BucketName/MyFileName.yaml"
Resources: # the AWS resources you are deploying
EC2Instance:
Type: AWS::EC2::Instance
Properties:
InstanceType: t2.micro
ImageId: ami-Odb1d6c9349334334c"
Outputs:
InstanceID:
Description: The Instance ID
Value: !Ref EC2Instance
- Resources is the only mandatory section of the CloudFormation template
-
Remember that the Transform section is used to reference additional code stored in S3, allowing for code re-use, e.g. for Lambda code or template snippets / reusale pieces of CloudFormation code.
-
CloudFormation allows you to manage, configure, and provision AWS infrastructure as code (YAML / JSON).
- Remember the main sections in the Cloudformation Template:
- Parameters: input custom values
- Conditions: e.g. provision resources based on environment
- Resources: Mandatory; the AWS resources to create
- Mappigs: Create custom mappings like Region: AMI
- Transforms: Reference code located in S3 e.g. Lambda code or reusable snippets of CloudFormation code.