AWS CloudFormation - Infrastructure as Code
80 minAWS CloudFormation is a service that helps you model and set up AWS resources so you can spend less time managing those resources and more time focusing on your applications. CloudFormation treats infrastructure as code, enabling you to define your entire infrastructure in template files (JSON or YAML) that can be version controlled, reviewed, and reused. This approach brings software engineering best practices to infrastructure management.
CloudFormation templates describe the desired state of your AWS resources. Templates include parameters for customization, resources to create, outputs for returning values, and conditions for conditional resource creation. CloudFormation automatically handles resource dependencies, creating resources in the correct order. If stack creation fails, CloudFormation automatically rolls back changes, ensuring your infrastructure remains in a consistent state.
CloudFormation stacks are collections of AWS resources created from a template. You can create, update, or delete entire stacks as single units. Stack updates enable you to modify infrastructure incrementally, with CloudFormation determining what changes are needed. Change sets allow you to preview changes before applying them, reducing the risk of unintended modifications. Stack policies protect critical resources from accidental updates or deletions.
CloudFormation supports nested stacks, enabling you to break complex infrastructures into manageable, reusable components. Nested stacks promote code reuse and make templates more maintainable. Stack sets enable you to create, update, or delete stacks across multiple accounts and regions from a single operation, simplifying multi-account and multi-region deployments.
CloudFormation integrates with other AWS services and supports custom resources for resources not natively supported. Drift detection identifies when resources have been modified outside of CloudFormation, helping maintain infrastructure consistency. CloudFormation also supports importing existing resources into stacks, enabling you to adopt Infrastructure as Code for existing infrastructure.
Best practices for CloudFormation include using parameters for customization, organizing templates with nested stacks, validating templates before deployment, and using change sets for updates. CloudFormation enables consistent, repeatable infrastructure deployments, reduces human error, and makes infrastructure changes auditable. Understanding CloudFormation is essential for modern AWS operations and DevOps practices.
Key Concepts
- CloudFormation enables Infrastructure as Code for AWS resources.
- Templates define desired infrastructure state in JSON or YAML.
- Stacks are collections of resources created from templates.
- CloudFormation handles dependencies and rollbacks automatically.
- Change sets preview modifications before applying them.
Learning Objectives
Master
- Writing CloudFormation templates in YAML or JSON
- Creating and managing CloudFormation stacks
- Using parameters, conditions, and outputs in templates
- Implementing nested stacks and stack sets
Develop
- Understanding Infrastructure as Code principles
- Designing reusable, maintainable infrastructure templates
- Implementing DevOps practices for infrastructure management
Tips
- Use YAML for templates as it's more readable than JSON.
- Validate templates before deployment: aws cloudformation validate-template.
- Use change sets to preview updates before applying them.
- Organize complex infrastructure using nested stacks.
Common Pitfalls
- Not validating templates, causing deployment failures.
- Hardcoding values instead of using parameters, reducing template reusability.
- Not using change sets, applying unintended infrastructure changes.
- Not managing stack dependencies properly, causing deployment issues.
Summary
- CloudFormation enables Infrastructure as Code for AWS.
- Templates define infrastructure in version-controlled files.
- Stacks enable consistent, repeatable infrastructure deployments.
- CloudFormation automates dependency management and rollbacks.
Exercise
Create a CloudFormation template to deploy a complete web application stack.
# Create a CloudFormation template
cat > web-app-template.yaml << 'EOF'
AWSTemplateFormatVersion: '2010-09-09'
Description: 'Web application with EC2, RDS, and ALB'
Parameters:
KeyName:
Type: AWS::EC2::KeyPair::KeyName
Description: Name of an existing EC2 KeyPair
Resources:
VPC:
Type: AWS::EC2::VPC
Properties:
CidrBlock: 10.0.0.0/16
EnableDnsHostnames: true
EnableDnsSupport: true
Tags:
- Key: Name
Value: WebAppVPC
PublicSubnet1:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref VPC
CidrBlock: 10.0.1.0/24
AvailabilityZone: !Select [0, !GetAZs '']
MapPublicIpOnLaunch: true
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
Route:
Type: AWS::EC2::Route
DependsOn: AttachGateway
Properties:
RouteTableId: !Ref RouteTable
DestinationCidrBlock: 0.0.0.0/0
GatewayId: !Ref InternetGateway
SubnetRouteTableAssociation1:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
SubnetId: !Ref PublicSubnet1
RouteTableId: !Ref RouteTable
WebServerSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Enable HTTP and SSH access
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:
ImageId: ami-0c02fb55956c7d316
InstanceType: t2.micro
KeyName: !Ref KeyName
SecurityGroupIds:
- !Ref WebServerSecurityGroup
SubnetId: !Ref PublicSubnet1
UserData:
Fn::Base64: !Sub |
#!/bin/bash
yum update -y
yum install -y httpd
systemctl start httpd
systemctl enable httpd
echo "<h1>Hello from CloudFormation!</h1>" > /var/www/html/index.html
Outputs:
WebsiteURL:
Description: URL for the website
Value: !Sub http://${WebServer.PublicIp}
Export:
Name: !Sub "${AWS::StackName}-WebsiteURL"
EOF
# Deploy the CloudFormation stack
aws cloudformation create-stack \
--stack-name my-web-app \
--template-body file://web-app-template.yaml \
--parameters ParameterKey=KeyName,ParameterValue=my-key-pair
Exercise Tips
- Use AWS SAM (Serverless Application Model) for serverless CloudFormation templates.
- Validate templates locally: cfn-lint or AWS CloudFormation Linter.
- Use stack exports and imports to share resources between stacks.
- Enable stack termination protection for production stacks.