Skip to main content

Managing AWS with CloudFormation and SSM

Define AWS infrastructure as code with CloudFormation, reach servers without SSH using Session Manager, and patch fleets with Systems Manager.

Overview and What You Will Learn

AWS CloudFormation creates, updates and deletes AWS resources from a template file, so every environment is built the same way and every change is reviewed in Git. AWS Systems Manager (SSM) then operates the servers you built: Session Manager gives a shell without SSH or open ports, Run Command executes scripts across many instances, and Patch Manager applies operating system patches on a schedule.

In this lab you will:

  • Write a template with parameters, a condition, an IAM role and an EC2 instance
  • Deploy it as a stack, preview an update with a change set and detect configuration drift
  • Protect data with DeletionPolicy and understand service roles and StackSets
  • Open a shell with Session Manager, run commands by tag, and scan for missing patches

Why This Matters in Production

Imagine a platform team at a company like Swiggy building a new microservice by hand in the console: a VPC, subnets, security groups, instances, a database and a load balancer. When staging is built the same way three weeks later, the two environments differ in small ways nobody wrote down, and one of them has a bug nobody can explain. A template removes that guesswork. Likewise, when a security patch must reach 200 instances before the weekend, Patch Manager applies it in parallel and reports exactly which instances failed, with no SSH sessions and no missed servers.

Core Principles

The template is the source of truth and the console only reflects it. A stack is one deployed copy of a template, and CloudFormation tracks every resource in it, so it can update only what changed and delete everything in the right order.

flowchart LR T[Template in Git] -->|create or update| S[CloudFormation stack] S --> R1[(Resources)] T -->|preview| C[Change set] C -->|review, then execute| S R1 -.->|manual edit| D{Drift detection} D -.-> S classDef code fill:#EDE9FE,color:#1E293B classDef cfn fill:#326CE5,color:#FFFFFF classDef res fill:#D1FAE5,color:#1E293B class T code class S,C,D cfn class R1 res

A template has these sections. Only Resources is required.

Section Purpose
Parameters Values supplied at deploy time
Mappings and Conditions Lookup tables and if-logic
Resources The AWS resources to create (required)
Outputs Values to display or export to other stacks

The intrinsic functions you will use most are !Ref (a parameter or resource), !Sub (string substitution), !GetAtt (a resource attribute), !FindInMap, !If, and !ImportValue (an export from another stack).

Systems Manager is a family of tools that all depend on the SSM Agent and an IAM role on the instance. The agent is preinstalled on Amazon Linux and recent Windows Server AMIs, and the managed policy AmazonSSMManagedInstanceCore gives the instance permission to talk to the service.

SSM tool What it does
Session Manager Shell access with no inbound ports or key pairs
Run Command Run a script on many instances at once
Patch Manager Scan and patch against a baseline
Parameter Store Configuration and secret values
Automation Multi-step runbooks on AWS resources
Maintenance Windows and State Manager Scheduled work and desired configuration

Detailed Step-by-Step Practical Lab

Milestone 1: Write the Template

Save this as lab-stack.yaml. It looks up the latest Amazon Linux AMI from a public SSM parameter instead of hardcoding an AMI ID, which would be wrong in other regions and goes stale.

YAML
AWSTemplateFormatVersion: "2010-09-09"
Description: DevOps Network lab - EC2 reachable only through SSM
Parameters:
Environment:
Type: String
Default: dev
AllowedValues: [dev, staging, prod]
InstanceType:
Type: String
Default: t3.micro
LatestAmiId:
Type: AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>
Default: /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64
Conditions:
IsProd: !Equals [!Ref Environment, prod]
Resources:
SsmRole:
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/AmazonSSMManagedInstanceCore
SsmInstanceProfile:
Type: AWS::IAM::InstanceProfile
Properties:
Roles: [!Ref SsmRole]
WebServer:
Type: AWS::EC2::Instance
Properties:
InstanceType: !Ref InstanceType
ImageId: !Ref LatestAmiId
IamInstanceProfile: !Ref SsmInstanceProfile
Monitoring: !If [IsProd, true, false]
Tags:
- Key: Name
Value: !Sub "devops-web-${Environment}"
- Key: Environment
Value: !Ref Environment
AssetsBucket:
Type: AWS::S3::Bucket
DeletionPolicy: Retain
UpdateReplacePolicy: Retain
Properties:
VersioningConfiguration:
Status: Enabled
Outputs:
InstanceId:
Description: EC2 instance ID
Value: !Ref WebServer
AssetsBucketName:
Description: Retained assets bucket
Value: !Ref AssetsBucket
Export:
Name: !Sub "${AWS::StackName}-AssetsBucket"

