Run Command, Automation and State Manager
-
Phase 0: Before you start
-
Phase 1: The foundation
-
Phase 2: Operations and security
-
Phase 3: SQL Server on AWS
-
Phase 4: Troubleshooting step by step
-
Phase 5: Final project and career
Logging in to twenty servers one after another to check disk space, restart a service or fix a setting takes ages, and sooner or later you get one wrong. AWS Systems Manager automation tools take that job off your hands, with Run Command for one-off jobs across many servers, Automation runbooks for fixes you repeat, and State Manager to stop settings drifting.
You’ll check disk and uptime on two servers with a single command, write a runbook that clears old temp files and tags the server, and let State Manager bring a stopped service back without you touching it. Then you’ll fix two Run Command mistakes that eat up a lot of time on real teams.
| Time | You need | By the end you can |
|---|---|---|
| 60 minutes (two small instances and the Session Manager endpoints for under an hour) | saat-vpc, Start-SsmEndpoints.ps1 and Stop-SsmEndpoints.ps1, saat-ec2-ssm-profile, your laptop signed in as saat-admin. Cost: about USD 0.10. Run Command and State Manager have no extra charge on EC2; Automation includes a monthly allowance of steps. | Run commands across servers by tag with rate control, write and run your own Automation runbook, keep settings in place with a State Manager association, and read the command results for each instance. |
What it is, in one line
AWS Systems Manager automation means running commands, runbooks and scheduled associations on your servers through Systems Manager, with no SSH or RDP needed.
In Simple Words
The school announcement system
A principal doesn’t walk to every classroom to say “exams start at ten”; one announcement on the speaker reaches every room at once, and that’s Run Command. For fire drills there’s a written plan (ring the bell, open the doors, count the children, report to the office) that anyone can follow the same way every time, and that’s an Automation runbook. Then there’s the caretaker who checks every evening that the windows are locked and locks any that aren’t, without anyone asking, which is State Manager.
Engineer's View
How the three tools really work
All three run SSM documents. Run Command sends a Command document such as AWS-RunShellScript or AWS-RunPowerShellScript to targets you pick by instance ID or tag, and you control the pace with max concurrency and max errors. Each instance sends back a status, an exit code and the first 24,000 characters of output, and if you need more you send it to S3 or CloudWatch Logs.
Automation runs Automation documents (runbooks, schema 0.3) built from steps like aws:runCommand, aws:executeAwsApi, aws:createTags, aws:approve and aws:branch, and AWS publishes hundreds of ready-made ones such as AWS-RestartEC2Instance and AWSSupport-TroubleshootSSH. A runbook uses your own permissions unless you pass an AutomationAssumeRole, and that’s what lets you hand people a safe button without giving them broad IAM rights.
State Manager creates associations, each one a document, a set of targets and a schedule (no more often than every 30 minutes), which keep instances in the state you defined and report association compliance. Patch Manager and the CloudWatch agent setup are often run this way.
How it works, step by step
Pick the tool based on the job:
1Run Command for now
“Show me disk space on every web server” is a Run Command job, with one document, many targets and results in seconds.
2Automation for a procedure
“Clean old temp files and then record that we did it” has steps that must happen in order, so it goes in a runbook.
3State Manager for always
“chronyd must always be running” isn’t something you do once, so an association checks every 30 minutes and fixes any drift.
This is the runbook you’ll build in the lab:
A habit worth picking up: the third time you run the same Run Command, turn it into a runbook, and once you find yourself running a runbook on a schedule, think about making it an association.
✅ Checkpoint: You can say which tool suits a one-off check, a multi-step fix and a setting that has to stay put, and how rate control keeps the damage small.
Hands-on lab: AWS Systems Manager automation without SSH
Before you run any command, double-check it
Read every command twice before you press Enter. Check the target: the system or account, the IDs, the names and the sizes. These commands are for learning and were tested in our lab, not on your system. At work, run the read-only list commands first, follow your change process, make sure a backup exists, and ask a second person to check anything that changes or deletes data. You run them at your own risk.
Start as usual:
cd C:\aws-lab
aws login --profile saat-admin
$env:AWS_PROFILE = 'saat-admin'
$v = Get-Content C:\aws-lab\saat-vpc.json | ConvertFrom-Json
.\Start-SsmEndpoints.ps11Launch two web servers
Paste this whole block:
$base = aws ssm get-parameter --name /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64 --query Parameter.Value --output text
$ids = foreach ($s in @(@('ops01', $v.PrivateA), @('ops02', $v.PrivateB))) {
aws ec2 run-instances --image-id $base --instance-type t3.micro --subnet-id $s[1] --security-group-ids $v.AppSg --iam-instance-profile Name=saat-ec2-ssm-profile --metadata-options HttpTokens=required --tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=$($s[0])},{Key=Role,Value=web},{Key=course,Value=saatvedha-aws},{Key=lesson,Value=28}]" --query "Instances[0].InstanceId" --output text
}
foreach ($i in $ids) { do { Start-Sleep 20; $p = aws ssm describe-instance-information --filters "Key=InstanceIds,Values=$i" --query "InstanceInformationList[0].PingStatus" --output text } until ($p -eq 'Online') }
aws ssm describe-instance-information --filters "Key=tag:Role,Values=web" --query "InstanceInformationList[].[InstanceId,PingStatus,PlatformName]" --output textYou should see something like this:
i-0b1c2d3e4f5a60051 Online Amazon Linux
i-0b1c2d3e4f5a60052 Online Amazon Linux2One command, every web server
Paste this whole block:
'{ "commands": [ "df -h /", "uptime" ] }' | Set-Content rc-params.json
$cmd = aws ssm send-command --document-name AWS-RunShellScript --targets "Key=tag:Role,Values=web" --parameters file://rc-params.json --max-concurrency 50% --max-errors 1 --comment "disk check" --query Command.CommandId --output text
Start-Sleep 15
foreach ($i in $ids) { aws ssm get-command-invocation --command-id $cmd --instance-id $i --query StandardOutputContent --output text }You should see something like this for each server:
Filesystem Size Used Avail Use% Mounted on
/dev/nvme0n1p1 8.0G 1.7G 6.3G 21% /
19:42:10 up 12 min, 0 users, load average: 0.00, 0.02, 0.01The parameters go in a file because Windows PowerShell 5.1 strips the inner quotes otherwise. --max-concurrency 50% runs on half the servers at a time, and --max-errors 1 stops sending to new servers after the second failure, so one bad command can’t take out the whole fleet.
3Write and run a runbook
Paste this whole block:
@'
description: Delete temp files older than 7 days and tag the instance
schemaVersion: '0.3'
parameters:
InstanceId:
type: String
description: The instance to clean
mainSteps:
- name: cleanTmp
action: aws:runCommand
inputs:
DocumentName: AWS-RunShellScript
InstanceIds:
- '{{ InstanceId }}'
Parameters:
commands:
- find /var/tmp -type f -mtime +7 -print -delete
- df -h /
- name: tagInstance
action: aws:createTags
inputs:
ResourceType: EC2
ResourceIds:
- '{{ InstanceId }}'
Tags:
- Key: LastDiskCleanup
Value: '{{ global:DATE }}'
'@ | Set-Content saat-diskcleanup.yaml
aws ssm create-document --name saat-DiskCleanup --document-type Automation --document-format YAML --content file://saat-diskcleanup.yaml --tags Key=course,Value=saatvedha-aws --query "DocumentDescription.Status" --output text
Start-Sleep 5
$ae = aws ssm start-automation-execution --document-name saat-DiskCleanup --parameters "InstanceId=$($ids[0])" --query AutomationExecutionId --output text
do { Start-Sleep 10; $st = aws ssm get-automation-execution --automation-execution-id $ae --query AutomationExecution.AutomationExecutionStatus --output text } until ($st -notin 'Pending', 'InProgress', 'Waiting')
aws ssm get-automation-execution --automation-execution-id $ae --query "AutomationExecution.StepExecutions[].[StepName,StepStatus]" --output text
aws ec2 describe-tags --filters "Name=resource-id,Values=$($ids[0])" "Name=key,Values=LastDiskCleanup" --query "Tags[0].Value" --output textYou should see something like this:
Creating
cleanTmp Success
tagInstance Success
2026-10-20You get two steps, run in order, with a record of each, and anyone on the team can run the same runbook from the console without knowing what commands are inside. Open Systems Manager and go to Automation to see the execution and the output of each step.


