
Automating Patched AMI Rollouts for AWS Data Workers
A patched AMI is ready for production only after workers pass job tests - not just EC2 health checks. Use EC2 Image Builder to build and test the image, pin its AMI ID in a numbered launch-template version, and replace workers in controlled batches.
For a 20-worker fleet, a 90% minimum healthy capacity sets an 18-worker floor during replacement. A safe rollout also needs:
- Readiness checks and alarms to detect failed startup, job errors, and queue delays.
- A drain handler to stop new jobs and finish or checkpoint active work before termination.
- A rollback path that keeps the previous AMI and template version ready to launch.
- Automation, approvals, and records to prevent conflicting changes and track results.
Promote the image only after workload checks pass and the observation window closes. If checks fail, roll back an eligible active rollout or start a recovery rollout using the previous version.
Safe AWS Patched AMI Rollout Workflow
2. Build and Test the Patched AMI
Configure the EC2 Image Builder Pipeline
Start with an approved source AMI and record its resolved AMI ID. Create an immutable Image Builder recipe version that applies patches, hardening, pinned dependencies, agents, and readiness checks - in that order. Each recipe version is one release candidate for later launch-template promotion. Use AWS-managed update components for OS patches and custom components for pinned packages and approved package exclusions. Give every exclusion an owner, reason, and expiration date. Create a new recipe version whenever its configuration changes.
Bake the Databricks on AWS worker application, libraries, SSM Agent, CloudWatch Agent, and security tooling into the image. Pass queues, environment values, and secrets at launch. Keep the Image Builder infrastructure role, build/test instance profile, and launch-time worker permissions separate. Require IMDSv2 on build and test instances. Configure encrypted EBS storage in the recipe and approved KMS keys in distribution settings where required. Verify that authorized launch roles can use those keys.
Test the Worker Before Promotion
Test the candidate AMI on a new instance before any launch-template promotion. Add component assertions to check installed patches, package versions, services, and successful reboot completion. In an isolated subnet with a dedicated test queue, verify SSM access, runtime role access, encrypted EBS volume use, queue processing, and CloudWatch log delivery. Test the production bootstrap path in isolation, too.
Run a controlled workload that covers valid jobs, malformed input, retries, and interruption. Compare outputs against known fixtures, check processing and failure metrics, and verify checkpoint recovery. Send a drain signal and confirm that the worker shuts down cleanly within the drain deadline. Keep exact results - including job counts, failures, recovery time, and startup-to-ready time - not just a “passed” label. Do not promote the AMI if any assertion fails.
Record Image Details and Keep the Previous Baseline
Once validation passes, lock the exact image version and preserve the rollback path. Record AMI tags and deployment evidence for the source AMI, Region, architecture, patch baseline, recipe and component versions, application digest, UTC build timestamp, and test results. Link the candidate AMI to its numbered launch-template version before rollout.
Retain the previous known-good AMI, its EBS snapshots, and recipe versions until the observation window closes. Check that its KMS keys and required artifacts remain available. Keep the exact rollback image launchable until the observation window ends.
sbb-itb-61a6e59
Back to Basics: Automating Virtual Machine Image Creation
3. Publish the Launch Template and Replace Workers
After the patched AMI passes validation, publish a new launch-template version and roll it out through a controlled instance refresh.
Create a Launch-Template Version and Start Replacement
Create a numbered launch-template version from the known-good baseline. Change only the AMI and reviewed settings, then inspect the output before starting replacement.
Pass the new version number in DesiredConfiguration. Do not change the Auto Scaling group’s reference or the template default first. Install the termination hook and handler described below before running this sequence.
set -euo pipefail
# Environment-specific values: replace and verify before running.
export AWS_REGION="us-east-1"
export ENVIRONMENT="production"
export ASG_NAME="prod-data-workers"
export LT_ID="lt-0123456789abcdef0"
export BASE_LT_VERSION="42"
export PATCHED_AMI_ID="ami-0123456789abcdef0"
OPERATOR=$(aws sts get-caller-identity --query Arn --output text)
NEW_LT_VERSION=$(aws ec2 create-launch-template-version \
--region "$AWS_REGION" \
--launch-template-id "$LT_ID" \
--source-version "$BASE_LT_VERSION" \
--version-description "patched-worker-$(date -u +%Y%m%d)" \
--launch-template-data "{\"ImageId\":\"$PATCHED_AMI_ID\"}" \
--query 'LaunchTemplateVersion.VersionNumber' --output text)
# Review this output against the approved configuration before proceeding.
aws ec2 describe-launch-template-versions \
--region "$AWS_REGION" \
--launch-template-id "$LT_ID" \
--versions "$BASE_LT_VERSION" "$NEW_LT_VERSION"
read -r -p "Type APPROVED to start replacement: " APPROVAL
[[ "$APPROVAL" == "APPROVED" ]] || exit 1
STARTED_AT=$(date -u +%Y-%m-%dT%H:%M:%SZ)
REFRESH_ID=$(aws autoscaling start-instance-refresh \
--region "$AWS_REGION" \
--auto-scaling-group-name "$ASG_NAME" \
--desired-configuration \
"LaunchTemplate={LaunchTemplateId=$LT_ID,Version=$NEW_LT_VERSION}" \
--preferences '{
"MinHealthyPercentage":90,
"InstanceWarmup":300,
"CheckpointPercentages":[10,50],
"CheckpointDelay":600,
"AutoRollback":true,
"SkipMatching":true
}' \
--query InstanceRefreshId --output text)
printf '%s\n' \
"environment=$ENVIRONMENT operator=$OPERATOR started=$STARTED_AT" \
"asg=$ASG_NAME template=$LT_ID prior=$BASE_LT_VERSION target=$NEW_LT_VERSION" \
"ami=$PATCHED_AMI_ID refresh=$REFRESH_ID" \
| tee deployment-record.txt
aws autoscaling describe-instance-refreshes \
--region "$AWS_REGION" \
--auto-scaling-group-name "$ASG_NAME" \
--instance-refresh-ids "$REFRESH_ID"
Control Replacement With Capacity and Readiness Checks
Control replacement with refresh limits and readiness checks. Use an instance refresh, not manual termination, so replacement follows those controls.
On a 20-worker group, 90% minimum healthy capacity keeps 18 instances available.
Replace the 300-second warm-up with your measured startup-to-ready time. SkipMatching avoids replacing instances that already use the target configuration.
The 10% and 50% checkpoints give you early windows to validate the rollout. The 600-second delay replaces AWS’s 3,600-second default. But checkpoints are timed pauses - not health tests. Use external checks and CloudWatch alarms as release gates.
Have an external controller check registration, queue polling, smoke-job outputs, retries, and latency, then request rollback if those checks fail. EC2 health and InService status alone do not prove a worker is ready. This complexity is why modern data engineering roadmaps emphasize infrastructure automation alongside core pipeline development. Publish application signals to CloudWatch and connect decisive alarms to the refresh. AutoRollback=true does not detect application failures on its own.
Drain Jobs With a Termination Lifecycle Hook
Before replacement starts, create an autoscaling:EC2_INSTANCE_TERMINATING hook and connect its events to a drain handler. As the refresh starts terminating instances, the hook must hand off work to that handler.
The handler should move the worker into DRAINING, stop new claims, finish or durably checkpoint active jobs, safely release leases, and publish telemetry. Send lifecycle heartbeats while draining, with both a heartbeat timeout and an overall drain deadline. AWS allows heartbeat timeouts from 30 to 7,200 seconds. Extensions must not turn draining into an indefinite wait.
After draining, call CompleteLifecycleAction with CONTINUE. ABANDON also terminates the instance, but skips remaining lifecycle actions. If the deadline expires, leave unfinished jobs retryable. Checkpoints, leases, and idempotent writes must protect interrupted work.
4. Automate Monitoring and Rollback
Once the instance refresh starts, use alarms and rollback rules to control whether each replacement wave proceeds.
Set Rollout Alarms
Attach release-blocking CloudWatch alarms and enable automatic rollback before replacement begins. AWS supports up to 10 CloudWatch metric or composite alarms per refresh. Cover launch failures, registration failures, capacity loss, queue backlog, error rate, latency, and throttling.
Check alarm states and missing-data settings before deployment. Missing registration telemetry should block readiness. Missing queue metrics can remain non-breaching when the queue is empty. Base readiness windows on observed boot and registration times, but don’t let those windows hide sustained failures.
These alarms should trigger automatic rollback - not just help explain a failure afterward.
Roll Back Active or Completed Deployments
For an active refresh, call rollback-instance-refresh only while the refresh remains rollback-eligible. Track RollbackInProgress until it reaches a terminal state. Cancellation stops future replacements; it does not restore workers already replaced.
A completed refresh cannot be rolled back directly. Mark the AMI and launch-template version as failed, then start a new refresh using the previous numbered launch-template version. Before allowing promotion again, record the failed refresh ID, symptoms, deployment logs, alarm timeline, recovery version, and corrective action.
Save the rollback result in the same automation record used for promotion.
Define Automation Checks and Owners
Use AWS Systems Manager Automation to enforce the patched AMI workflow through approval, publication, refresh, drain, verification, and rollback. Give every step explicit inputs, outputs, timeouts, retry limits, and failure actions. Apply least-privilege roles, and keep AMI IDs, test results, approvals, alarm histories, refresh status, and rollback outcomes in the deployment record.
Put each control in a runbook or Automation document so teams can execute and audit it.
| Stage | Check | Signal | Failure action | Owner |
|---|---|---|---|---|
| Source approval | Patch scope approved | Approval record | Block build | Security |
| Build and publication | Tests pass; approved IDs match | Test and template evidence | Block publication | Platform engineering |
| Replacement | Workload gates pass | Rollout alarms | Request rollback | Data-platform on call |
| Lifecycle handling | Drain deadline met | Drain result | Escalate; protect retryable work | Data-platform on call |
| Recovery and reporting | Recovery verified | Status and evidence | Keep incident open | Incident owner |
Assign one owner to each failure path so the lock has a single decision-maker.
Lock the rollout before publication or refresh to prevent concurrent AMI or template changes during the refresh window. Record the lock owner, refresh ID, template version, creation time, and expiration.
Block overlapping refreshes, conflicting scaling actions, maintenance windows, and template changes, and notify their owners. Release the lock only after verification or a documented handoff.
| Phase | Control | Pass threshold | Evaluation window | Failure action |
|---|---|---|---|---|
| Pre-refresh | Registration test | Meets approved baseline | Measured readiness window | Block publication |
| In-refresh | Release-blocking alarms | Meets approved baseline | During rollout | Request rollback |
| Post-refresh | Status and workload verification | Successful; meets approved baseline |
Approved observation window | Block promotion; start recovery refresh |
5. Conclusion: Verify Results and Set the New Baseline
A successful refresh is not yet an approved baseline. Once the observation window closes, verify that you have an immutable AMI identified by its full AMI ID, the complete recorded image record, and a numbered launch-template version pointing to that AMI.
Confirm that replacement workers passed health checks and the startup window, then processed representative jobs. Check their results against the prior baseline for counts, checksums, schemas, partition placement, and downstream handoffs. Workers must also have drained within the timeout without lost or duplicated work, while maintaining minimum capacity and replacement headroom.
Record the alarm evaluation results for the observation window and the rollback state at close. State whether active-refresh rollback is still available or recovery requires a new refresh from the prior configuration. Keep the previous known-good AMI and numbered template version under the rollback-retention policy.
Promote only after replacement succeeds, workload checks pass, and the observation window closes without unresolved exceptions. Publish a brief closure record with the UTC rollout window, AMI and source image IDs, build and template versions, instance-refresh ID, capacity, drain and workload results, alarm status, exceptions, rollback deadline, owner, and evidence links.
Mark the exact AMI and template version as approved in the deployment registry. Update the image catalog and documented desired configuration before promoting the patched AMI as the new baseline.
FAQs
How do I size rollout batches for an uneven workload?
Size rollout batches around the heaviest transformation step, not the average file size. Divide work by partition - such as date, tenant, or region - so jobs can run in parallel without collisions. For bursty ETL workloads, use queue depth as the main scaling signal rather than CPU utilization. A growing queue gives an earlier warning of pending latency.
DataExpert.io Academy offers data engineering boot camps and subscriptions that teach these production orchestration strategies.
What if a job outlasts the drain deadline?
Plan for termination if a job runs past the drain deadline. Use idempotent writes so retries or resumed jobs don’t duplicate data. Add lifecycle hooks that tell workers to finish their current partition before shutting down.
If tasks repeatedly hit execution time limits, split the workload by time window or partition instead of just increasing the timeout.
How long should I monitor workers before approving an AMI?
Monitor workers through a full, stable run cycle that includes startup and normal operation - not just a short, fixed window.
Before approving the AMI and rolling forward, confirm that workers pass steady-state health checks and complete representative workloads without recurring job failures. Errors should stay at or below your acceptable thresholds. Drain jobs, and use monitoring and alarms to check worker behavior.