The role has no hardcoded name, so deploying needs only CAPABILITY_IAM. DeletionPolicy: Retain keeps the bucket when the stack is deleted, which is what you want for anything that holds data.

Bash
aws cloudformation validate-template --template-body file://lab-stack.yaml
Milestone 2: Deploy the Stack

deploy creates the stack if it is new and updates it if it exists.

Bash
export AWS_REGION=ap-south-1
aws cloudformation deploy \
--stack-name devops-lab-dev \
--template-file lab-stack.yaml \
--parameter-overrides Environment=dev \
--capabilities CAPABILITY_IAM
export INSTANCE_ID=$(aws cloudformation describe-stacks \
--stack-name devops-lab-dev \
--query "Stacks[0].Outputs[?OutputKey=='InstanceId'].OutputValue" \
--output text)
echo $INSTANCE_ID
# See the creation order and any failures
aws cloudformation describe-stack-events \
--stack-name devops-lab-dev \
--query "StackEvents[].[LogicalResourceId,ResourceStatus]" --output table
Milestone 3: Connect with Session Manager

Session Manager reaches the instance through the SSM service, so the instance needs no public IP, no port 22 and no key pair. You need the Session Manager plugin installed for the AWS CLI.

Bash
# Wait until the instance appears as a managed node (about a minute)
aws ssm describe-instance-information \
--query "InstanceInformationList[].[InstanceId,PingStatus]" --output table
aws ssm start-session --target $INSTANCE_ID

Inside the session, run whoami and hostname to confirm you are on the instance.

Who ran which API call is recorded in CloudTrail automatically. To record the commands typed in a session, you must enable session logging to S3 or CloudWatch Logs in Session Manager preferences. Instances in private subnets with no internet path need VPC endpoints for ssm, ssmmessages and ec2messages.

Security

Session Manager access is controlled by IAM. Grant ssm:StartSession only on the instances or tags a person needs, and consider requiring MFA, otherwise you have replaced SSH keys with an unrestricted shell.

Milestone 4: Run a Command on Many Instances

Run Command targets instances by ID or by tag, so the same call works for one server or five hundred.

Bash
COMMAND_ID=$(aws ssm send-command \
--document-name AWS-RunShellScript \
--targets Key=tag:Environment,Values=dev \
--parameters 'commands=["uptime","df -h /"]' \
--query "Command.CommandId" --output text)
aws ssm list-command-invocations \
--command-id $COMMAND_ID --details \
--query "CommandInvocations[].[InstanceId,Status,CommandPlugins[0].Output]" \
--output text

For large fleets add --max-concurrency 10% and --max-errors 5% so a bad command stops after a few failures instead of running everywhere.

Milestone 5: Scan for Missing Patches

Patch Manager compares instances to a patch baseline. Running the AWS-RunPatchBaseline document with Scan reports compliance without changing anything.

Bash
aws ssm send-command \
--document-name AWS-RunPatchBaseline \
--targets Key=tag:Environment,Values=dev \
--parameters Operation=Scan
# After it finishes
aws ssm describe-instance-patch-states \
--instance-ids $INSTANCE_ID \
--query "InstancePatchStates[].[InstanceId,MissingCount,FailedCount]" --output table

In production you do not run this by hand. You tag instances with a Patch Group value, attach a custom baseline to that group (for example critical security updates only, approved after a few days), and schedule Install inside a maintenance window. AWS Systems Manager Quick Setup can create this whole arrangement for an organization. Always patch staging first and let production follow once staging is healthy.

Milestone 6: Preview an Update with a Change Set

A change set shows exactly what CloudFormation will do before it does it. Add a ManagedBy tag to the instance in lab-stack.yaml first.

