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
DeletionPolicyand 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.
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.
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.
aws cloudformation validate-template --template-body file://lab-stack.yamlMilestone 2: Deploy the Stack
deploy creates the stack if it is new and updates it if it exists.
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 failuresaws cloudformation describe-stack-events \ --stack-name devops-lab-dev \ --query "StackEvents[].[LogicalResourceId,ResourceStatus]" --output tableMilestone 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.
# 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_IDInside 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.
SecuritySession Manager access is controlled by IAM. Grant
ssm:StartSessiononly 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.
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 textFor 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.
aws ssm send-command \ --document-name AWS-RunPatchBaseline \ --targets Key=tag:Environment,Values=dev \ --parameters Operation=Scan # After it finishesaws ssm describe-instance-patch-states \ --instance-ids $INSTANCE_ID \ --query "InstancePatchStates[].[InstanceId,MissingCount,FailedCount]" --output tableIn 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.
Tags: - Key: Name Value: !Sub "devops-web-${Environment}" - Key: Environment Value: !Ref Environment - Key: ManagedBy Value: CloudFormationaws 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-tagRead 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.
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 MODIFIEDFix 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.
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_IAMStackSets 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.
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-1AWS 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.
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-devaws cloudformation wait stack-delete-complete --stack-name devops-lab-dev aws s3 rb s3://$BUCKET --forceProduction Best Practices & Common Pitfalls
- Change infrastructure only through templates. Manual edits cause drift and surprises on the next update.
- Always review a change set for production. Watch for
Replacement: Trueon databases and instances. - Retain stateful resources. Use
DeletionPolicyandUpdateReplacePolicyon databases, buckets and volumes, and turn on stack termination protection for important stacks. - 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.
- Prefer Session Manager to SSH. Close port 22, remove key pairs and log sessions.
- Patch in rings. Staging first, then production, inside a maintenance window.
- Validate in CI. Run
cfn-lintand a change set on every pull request.
Common MistakeDeleting a stack that contains a database or bucket without
DeletionPolicy. CloudFormation deletes every resource in the stack, including the data inside them. SetRetainorSnapshoton anything you cannot recreate.
TipUse
aws cloudformation deploy --no-execute-changesetin CI to produce a reviewable change set on every pull request, then execute it only after approval.
RememberThe 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 |