4Keep a service running with State Manager
Paste the whole block. It creates an association, stops chronyd on ops02 to cause some drift, and then lets the association fix it:
'{ "commands": [ "systemctl is-active --quiet chronyd || systemctl restart chronyd", "systemctl is-active chronyd" ] }' | Set-Content assoc-params.json
$assoc = aws ssm create-association --association-name saat-keep-chrony --name AWS-RunShellScript --targets "Key=tag:Role,Values=web" --parameters file://assoc-params.json --schedule-expression "rate(30 minutes)" --query AssociationDescription.AssociationId --output text
'{ "commands": [ "systemctl stop chronyd", "systemctl is-active chronyd || true" ] }' | Set-Content stop-params.json
$stop = aws ssm send-command --document-name AWS-RunShellScript --instance-ids $ids[1] --parameters file://stop-params.json --query Command.CommandId --output text
Start-Sleep 15
aws ssm get-command-invocation --command-id $stop --instance-id $ids[1] --query StandardOutputContent --output text
aws ssm start-associations-once --association-ids $assoc
Start-Sleep 60
aws ssm describe-instance-associations-status --instance-id $ids[1] --query "InstanceAssociationStatusInfos[0].[Name,Status]" --output textYou should see something like this:
inactive
AWS-RunShellScript Successchronyd was stopped and the association started it again. You wouldn’t normally trigger it by hand, because within 30 minutes it would have run on its own. Teams use this to keep agents, time sync and security settings in place on servers that people still log in to.
✅ Checkpoint: Run Command brought back disk and uptime from both servers, saat-DiskCleanup ran both steps and tagged ops01, and saat-keep-chrony got chronyd running again on ops02. Keep it all for the break lab.
Break It, Then Fix It
Two Run Command mistakes, where one runs on nobody and the other fails on everybody.
1Break it: a tag value with the wrong case
Send the disk check to Role=Web:
$cmd = aws ssm send-command --document-name AWS-RunShellScript --targets "Key=tag:Role,Values=Web" --parameters file://rc-params.json --query Command.CommandId --output text
Start-Sleep 20
aws ssm list-commands --command-id $cmd --query "Commands[0].[TargetCount,CompletedCount]" --output textYou should see this:
0 0There’s no error. The command was accepted and ran on zero servers, because tag values are case-sensitive, and in a real incident this is how someone ends up saying “I restarted it everywhere” when nothing changed at all.
Fix: check what the target matches before you believe the result:
aws ssm describe-instance-information --filters "Key=tag:Role,Values=Web" --query "length(InstanceInformationList)"
aws ssm describe-instance-information --filters "Key=tag:Role,Values=web" --query "length(InstanceInformationList)"You should see this:
0
22Break it: restart a service that isn’t there
Ask both servers to restart nginx:
'{ "commands": [ "systemctl restart nginx" ] }' | Set-Content nginx-params.json
$cmd = aws ssm send-command --document-name AWS-RunShellScript --targets "Key=tag:Role,Values=web" --parameters file://nginx-params.json --query Command.CommandId --output text
Start-Sleep 20
aws ssm list-commands --command-id $cmd --query "Commands[0].[Status,ErrorCount]" --output text
aws ssm get-command-invocation --command-id $cmd --instance-id $ids[0] --query "[Status,ResponseCode,StandardErrorContent]" --output textYou should see something like this:
Failed 2
Failed 5 Failed to restart nginx.service: Unit nginx.service not found.
failed to run commands: exit status 5
The overall status only says Failed. The reason sits in each instance’s StandardErrorContent and exit code, and here it’s that these servers don’t run nginx at all. It’s common for a team to retry a failed command three times before anyone reads the error.
Fix: read the error for each instance first, then send the right command. In this case the web service you named doesn’t exist, so the answer is to fix the inventory or the runbook and not to keep retrying.
Clean up:
aws ssm delete-association --association-id $assoc
aws ssm delete-document --name saat-DiskCleanup
aws ec2 terminate-instances --instance-ids $ids | Out-Null
aws ec2 wait instance-terminated --instance-ids $ids
.\Stop-SsmEndpoints.ps1
Remove-Item rc-params.json, assoc-params.json, stop-params.json, nginx-params.json, saat-diskcleanup.yaml
.\Find-LabResources.ps1✅ Checkpoint: You caught a command that matched zero targets and read a real failure out of StandardErrorContent. The association, runbook and both servers are gone.
This happened at work
The cleanup command that ran everywhere
A media company had a Run Command script that freed disk space on its transcoding servers by deleting old files in /data/tmp. One day an engineer adapted it for the log servers, changed the path, and targeted tag:Env=prod in place of tag:Role=transcoder, leaving concurrency at the default. On most servers the path variable came out empty, so the script deleted from /data/ instead, and within a minute it had reached 140 production servers, database replicas included, before anyone spotted it. Several services had to be restored from snapshots over the next six hours. Afterwards the team moved the job into an Automation runbook with an aws:approve step for production, a dry-run step that prints what would be deleted, max concurrency of 5 percent with max errors 1, and an AutomationAssumeRole that can only touch servers tagged for that job.
Common mistakes and troubleshooting
| Mistake | What happens | What to do |
|---|---|---|
| Tag value with the wrong case | Command runs on zero servers, no error | Check the target with describe-instance-information first |
| Default concurrency on destructive commands | Every server breaks at once | Use small max concurrency and max errors 1 |
| Retrying failed commands blindly | Same failure, wasted time | Read StandardErrorContent and ResponseCode per instance |
| Inline JSON parameters in Windows PowerShell 5.1 | Quotes stripped, invalid JSON | Write parameters to a file and use file:// |
| Giving people broad IAM rights to run fixes | Too much power for one task | Runbooks with an AutomationAssumeRole |
| One-off commands for settings that must stay | Drift returns next week | State Manager associations on a schedule |
Interview questions
Click a question to open it. Each one is phrased the way an interviewer would ask it, and under it you’ll find why they ask it and one way you could answer in your own words.
Fresher level
1. Your manager asks you to restart a service on 30 servers right now. How could Run Command help you with that?
Why they ask this: They want to know you can work on many servers at once without logging in to each, and that you know the basic Systems Manager tools.
How you might answer: I’d pick an SSM document in Run Command, like a shell or PowerShell script, and target the 30 servers by instance ID or by tag, and it runs on all of them at once without SSH or RDP. Then I’d go through the output and status for each instance in the console to make sure the restart worked everywhere.
2. Can you explain in simple words what an Automation runbook is?
Why they ask this: They’re checking you know how to turn a manual procedure into something repeatable, which matters a lot in operations teams.
How you might answer: It’s an SSM document with steps that run in order, where a step can run a command, call an AWS API, wait for someone to approve, or branch on a result. I think of it as a written procedure that runs itself, so everyone does the task the same way.
3. What does State Manager do, and why would you use it instead of a one-time Run Command?
Why they ask this: Servers change over time, so they want to see you understand configuration drift and can keep servers in a known state.
How you might answer: State Manager applies an association, which is a document on a set of targets on a schedule, and it keeps instances in the state I defined and reports compliance. Run Command fixes something once, but State Manager keeps checking, so if someone changes a setting later it gets put back.
2–5 years experience
4. You need to run a risky script on all production servers. How would you make sure a mistake doesn’t hit everything at once?
Why they ask this: They want to see you think about blast radius before you press run, because careful people limit how much damage a bad script can do.
How you might answer: I’d be careful with the targeting and test the command on one instance first. Then I’d set max concurrency, as a number or a percent, plus max errors so it stops if failures start piling up, and for production I’d rather wrap it in a runbook with an approval step so a second person checks it.
5. Why would you set an AutomationAssumeRole on a runbook instead of letting people run it with their own permissions?
Why they ask this: It’s about safe delegation, letting people do a task without handing them broad access.
How you might answer: With an AutomationAssumeRole the runbook works through a tightly scoped role, so the person running it doesn’t need those permissions. A support engineer could restart an app through the runbook without admin rights on EC2, for example, and since every execution is logged we still know who ran what.
6. A Run Command you sent shows Failed in the console. Walk me through how you’d troubleshoot it.
Why they ask this: Failed commands happen all the time, so they want a clear order of checks that gets you to the reason quickly.
How you might answer: I’d open the status for each instance and look at the ResponseCode and StandardErrorContent, and check the instance was Online and the document parameters, timeout and permissions were right. If the output was long, I’d send it to S3 or CloudWatch Logs next time, since the console only shows part of it.
Senior level
7. Fifteen app teams keep asking your ops team to do routine tasks for them. How would you design self-service so they can do it safely themselves?
Why they ask this: They’re looking for platform thinking, meaning safe automation, permissions and approvals, and whether you can grow what an ops team covers without losing control.
How you might answer: I’d build a library of tested Automation runbooks, each with an assume role scoped by tags so a team can only touch its own resources, and production runs would need an approval step or Change Manager. Output would go to CloudWatch Logs, common alarms would trigger runbooks through EventBridge, and State Manager associations would hold the baseline settings in place.
8. Servers keep running out of disk space and waking people up at night. How would you remediate a full disk alarm automatically?
Why they ask this: They want event-driven automation with safety built in, and they’ll want to hear what you’d do if the automation itself goes wrong.
How you might answer: I’d put a CloudWatch alarm on disk_used_percent and send it to EventBridge, which starts a runbook. The runbook collects diagnostics, cleans the paths we know are safe, extends the EBS volume if the disk is still over the threshold, and then tells the team. I’d also add rate limits so it can’t get stuck in a loop.
Quick quiz
Q1. Which tool keeps a setting in place on a schedule?
- Run Command
- Automation
- State Manager
- Patch Manager
Show answer
C — Associations reapply the desired state regularly.
Q2. Why did the Role=Web command run on zero servers?
- The servers were offline
- Tag values are case-sensitive
- The document was wrong
- Concurrency was 0
Show answer
B — The tag value is web, in lowercase.
Q3. Where do you find why a command failed on one server?
- CloudTrail only
- StandardErrorContent and ResponseCode for that instance
- The AMI
- The VPC
Show answer
B — get-command-invocation shows per-instance errors.
Q4. What does --max-errors 1 do?
- Allows one server only
- Stops sending to new targets after errors exceed 1
- Retries once
- Ignores errors
Show answer
B — It limits damage from a bad command.
Q5. How does a runbook act with permissions you don’t have?
- It can’t
- Through an AutomationAssumeRole
- With root keys
- By using the instance role
Show answer
B — The assume role lets people run it safely.
Quick recap
- Run Command sends one document to many servers and gives you results per instance.
- Automation runbooks make multi-step fixes repeatable and safe.
- State Manager associations fix drift on a schedule.
- Use rate control, and check your targets before you run anything.
- Read StandardErrorContent before you retry a failed command.
Next lesson
Lesson 29: AWS Backup: plans, vaults, restore tests → Next you’ll back up EC2 and EBS with a backup plan, lock a vault, and, the part that matters most, prove that a restore works.
Further reading: AWS Systems Manager automation
Want to go deeper into AWS Systems Manager automation? Read AWS Systems Manager Run Command and AWS Systems Manager Automation. You can also see the full plan for this course on the AWS Cloud Administration course page.
