AWS CloudFormation Hands-On Guide
This step-by-step exercise will help you deploy a simple, production-style stack using CloudFormation: a VPC, public subnet, security group, an EC2 instance running a web server, and an S3 bucket. You will learn how to create, update, and delete stacks, use parameters and outputs, and validate changes with Change Sets.
Prerequisites
- An AWS account with permissions for VPC, EC2, S3, and IAM.
- AWS CLI installed and configured (aws configure).
- A key pair in your target region (or create one in EC2 > Key Pairs).
1) Create a basic template with parameters and outputs
Save the following YAML as web-stack.yaml. It creates:
- A VPC with an Internet Gateway and a public subnet
- A route to the internet
- A security group to allow HTTP
- An S3 bucket
- A t3.micro EC2 instance with UserData that installs nginx and serves a test page
AWSTemplateFormatVersion: '2010-09-09'
Description: Web stack with VPC, public subnet, EC2 nginx, and S3 bucket (hands-on demo)
Parameters:
KeyName:
Type: AWS::EC2::KeyPair::KeyName
Description: Name of an existing EC2 KeyPair to enable SSH access
InstanceType:
Type: String
Default: t3.micro
AllowedValues: [t3.nano, t3.micro, t3.small, t3.medium]
Description: EC2 instance type
BucketName:
Type: String
Description: Globally unique S3 bucket name
SSHLocation:
Type: String
Default: 0.0.0.0/0
Description: CIDR range to allow SSH (use your IP for better security)
LatestAmiId:
Type: AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>
Default: /aws/service/ecs/optimized-ami/amazon-linux-2/recommended/image_id
Mappings: {}
Resources:
VPC:
Type: AWS::EC2::VPC
Properties:
CidrBlock: 10.0.0.0/16
EnableDnsHostnames: true
EnableDnsSupport: true
Tags: [{ Key: Name, Value: demo-vpc }]
InternetGateway:
Type: AWS::EC2::InternetGateway
AttachIgw:
Type: AWS::EC2::VPCGatewayAttachment
Properties:
VpcId: !RefVPC
InternetGatewayId: !RefInternetGateway
PublicSubnet:
Type: AWS::EC2::Subnet
Properties:
VpcId: !RefVPC
CidrBlock: 10.0.1.0/24
MapPublicIpOnLaunch: true
AvailabilityZone: !Select [0, !GetAZs'']
Tags: [{ Key: Name, Value: demo-public-subnet }]
PublicRouteTable:
Type: AWS::EC2::RouteTable
Properties:
VpcId: !RefVPC
PublicRoute:
Type: AWS::EC2::Route
Properties:
RouteTableId: !RefPublicRouteTable
DestinationCidrBlock: 0.0.0.0/0
GatewayId: !RefInternetGateway
DependsOn: AttachIgw
PublicSubnetRouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
SubnetId: !RefPublicSubnet
RouteTableId: !RefPublicRouteTable
WebSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Enable HTTP and SSH
VpcId: !RefVPC
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 80
ToPort: 80
CidrIp: 0.0.0.0/0
- IpProtocol: tcp
FromPort: 22
ToPort: 22
CidrIp: !RefSSHLocation
WebBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !RefBucketName
WebInstanceProfileRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal: { Service: ec2.amazonaws.com }
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess
Tags: [{ Key: Name, Value: demo-web-role }]
WebInstanceProfile:
Type: AWS::IAM::InstanceProfile
Properties:
Roles: [!RefWebInstanceProfileRole]
WebInstance:
Type: AWS::EC2::Instance
Properties:
ImageId: !RefLatestAmiId
InstanceType: !RefInstanceType
KeyName: !RefKeyName
SubnetId: !RefPublicSubnet
SecurityGroupIds: [!RefWebSecurityGroup]
IamInstanceProfile: !RefWebInstanceProfile
UserData:
Fn::Base64: !Sub|
#!/bin/bash
yum update -y
amazon-linux-extras install -y nginx1
systemctl enable nginx
systemctl start nginx
echo "<h1>CloudFormation Demo - Instance ID: $(curl -s http://169.254.169.254/latest/meta-data/instance-id)</h1>" > /usr/share/nginx/html/index.html
Outputs:
WebsiteURL:
Description: Public URL of the web server
Value: !Sub"http://${WebInstance.PublicDnsName}"
BucketOutput:
Description: S3 bucket name
Value: !RefWebBucket
InstanceId:
Description: ID of the EC2 instance
Value: !RefWebInstance
Notes:
- LatestAmiId uses SSM Parameter for an ECS-optimized AL2 AMI. You can switch to Amazon Linux 2 parameter: /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.1-x86_64.
2) Validate and create the stack
Using AWS CLI:
# Validate the template
aws cloudformation validate-template --template-body file://web-stack.yaml
# Create the stack (replace values)
STACK_NAME=web-demo-stack
KEY_NAME=CHANGE_ME_KEYPAIR
BUCKET_NAME=CHANGE-ME-GLOBAL-UNIQUE-BUCKET
awscloudformationcreate-stack\
--stack-name$STACK_NAME\
--template-bodyfile://web-stack.yaml\
--capabilitiesCAPABILITY_NAMED_IAM\
--parameters\
ParameterKey=KeyName,ParameterValue=$KEY_NAME\
ParameterKey=BucketName,ParameterValue=$BUCKET_NAME\
ParameterKey=InstanceType,ParameterValue=t3.micro\
ParameterKey=SSHLocation,ParameterValue=$(curl-sifconfig.me)/32
Wait for completion:
aws cloudformation wait stack-create-complete --stack-name $STACK_NAME
aws cloudformation describe-stacks --stack-name $STACK_NAME --query "Stacks[0].Outputs"
3) Make a safe change using a Change Set
Example: tighten security group to allow HTTP only from your IP, or change instance type.
CHANGE_SET=web-change-1
aws cloudformation create-change-set \
--stack-name $STACK_NAME \
--change-set-name $CHANGE_SET \
--template-body file://web-stack.yaml \
--capabilities CAPABILITY_NAMED_IAM \
--parameters \
ParameterKey=KeyName,ParameterValue=$KEY_NAME \
ParameterKey=BucketName,ParameterValue=$BUCKET_NAME \
ParameterKey=InstanceType,ParameterValue=t3.small \
ParameterKey=SSHLocation,ParameterValue=$(curl -s ifconfig.me)/32
aws cloudformation wait change-set-create-complete --stack-name $STACK_NAME --change-set-name $CHANGE_SET
aws cloudformation describe-change-set --stack-name $STACK_NAME --change-set-name $CHANGE_SET
# Execute
awscloudformationexecute-change-set--stack-name$STACK_NAME--change-set-name$CHANGE_SET
awscloudformationwaitstack-update-complete--stack-name$STACK_NAME
4) Explore drift detection
If you manually change something (e.g., open port 443 in the SG), detect drift:
aws cloudformation detect-stack-drift --stack-name $STACK_NAME
aws cloudformation describe-stack-drift-detection-status --stack-drift-detection-id <DriftDetectionId>
aws cloudformation describe-stack-resource-drifts --stack-name $STACK_NAME
5) Clean up
Delete all resources by deleting the stack:
aws cloudformation delete-stack --stack-name $STACK_NAME
aws cloudformation wait stack-delete-complete --stack-name $STACK_NAME
If deletion fails due to the S3 bucket not being empty, empty it first:
aws s3 rm s3://$BUCKET_NAME --recursive
aws cloudformation delete-stack --stack-name $STACK_NAME
Extra: Parameterize AMIs with SSM and export outputs
- Use SSM Parameter Store to always fetch the latest AMI IDs.
- Export outputs so other stacks can import them:
Outputs:
VpcIdExport:
Value: !RefVPC
Export:
Name: !Sub"${AWS::StackName}-VpcId"
