CloudFormation & IaC
Duration: 60 min
Infrastructure as Code (IaC) lets you define AWS resources in code instead of clicking the console. AWS CloudFormation is the native IaC service. It uses JSON or YAML templates to create and manage stacks of resources. This module covers templates, stacks, parameters, outputs, and drift detection.
CloudFormation Basics
CloudFormation is AWS's IaC service. You write a template describing resources (EC2, S3, RDS, etc.), and CloudFormation creates and manages them as a stack.
Templates are JSON or YAML files. CloudFormation handles dependencies, rollback on failure, and updates.
Template Structure
A CloudFormation template has these sections:
AWSTemplateFormatVersion specifies the template version (usually "2010-09-09").
Description explains the template.
Parameters are input values you provide when creating the stack.
Resources define the AWS resources to create.
Outputs return values from the stack (e.g., instance IP, database endpoint).
Mappings define lookup tables for conditional values.
Stack Operations
Create a stack from a template. CloudFormation provisions all resources.
Update a stack to change resources. CloudFormation applies changes with minimal downtime.
Delete a stack to remove all resources (with some exceptions like S3 buckets with data).
Drift detection identifies resources that were manually changed outside CloudFormation.
Hands-On: Create CloudFormation Stack
Create a template file (template.yaml):
AWSTemplateFormatVersion: '2010-09-09'
Description: 'Simple EC2 instance'
Parameters:
InstanceType:
Type: String
Default: t3.micro
Description: EC2 instance type
Resources:
MyInstance:
Type: AWS::EC2::Instance
Properties:
ImageId: ami-0c55b159cbfafe1f0
InstanceType: !Ref InstanceType
Tags:
- Key: Name
Value: MyInstance
Outputs:
InstanceId:
Value: !Ref MyInstance
Description: Instance ID
InstancePublicIp:
Value: !GetAtt MyInstance.PublicIp
Description: Public IP addressCreate the stack:
aws cloudformation create-stack --stack-name my-stack \
--template-body file://template.yaml \
--parameters ParameterKey=InstanceType,ParameterValue=t3.smallDescribe stack:
aws cloudformation describe-stacks --stack-name my-stackGet stack outputs:
aws cloudformation describe-stacks --stack-name my-stack \
--query 'Stacks[0].Outputs'Detect drift:
aws cloudformation detect-stack-drift --stack-name my-stack
aws cloudformation describe-stack-drift-detection-status \
--stack-drift-detection-id drift-idPython Boto3 Example
import boto3
import json
cf = boto3.client('cloudformation')
# Create stack
cf.create_stack(
StackName='my-stack',
TemplateBody=open('template.yaml').read(),
Parameters=[
{'ParameterKey': 'InstanceType', 'ParameterValue': 't3.micro'}
]
)
# Describe stack
response = cf.describe_stacks(StackName='my-stack')
for stack in response['Stacks']:
print(f"Status: {stack['StackStatus']}")
for output in stack.get('Outputs', []):
print(f"{output['OutputKey']}: {output['OutputValue']}")
# Update stack
cf.update_stack(
StackName='my-stack',
TemplateBody=open('template.yaml').read()
)
# Delete stack
cf.delete_stack(StackName='my-stack')Advanced Template Example
AWSTemplateFormatVersion: '2010-09-09'
Description: 'VPC with public and private subnets'
Parameters:
VpcCidr:
Type: String
Default: 10.0.0.0/16
Resources:
VPC:
Type: AWS::EC2::VPC
Properties:
CidrBlock: !Ref VpcCidr
PublicSubnet:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref VPC
CidrBlock: 10.0.1.0/24
AvailabilityZone: us-east-1a
InternetGateway:
Type: AWS::EC2::InternetGateway
AttachGateway:
Type: AWS::EC2::VPCGatewayAttachment
Properties:
VpcId: !Ref VPC
InternetGatewayId: !Ref InternetGateway
PublicRouteTable:
Type: AWS::EC2::RouteTable
Properties:
VpcId: !Ref VPC
PublicRoute:
Type: AWS::EC2::Route
Properties:
RouteTableId: !Ref PublicRouteTable
DestinationCidrBlock: 0.0.0.0/0
GatewayId: !Ref InternetGateway
Outputs:
VpcId:
Value: !Ref VPC
SubnetId:
Value: !Ref PublicSubnetTerraform Example
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = var.instance_type
tags = {
Name = "MyInstance"
}
}
variable "instance_type" {
type = string
default = "t3.micro"
}
output "instance_id" {
value = aws_instance.web.id
}
output "public_ip" {
value = aws_instance.web.public_ip
}Quiz 1
❓ What is CloudFormation?
Quiz 2
❓ What is a CloudFormation stack?
Quiz 3
❓ What is drift detection?
Quiz 4
❓ What are CloudFormation parameters?
Quiz 5
❓ What are CloudFormation outputs?