Operational Automation: Lambda, Step Functions and Systems Manager Runbooks
Overview
Large environments cannot be operated by hand. DOP-C02 task 2.3 asks you to design automation for complex, large-scale tasks: inventory and patch fleets, orchestrate multi-step operations, keep systems in a desired state and run code in response to events. The main tools are Lambda with the SDKs, Step Functions and Systems Manager (Automation, Run Command, State Manager, Inventory, Change Manager, OpsCenter).
Think of a factory control room. Lambda functions are single-purpose robots, Step Functions is the supervisor sequencing the robots with retries and error paths, and Systems Manager is the maintenance crew with approved runbooks who can visit every machine safely.
The skill to show is choosing the right orchestrator: SSM Automation when the steps are AWS or instance operations with approvals and rate controls; Step Functions when business logic, long waits or branching dominate; plain Lambda for a short, single action.
Key Concepts
- Lambda automation runs SDK calls in response to EventBridge, schedules or API calls; keep functions idempotent, use least-privilege roles and a DLQ or on-failure destination.
- Step Functions Standard workflows run up to a year with exactly-once execution; Express workflows run up to five minutes at high volume with at-least-once semantics.
- Step Functions supports Retry, Catch, Choice, Map, Parallel, Wait states and optimised integrations (for example
ecs:runTask.sync,states:startExecution.sync, direct SDK integrations to over 200 services). - SSM Automation runbooks (documents) chain steps such as
aws:executeAwsApi,aws:runCommand,aws:changeInstanceState,aws:approveandaws:executeScript, with rate control (concurrency and error thresholds) and cross-account, multi-Region execution. - State Manager associations enforce a desired state on a schedule (agent updates, CloudWatch agent configuration, anti-virus), and report compliance.
- Inventory collects metadata (applications, files, network config, custom) and Resource Data Sync exports it to S3 for Athena and QuickSight analysis.
- Change Manager adds approval workflows and change calendars; OpsCenter aggregates OpsItems for operational issues linked to runbooks.
- EventBridge Scheduler invokes targets at scale on cron or one-time schedules, including time zones and flexible windows.
Detailed Notes
Choosing the orchestrator
| Need | Best choice | Reason |
|---|---|---|
| One quick reaction to an event | Lambda | Simple, cheap |
| Restart or patch many instances with approval and throttling | SSM Automation / Run Command | Built-in targets, rate control, no code |
| Multi-step with branching, retries, waits, human callbacks | Step Functions | Visual state machine, durable |
| Keep configuration enforced continuously | State Manager | Association with schedule and compliance |
| Time-based work | EventBridge Scheduler | Managed scheduler with retries |
| Cross-service data-driven pipeline | Step Functions + direct SDK integrations | Fewer Lambda functions |
A Step Functions remediation workflow
{
"StartAt": "IsolateInstance",
"States": {
"IsolateInstance": {
"Type": "Task",
"Resource": "arn:aws:states:::aws-sdk:ec2:modifyInstanceAttribute",
"Parameters": { "InstanceId.$": "$.detail.instance-id", "Groups": ["sg-0quarantine"] },
"Retry": [{ "ErrorEquals": ["States.TaskFailed"], "IntervalSeconds": 5, "MaxAttempts": 3, "BackoffRate": 2 }],
"Catch": [{ "ErrorEquals": ["States.ALL"], "Next": "NotifyFailure" }],
"Next": "SnapshotVolumes"
},
"SnapshotVolumes": { "Type": "Task", "Resource": "arn:aws:lambda:us-east-1:111122223333:function:snapshot-volumes", "Next": "ApproveTerminate" },
"ApproveTerminate": {
"Type": "Task",
"Resource": "arn:aws:states:::sns:publish.waitForTaskToken",
"Parameters": { "TopicArn": "arn:aws:sns:us-east-1:111122223333:secops", "Message": { "token.$": "$$.Task.Token" } },
"End": true
},
"NotifyFailure": { "Type": "Fail", "Cause": "Isolation failed" }
}
}
The .waitForTaskToken pattern pauses the workflow until a person or system calls SendTaskSuccess, which is how human approval fits into an automated process. The .sync pattern waits for jobs (ECS, Batch, Glue, nested executions) to finish.
Systems Manager Automation runbook
schemaVersion: "0.3"
description: Stop, resize and restart an instance
assumeRole: "{{ AutomationAssumeRole }}"
parameters:
InstanceId: { type: String }
InstanceType: { type: String, default: m6i.large }
AutomationAssumeRole: { type: String }
mainSteps:
- name: approve
action: aws:approve
inputs: { NotificationArn: "arn:aws:sns:us-east-1:111122223333:ops", MinRequiredApprovals: 1, Approvers: ["arn:aws:iam::111122223333:role/Ops"] }
- name: stop
action: aws:changeInstanceState
inputs: { InstanceIds: ["{{ InstanceId }}"], DesiredState: stopped }
- name: resize
action: aws:executeAwsApi
inputs: { Service: ec2, Api: ModifyInstanceAttribute, InstanceId: "{{ InstanceId }}", InstanceType: { Value: "{{ InstanceType }}" } }
- name: start
action: aws:changeInstanceState
inputs: { InstanceIds: ["{{ InstanceId }}"], DesiredState: running }
Run it at scale with targets and rate control:
aws ssm start-automation-execution --document-name ResizeInstance \
--targets Key=tag:env,Values=staging --max-concurrency 10% --max-errors 5% \
--target-locations "Accounts=111122223333,444455556666,Regions=us-east-1,eu-west-1,ExecutionRoleName=AutomationExecutionRole"
State Manager, Inventory and compliance
| Capability | Use | Detail |
|---|---|---|
| State Manager association | Apply a document to targets on a schedule or on new instances | Example: keep the CloudWatch agent configured, run AWS-GatherSoftwareInventory |
| Inventory | Know what is installed, where | Resource Data Sync to S3, query with Athena |
| Compliance | Show association and patch status | Aggregated per resource and in Explorer |
| Distributor | Package and distribute software | Versioned packages deployed by Run Command or State Manager |
| Change Manager / calendars | Approval gates and blackout windows | Block automation during freezes |
| OpsCenter | Central work items | Link CloudWatch alarms and runbooks |
Lambda automation checklist
- Use idempotency: check state before acting, and use client tokens.
- Configure timeouts, retries and destinations; for long work hand off to Step Functions or SSM.
- Grant the least privilege and use resource tags as conditions to limit what the function may touch.
- For multi-account actions, assume a role in each account through STS, using a small, audited role.
- Log structured JSON and emit custom metrics so automation itself is observable.
Common automation scenarios
- Stop non-production instances nights and weekends (EventBridge Scheduler plus SSM Automation
AWS-StopEC2Instance). - Rotate and distribute credentials (Secrets Manager rotation Lambda).
- Snapshot, copy and clean up backups.
- Enforce tags: Config rule plus remediation runbook.
- Roll a Region-wide AMI update: Image Builder, SSM Parameter Store AMI ID, instance refresh.
Real World Example
Scenario: a company must resize and patch 600 staging instances each month without outages for test teams. An EventBridge Scheduler rule starts an SSM Automation runbook across three accounts and two Regions with 10% concurrency and a 5% error threshold. The runbook takes a snapshot, patches via Patch Manager and verifies the application health endpoint.
A Step Functions workflow coordinates the larger release calendar: it checks Change Manager for blackout windows, starts the automation and waits for an approval token from the service owner before touching production.
Architecture Diagram
Schedules and events start workflows that call runbooks and functions.
- 1A schedule or event starts the process.
- 2Step Functions sequences checks, approvals and error handling.
- 3SSM Automation executes the operational steps on targets with concurrency and error limits.
- 4Lambda functions perform small custom actions through the SDK.
- 5Results and compliance are visible in Systems Manager, CloudWatch and OpsCenter.
Best Practices
- ✓Prefer managed runbooks and Step Functions direct integrations to hand-written glue code.
- ✓Always apply rate control and error thresholds when automating across fleets.
- ✓Make automation idempotent, least-privilege and observable (metrics, logs, alarms).
- ✓Add approvals and change calendars for production-impacting runbooks.
- ✓Use State Manager and Inventory to maintain and prove desired state continuously.
Common Interview Questions
Exam Tips
DOP-C02 focus
- "Run a command on thousands of instances with limits and no SSH" = Run Command or Automation with rate control.
- "Enforce configuration continuously" = State Manager association.
- "Orchestrate multi-step workflow with retries and human approval" = Step Functions.
- "Inventory of installed software across accounts" = SSM Inventory + Resource Data Sync + Athena.
Chapter quiz
Infrastructure as Code and Configuration Management · 10 questions
1.A company wants to run a runbook that restarts application services on 2,000 instances across multiple accounts and Regions. A mistake could cause an outage, so only a small portion of the fleet should be affected if the runbook fails. Which configuration is best?
2.A remediation workflow must isolate a compromised instance, snapshot its volumes, wait for a security engineer to approve termination, and handle failures with retries. Which service should orchestrate this?
3.The security team wants every EC2 instance, including those launched in the future, to run the CloudWatch agent with a standard configuration and to report whether instances comply. Which solution requires the least ongoing effort?
4.A team needs to analyse installed software across 80 accounts to find instances running a vulnerable agent version, using SQL. Which approach is most appropriate?
5.Development instances should stop at 19:00 and start at 07:00 on weekdays in a specific time zone across several accounts, with retries if the API is throttled. Which design is most operationally efficient?
6.A CloudFormation update will modify the instance type of an RDS DB instance and change the DB subnet group. The team wants to know in advance whether any resource will be replaced. What should they do?
7.A stack that contains a Lambda-backed custom resource stays in DELETE_IN_PROGRESS for about an hour and then fails. What is the MOST likely cause?
8.A company with 200 accounts in AWS Organizations needs a security IAM role and AWS Config recorder deployed in every current and future account in the Workloads OU, in two Regions, with minimal administration. What is the BEST solution?
9.A DevOps engineer needs a CDK pipeline in a tooling account to deploy stacks into a production account. The deployment fails with a permissions error assuming roles. What is the likely missing step?
10.Operations staff currently SSH to EC2 instances through a bastion host to run maintenance commands. Security requires removing inbound SSH, keeping a record of every session and restricting who can connect using IAM. What should be implemented?
0 of 10 answered
Finished this lesson?
0 of 44 lessons done · 0% of the course