YAML
Tags:
- Key: Name
Value: !Sub "devops-web-${Environment}"
- Key: Environment
Value: !Ref Environment
- Key: ManagedBy
Value: CloudFormation
Bash
aws cloudformation create-change-set \
--stack-name devops-lab-dev \
--change-set-name add-managedby-tag \
--template-body file://lab-stack.yaml \
--capabilities CAPABILITY_IAM
aws cloudformation wait change-set-create-complete \
--stack-name devops-lab-dev --change-set-name add-managedby-tag
aws cloudformation describe-change-set \
--stack-name devops-lab-dev --change-set-name add-managedby-tag \
--query "Changes[].ResourceChange.[Action,LogicalResourceId,Replacement]" \
--output table
# Modify WebServer False
aws cloudformation execute-change-set \
--stack-name devops-lab-dev --change-set-name add-managedby-tag

Read the Replacement column carefully. True means the resource will be deleted and recreated. With the LatestAmiId parameter, a newer public AMI can make CloudFormation replace the instance on an unrelated update, which is a classic surprise. Pin the AMI value for production stacks, or build your own AMIs.

Milestone 7: Detect Drift

Drift detection compares real resources to the template. Change something outside CloudFormation and find it.

Bash
aws ec2 create-tags --resources $INSTANCE_ID --tags Key=Manual,Value=true
DRIFT_ID=$(aws cloudformation detect-stack-drift \
--stack-name devops-lab-dev --query StackDriftDetectionId --output text)
aws cloudformation describe-stack-drift-detection-status \
--stack-drift-detection-id $DRIFT_ID
aws cloudformation describe-stack-resource-drifts \
--stack-name devops-lab-dev \
--stack-resource-drift-status-filters MODIFIED

Fix drift by updating the template to match the change or by reverting the manual edit. Never leave it, because the next stack update may overwrite the change or fail.

Milestone 8: Understand Service Roles and StackSets

A CloudFormation service role lets CloudFormation create resources using a role's permissions, so a developer needs only permission to deploy stacks and to pass that role.

Bash
aws cloudformation deploy \
--stack-name devops-lab-dev \
--template-file lab-stack.yaml \
--role-arn arn:aws:iam::123456789012:role/cfn-deploy-role \
--capabilities CAPABILITY_IAM

StackSets deploy one template to many accounts and regions. With AWS Organizations you can use service-managed permissions and automatic deployment, so new accounts receive the baseline automatically.

Bash
aws cloudformation create-stack-set \
--stack-set-name security-baseline \
--template-body file://baseline.yaml \
--permission-model SERVICE_MANAGED \
--auto-deployment Enabled=true,RetainStacksOnAccountRemoval=false \
--capabilities CAPABILITY_IAM
aws cloudformation create-stack-instances \
--stack-set-name security-baseline \
--deployment-targets OrganizationalUnitIds=ou-abcd-12345678 \
--regions ap-south-1 ap-southeast-1

AWS Infrastructure Composer (formerly Application Composer) is a visual canvas that generates template YAML, useful for scaffolding and for understanding an existing template.

Milestone 9: Clean Up

Deleting the stack removes the instance, profile and role in the right order. The bucket survives because of Retain, so remove it yourself.

Bash
BUCKET=$(aws cloudformation describe-stacks --stack-name devops-lab-dev \
--query "Stacks[0].Outputs[?OutputKey=='AssetsBucketName'].OutputValue" --output text)
aws cloudformation delete-stack --stack-name devops-lab-dev
aws cloudformation wait stack-delete-complete --stack-name devops-lab-dev
aws s3 rb s3://$BUCKET --force

Production Best Practices & Common Pitfalls

  1. Change infrastructure only through templates. Manual edits cause drift and surprises on the next update.
  2. Always review a change set for production. Watch for Replacement: True on databases and instances.
  3. Retain stateful resources. Use DeletionPolicy and UpdateReplacePolicy on databases, buckets and volumes, and turn on stack termination protection for important stacks.
  4. Keep stacks small and layered. Network, data and application stacks update independently. Exports cannot be changed or removed while another stack imports them, so use them for stable values only.
  5. Prefer Session Manager to SSH. Close port 22, remove key pairs and log sessions.
  6. Patch in rings. Staging first, then production, inside a maintenance window.
  7. Validate in CI. Run cfn-lint and a change set on every pull request.
