2.4 Automated Remediation with Systems Manager & Lambda
Key Takeaways
- Automated remediation loops integrate detection (CloudWatch Alarms, EventBridge Rules, AWS Config Rules) with execution (SSM Automation runbooks or AWS Lambda) and audit trails (AWS CloudTrail).
- SSM Automation runbooks provide pre-built, long-running, and OS-aware administrative workflows (e.g., AWS-RestartEC2Instance, AWS-EnableS3BucketEncryption) with native approval gates (aws:approve).
- SSM Automation documents require schemaVersion 0.3, an AutomationAssumeRole with appropriate IAM permissions, and step action plugins like aws:executeAwsApi and aws:changeInstanceState.
- AWS Config rules provide continuous compliance monitoring that triggers SSM Automation remediation automatically, mapping the non-compliant resource ID to the runbook parameter.
- Production incident response patterns utilize automated runbooks to quarantine compromised EC2 instances into isolation security groups, capture volatile memory and EBS snapshots, and detach instances from Auto Scaling groups to prevent premature termination.
2.4 Automated Remediation with Systems Manager & Lambda
Automated remediation transforms static monitoring into self-healing infrastructure. When operational incidents, resource failures, or compliance violations occur, relying on human engineers to diagnose and execute corrective actions introduces latency, operational overhead, and human error. AWS provides two primary compute engines for automated remediation: AWS Systems Manager (SSM) Automation and AWS Lambda. For the CloudOps Associate exam, engineers must know how to choose between these engines, design multi-step runbooks, implement approval gates, integrate with AWS Config rules, and execute production incident response workflows.
Remediation Workflow Architecture: Choosing SSM Automation vs. Lambda
An automated remediation loop follows three distinct operational phases:
- Detection: A CloudWatch Alarm trips into the
ALARMstate, an EventBridge rule detects a state-change or API call, or an AWS Config rule flags a resource as non-compliant. - Orchestration & Execution: The detection mechanism triggers either an SSM Automation runbook or an AWS Lambda function.
- Audit & Verification: Every remediation action must be logged in AWS CloudTrail, Systems Manager execution history, and CloudWatch Logs to ensure traceability and verify successful resolution.
Choosing the appropriate execution engine is a common exam theme:
| Architectural Criterion | AWS Systems Manager Automation | AWS Lambda |
|---|---|---|
| Primary Use Case | Multi-service AWS API orchestration, fleet operations, OS-level administration | Custom algorithmic business logic, complex data transformations, rapid micro-actions |
| Code Maintenance | Low (declarative YAML/JSON documents; hundreds of pre-built AWS runbooks) | Higher (requires authoring, testing, packaging, and maintaining runtime dependencies) |
| Execution Duration | Long-running workflows (days or weeks; supports pauses and approval gates) | Hard limit of 15 minutes (900 seconds) per invocation |
| OS-Level Execution | Native integration with SSM Agent via Run Command plugins | Cannot execute commands directly inside private OS instances without bastion/network proxies |
| Human Approval Gates | Native support via the aws:approve action plugin | Requires custom Step Functions state machine or external webhooks |
As a general CloudOps rule of thumb: prefer AWS-managed SSM Automation runbooks first. Only introduce AWS Lambda when custom parsing, external third-party API integration, or sub-second latency is strictly necessary.
SSM Automation Runbooks: Structure & Execution
An SSM Automation runbook is a declarative document (defined in YAML or JSON) that specifies the tasks executed by Systems Manager. AWS provides dozens of predefined, battle-tested runbooks, including:
AWS-RestartEC2Instance: Safely reboots an EC2 instance.AWS-StopEC2Instance: Stops an instance to halt runaway costs or isolate workloads.AWS-CreateSnapshot: Generates point-in-time EBS volume snapshots prior to maintenance.AWS-PublishSNSNotification: Broadcasts incident updates to operational channels.AWS-AttachEBSVolume: Automatically attaches replacement storage volumes.
Document Structure & The Automation Assume Role
An Automation document consists of several core sections:
schemaVersion: Must be specified as0.3to support modern branching, looping, and multi-step workflows.assumeRole: The ARN of the IAM role that Systems Manager assumes to perform actions (AutomationAssumeRole). This role must have a trust policy allowingssm.amazonaws.comand identity policies granting the specific AWS API actions executed in the runbook.parameters: Defines inputs passed at runtime (e.g.,InstanceId,SnapshotId), along with types, descriptions, and defaults.mainSteps: An ordered sequence of steps using SSM action plugins.outputs: Values exported from steps for subsequent runbooks or parent workflows.
A production-grade custom runbook leverages action plugins such as aws:executeAwsApi (making direct AWS API calls), aws:waitForAwsResourceProperty (polling until resources enter a desired state), and conditional branching (onFailure, nextStep):
description: "Diagnose and reboot unresponsive EC2 instance"
schemaVersion: "0.3"
assumeRole: "arn:aws:iam::123456789012:role/SSMAutomationRole"
parameters:
InstanceId:
type: "String"
description: "Target EC2 Instance to remediate"
mainSteps:
- name: "CreateSafetySnapshot"
action: "aws:executeAwsApi"
inputs:
Service: "ec2"
Api: "CreateSnapshot"
VolumeId: "{{GetVolume.VolumeId}}"
Description: "Pre-remediation snapshot"
nextStep: "RestartInstance"
onFailure: "Abort"
- name: "RestartInstance"
action: "aws:changeInstanceState"
inputs:
InstanceIds:
- "{{InstanceId}}"
CheckStateOnly: false
DesiredState: "reboot"
nextStep: "WaitForHealthy"
- name: "WaitForHealthy"
action: "aws:waitForAwsResourceProperty"
timeoutSeconds: 300
inputs:
Service: "ec2"
Api: "DescribeInstanceStatus"
InstanceIds:
- "{{InstanceId}}"
PropertySelector: "$.InstanceStatuses[0].InstanceStatus.Status"
DesiredValues:
- "ok"
isEnd: true
Manual Approval Steps (aws:approve)
In mission-critical or high-risk environments, full automation may be restricted by compliance policies. SSM Automation supports hybrid workflows using the aws:approve action plugin. When reached, execution pauses, dispatches an approval notification via Amazon SNS to designated Approvers (IAM users or roles), and waits for a human operator to issue an Approve or Reject API call before proceeding to potentially destructive steps (such as instance termination or database failover).
Integrating Remediation with AWS Config Rules
AWS Config continuously evaluates AWS resource configurations against desired baselines. When a managed or custom Config rule detects non-compliance, it can initiate automatic remediation via SSM Automation.
To configure automatic remediation:
- Select the AWS Config rule (e.g.,
s3-bucket-server-side-encryption-enabledorrestricted-ssh). - Attach an SSM Automation remediation action (e.g.,
AWS-EnableS3BucketEncryption). - Configure the Resource ID parameter to map the non-compliant resource ID emitted by Config directly to the runbook's target parameter (e.g.,
BucketName). - Specify the
AutomationAssumeRoleARN with permissions to modify the target resource. - Set the execution mode to Automatic and define retry attempts (e.g., retry 5 times every 60 seconds).
As soon as a developer creates an unencrypted S3 bucket, AWS Config detects non-compliance within seconds and triggers the runbook, applying default SSE-S3 or KMS encryption without human intervention.
Operational Scenarios: Self-Healing & Incident Response
1. Application Daemon Recovery via SSM Run Command
When a CloudWatch metric alarm detects that a critical daemon (e.g., httpd or nginx) has stopped, an EventBridge rule invokes an SSM Automation runbook. The runbook uses the aws:runCommand plugin to execute systemctl restart nginx via the SSM Agent on the instance, avoiding SSH key management and private network access restrictions.
2. Compromised Instance Quarantine & Digital Forensics
When AWS GuardDuty detects that an EC2 instance is communicating with a known command-and-control server:
- EventBridge intercepts the GuardDuty finding and invokes an incident response SSM Automation runbook.
- The runbook immediately detaches the instance from its Auto Scaling group (or puts it in standby) to prevent the ASG from terminating it.
- The runbook replaces the instance's security groups with an Isolation Security Group that denies all inbound and outbound traffic, severing network access.
- The runbook takes point-in-time EBS volume snapshots of all attached disks for forensic analysis.
- It triggers volatile memory capture via the SSM Agent before stopping the instance.
- All actions are logged immutably in CloudTrail for legal and compliance auditability.
A CloudOps engineer configures an AWS Config rule s3-bucket-server-side-encryption-enabled to detect unencrypted S3 buckets and attaches the managed SSM Automation runbook AWS-EnableS3BucketEncryption for automatic remediation. However, when a non-compliant bucket is detected, the remediation action fails immediately with an AccessDenied error during execution. What is the cause of this failure?
A financial services organization requires that whenever a production EC2 instance triggers a high memory and disk exhaustion alarm, an automated runbook must gather diagnostic memory dumps, stage an EBS snapshot, but MUST PAUSE and receive explicit authorization from an on-call operations engineer before terminating and replacing the instance. Which SSM Automation document action plugin should be implemented for this pause-and-approval step?
A security monitoring rule detects that an EC2 instance in a public subnet has established connections to a known malicious command-and-control IP address. To prevent data exfiltration while preserving digital forensic evidence for investigation, which sequence of automated remediation actions should the incident response runbook execute?