Common Mistake

Deleting a stack that contains a database or bucket without DeletionPolicy. CloudFormation deletes every resource in the stack, including the data inside them. Set Retain or Snapshot on anything you cannot recreate.

Tip

Use aws cloudformation deploy --no-execute-changeset in CI to produce a reviewable change set on every pull request, then execute it only after approval.

Remember

The template is the source of truth. If the console and the template disagree, the template is right and the console has drifted.

Quick Reference & Troubleshooting Commands

Command Description
aws cloudformation deploy Create or update a stack from a template file
aws cloudformation create-change-set Preview an update
aws cloudformation detect-stack-drift Start drift detection
aws cloudformation describe-stack-events See resource-level progress and errors
aws ssm start-session --target ID Open a Session Manager shell
aws ssm send-command Run a document on instances
aws ssm describe-instance-patch-states Show patch compliance
Symptom Likely cause and fix
ROLLBACK_COMPLETE on create A resource failed, read describe-stack-events, delete the stack and redeploy
Requires capabilities: [CAPABILITY_IAM] Template creates IAM resources, add the capability flag
Instance not in Session Manager Missing instance profile, agent not running, or no route or VPC endpoints to SSM
UPDATE_ROLLBACK_FAILED A resource could not roll back, fix the cause and use continue-update-rollback
Export cannot be deleted Another stack imports it, remove the import first

Resources

AWS Direct Connect vs VPN: Run Both as Failover

AWS Direct Connect vs VPN: Run Both as Failover

Run AWS Direct Connect as primary and Site-to-Site VPN as BGP failover. Size the backup, set route preference and test it before an outage does.

10 min read•Aug 2026
Lambda vs Fargate vs EC2 Spot: The Cost Crossover

Lambda vs Fargate vs EC2 Spot: The Cost Crossover

Lambda vs Fargate vs EC2 Spot, at the crossover where Lambda stops being cheaper — 2026 pricing, invocation thresholds, and interruption math.

5 min read•Aug 2026
Secrets Manager vs Parameter Store vs Vault

Secrets Manager vs Parameter Store vs Vault

Secrets Manager vs Parameter Store vs Vault: cost math, rotation, dynamic secrets and a decision flow, plus the Vault, IBM and OpenBao licensing context.

10 min read•Aug 2026
AWS VPC Security: Hardening Every Layer

AWS VPC Security: Hardening Every Layer

Harden your AWS VPC in layers: subnets, Security Groups, NACLs, Flow Logs, endpoints, and IAM conditions, with CLI examples for production.

10 min read•Jul 2026
Event-Driven Architecture on AWS Explained

Event-Driven Architecture on AWS Explained

Build event-driven systems on AWS with SQS, SNS, EventBridge and Kinesis: fan-out, DLQs, idempotent consumers and queue-based scaling.

11 min read•Jul 2026
S3 vs RDS vs DynamoDB: Choosing AWS Storage

S3 vs RDS vs DynamoDB: Choosing AWS Storage

Choosing S3, RDS, or DynamoDB wrong costs you in performance, cost, and scalability. Here is a practical decision guide based on your actual access patterns.

5 min read•Jul 2026
AWS Cost Optimisation: 8 Actions That Cut Bills

AWS Cost Optimisation: 8 Actions That Cut Bills

Cut your AWS bill without re-architecting: eight ordered steps from anomaly alerts and tagging to rightsizing, VPC endpoints, Savings Plans and Spot.

11 min read•Jul 2026
EC2 vs Lambda vs Fargate: Choosing AWS Compute

EC2 vs Lambda vs Fargate: Choosing AWS Compute

Choose between EC2, Lambda and Fargate using traffic shape, state and runtime limits, with worked cost break-evens instead of rules of thumb.

11 min read•Jul 2026

Explore More in AWS DevOps, Cost, and Machine Learning

All 6 Topics

Frequently Asked Questions

Is Managing AWS with CloudFormation and SSM free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Managing AWS with CloudFormation and SSM topic cover?

Define AWS infrastructure as code with CloudFormation, reach servers without SSH using Session Manager, and patch fleets with Systems Manager.

Found a mistake, an outdated step or a broken link?