devHọc Dev

Week 4 - Day 2: Monitoring/Logging, EventBridge Automation and CI/CD

Week 4 – Day 2

This lesson combines 3 topics: Monitoring and Logging, EventBridge and Automation, CI/CD and DevOps on AWS.

Learning Objectives

  • Know the CloudWatch components (metrics, logs, alarms, dashboards) and the subscription filter pattern
  • Distinguish CloudTrail (who did what) vs Config (configuration state) vs X-Ray (request tracing)
  • Design multi-account centralized logging at the Professional level
  • Understand EventBridge event buses, rules, targets and event pattern matching
  • Know the Systems Manager modules used for automation (Patch, Session, Run Command, Automation)
  • Compare IaC options (CloudFormation, CDK, Terraform) by scenario
  • Know the Developer Tools chain (CodeBuild/CodeDeploy/CodePipeline) and the role of CodeConnections with external Git providers
  • Distinguish deployment strategies (rolling, blue/green, canary) by trade-off
  • Know the multi-account pipeline pattern and IaC selection at the Professional level

Part 1: Monitoring and Logging

1. CloudWatch Deep Dive

┌─────────────────────────────────────────────────────────┐│CLOUDWATCHCOMPONENTS││││METRICS:││├──Standard(1-minutefordetailed)││├──Custom(PutMetricDataAPI)││└──High-resolution(1-second)││││LOGS:││├──LogGroups→LogStreams→LogEvents││├──MetricFilters││├──SubscriptionFilters││└──LogInsights(querylanguage)││││ALARMS:││├──MetricAlarms││├──CompositeAlarms││└──Actions:SNS,AutoScaling,EC2││││DASHBOARDS:││└──Cross-account,cross-region││││EVENTS(EventBridge):││└──Rules→Targets(Lambda,SNS,etc.)│└─────────────────────────────────────────────────────────┘

2. CloudWatch Logs Architecture

┌─────────────────────────────────────────────────────────┐│LOGSDESTINATIONS││││Sources:││├──EC2(CloudWatchAgent)││├──Lambda(automatic)││├──VPCFlowLogs││├──APIGateway││└──Manymore...││││Processing:││┌─────────────────┐│││CloudWatchLogs│││└────────┬────────┘│││││SubscriptionFilter│││││┌─────┴─────┬─────────┬─────────┐││▼▼▼▼││KinesisLambdaOpenSearchFirehose││StreamsService→S3│└─────────────────────────────────────────────────────────┘

3. X-Ray

Distributed Tracing:
- Trace requests across services
- Service map visualization
- Performance bottleneck identification

Components:
- X-Ray SDK (in application)
- X-Ray Daemon (collects and sends traces)
- X-Ray Console (analysis)

Sampling:
- First request each second: traced
- 5% of additional requests: traced
- Custom sampling rules available

4. CloudTrail

┌─────────────────────────────────────────────────────────┐│CLOUDTRAIL││││EventTypes:││├──ManagementEvents(default)│││└──APIcalls(CreateBucket,RunInstances)││├──DataEvents(extracost)│││└──S3objectoperations,Lambdainvocations││└──InsightsEvents││└──Unusualactivitydetection││││TrailConfigurations:││├──Singleregionorallregions││├──Organizationtrail││├──LogtoS3and/orCloudWatchLogs││└──EncryptionwithKMS││││BestPractice:││-Enableinallregions││-LogtocentralizedS3bucket││-Enablelogfilevalidation│└─────────────────────────────────────────────────────────┘

5. AWS Config

Configurationtrackingandcompliance:Rules:├──AWSManagedRules(200+)└──CustomRules(Lambda)Examples:-s3-bucket-public-read-prohibited-encrypted-volumes-iam-password-policyConformancePacks:-Pre-builttemplates-PCIDSS,HIPAA,CIS-Custompacks

6. AWS Health (Personal Health Dashboard)

Monitoring is not only about workload metrics/logs; you also need to know when AWS itself has an incident or schedules maintenance that affects your resources. That is the job of AWS Health.

6.1. The two views of the AWS Health Dashboard

Service healthYour account health
Old nameService Health Dashboard (SHD)Personal Health Dashboard (PHD)
ScopeGeneral status of every service/region, public, no sign-in requiredEvents affecting YOUR resources (personalized per account)
ContentWhich services are operational/degraded in which regionsScheduled changes (EC2 instance retirement, EBS/RDS maintenance), service issues currently impacting specific resources
DetailDoes not tell you whether you are affectedEvent timeline + list of affected resources (instance ID, volume ID...)

When the exam asks "how to know if your resources are affected by an AWS event" → Your account health (PHD), not the public status page.

6.2. AWS Health API and organizational view

  • AWS Health API: programmatic access to health events; requires a Business or Enterprise Support plan (a common trap in questions).
  • Organizational view: enabled in the management account (or a delegated administrator) → aggregates health events of all member accounts in the Organization in one place. The standard pattern for a central ops team tracking incidents/maintenance across hundreds of accounts without logging in to each one.

6.3. Automation with EventBridge

AWS Health emits events to EventBridge (source aws.health) → rule → automation target:

┌─────────────────────────────────────────────────────────┐│AUTO-REMEDIATION:EC2INSTANCERETIREMENT││││AWSHealthevent:││"EC2instancescheduledforretirement"│││││▼││┌──────────────┐rulematch:│││EventBridge│source=aws.health│││Rule│eventTypeCode=││└──────┬───────┘AWS_EC2_INSTANCE_RETIREMENT_│││SCHEDULED││┌────┴─────────────┐││▼▼││┌──────┐┌─────────┐│││SNS││Lambda│──▶stop→startinstance│││notify│└─────────┘(EBS-backed→moves│││ops│toanewhostBEFORE││└──────┘retirementdeadline)│└─────────────────────────────────────────────────────────┘

A classic exam example: AWS schedules the retirement of a physical host → the event EC2 instance scheduled for retirement appears in the PHD → an EventBridge rule catches the event → Lambda stops and then starts the instance (EBS-backed) so it is placed on a new host before the deadline, instead of waiting for AWS to force it. SNS runs in parallel to notify on-call.

6.4. Exam keywords

  • "be notified when AWS schedules maintenance on YOUR resources" → AWS Health (Your account health / PHD) + EventBridge → SNS. Not a CloudWatch metric; retirement/maintenance is not a workload metric.
  • "automate response to instance retirement" → AWS Health event + EventBridge rule + Lambda (stop/start).
  • "aggregate health events across all accounts in the Organization" → AWS Health organizational view (delegated admin; the Health API needs Business/Enterprise Support).

7. Resilience, Incident Response and Quota Automation

Domain 3 (Continuous Improvement) does not stop at "having metrics and logs". Questions ask about validating fault tolerance, coordinating during incidents, and automatically handling service limits.

ServiceWhat it doesExam keyword
CloudWatch Contributor InsightsRules read a log group (JSON/CLW format) and compute the top-N contributors in real time: the IPs calling the most, the URLs with the most errors, the hottest DynamoDB partition keys"identify which clients/keys generate the most traffic/errors" → Contributor Insights, not Logs Insights (ad hoc queries)
AWS Resilience HubYou declare an RTO/RPO policy for the application (from CloudFormation/Terraform/Resource Group); Resilience Hub assesses the architecture, scores it, gives recommendations (add AZs, enable backups, Multi-AZ) and generates alarms/SOPs/FIS experiments"assess whether the application meets RTO/RPO targets and get recommendations"
AWS Fault Injection Service (FIS)Controlled chaos engineering: experiment templates (stop EC2, throttle APIs, lose an AZ, network latency), with a stop condition tied to a CloudWatch alarm to halt automatically when a threshold is breached"validate resilience by injecting failures in a controlled manner"
Amazon Application Recovery Controller (ARC) (formerly Route 53 ARC)Routing control: on/off switches per cell/Region, with state changed through a cluster of 5 endpoints in 5 Regions (a highly available data plane) → manual, controlled failover; zonal shift / zonal autoshift moves traffic away from an impaired AZ; Region switch orchestrates failover of a whole application to another Region according to a plan. Readiness check no longer accepts new customers."fail over between Regions in a controlled, operator-initiated way during a large-scale event" → ARC routing control / Region switch; "shift traffic away from an impaired AZ" → zonal shift
Incident Manager + OpsCenter (Systems Manager)OpsCenter aggregates OpsItems from CloudWatch alarms/EventBridge/Config; Incident Manager creates a response plan: escalation, on-call schedule, chat channel, an Automation runbook that runs automatically when an alarm fires. Incident Manager no longer accepts new customers; the exam may still ask about it; new customers use OpsCenter + Automation or another on-call tool"automatically engage on-call responders and run a runbook when a critical alarm fires"
Service Quotas automationService Quotas publishes usage metrics to CloudWatch → alarm at ≥ 80% of the quota → EventBridge/Lambda calls RequestServiceQuotaIncrease; a quota request template makes new accounts in the org request quotas automatically when created"proactively avoid hitting service limits across new accounts" → quota request template + alarm, not manual Trusted Advisor
Chaos/resilienceloop(Domain3):ResilienceHub(assess,RTO/RPOgaps)──▶FISexperiment(realfaulttest)▲││CloudWatchalarm=stopcondition│└────IncidentManager/OpsCenter◀──────┘(realincident:responseplan)

Commonly tested distinctions: Trusted Advisor only reports service limits (for some checks), while Service Quotas has the API to request increases and the metrics to alarm on; Logs Insights is on-demand querying, Contributor Insights is a continuously running rule for top-N; Route 53 health check failover is automatic (health checks and DNS answers run on the Route 53 data plane) but the decision is made by the health check, which can flap during partial failures; ARC routing control lets an operator fail over deliberately through the 5-Region cluster, suited to large incidents that need control.

Part 2: EventBridge and Automation

1. Amazon EventBridge

┌─────────────────────────────────────────────────────────┐│EVENTBRIDGE││││EventSources:││├──AWSServices(built-in)││├──CustomApplications││├──SaaSPartners(Zendesk,Datadog)││└──ScheduledEvents(cron)││││┌─────────────────────────────────────────────────┐│││EventBus││││┌────────────────────────────────────────────┐│││││Rules││││││-EventPatternmatching││││││-Scheduleexpressions│││││└────────────────────────────────────────────┘│││││││││┌──────┴──────┐││││▼▼││││TargetsTargets││││(Lambda)(SNS,SQS)│││└─────────────────────────────────────────────────┘││││EventBuses:││├──Default(AWSevents)││├──Custom(yourevents)││└──Partner(SaaSevents)│└─────────────────────────────────────────────────────────┘

2. Event Patterns

{
  "source": ["aws.ec2"],
  "detail-type": ["EC2 Instance State-change Notification"],
  "detail": {
    "state": ["stopped", "terminated"]
  }
}

3. AWS Systems Manager

┌─────────────────────────────────────────────────────────┐│SYSTEMSMANAGER││││Inventory:││└──Collectmetadatafrominstances││││PatchManager:││└──AutomateOSpatching││││SessionManager:││└──SecureshellaccesswithoutSSH││││ParameterStore:││└──Centralizedconfiguration││││Automation:││└──Runbooksforoperationaltasks││││StateManager:││└──Maintaininstanceconfiguration││││RunCommand:││└──Executecommandsatscale│└─────────────────────────────────────────────────────────┘

4. Infrastructure as Code

CloudFormation:
- Native AWS
- JSON/YAML templates
- StackSets for multi-account/region

AWS CDK:
- Code-first approach
- TypeScript, Python, Java, C#
- Generates CloudFormation

Terraform:
- Multi-cloud
- HCL language
- State management

Part 3: CI/CD and DevOps on AWS

CI/CD Overview

┌─────────────────────────────────────────────────────────────┐│CI/CDPIPELINE││││SOURCEBUILDTESTDEPLOYMONITOR│││││││││▼▼▼▼▼││GitHubCodeBuildCodeBuildCodeDeployCloudWatch││GitLab+Tests+Scans+PipelinesX-Ray││Bitbucket││(viaCodeConnections)││││◄───────CodePipelineorchestrates───────►│└─────────────────────────────────────────────────────────────┘

AWS Developer Tools

1. Source control: CodeCommit or GitHub/GitLab/Bitbucket via CodeConnections

CodeCommit status update (important for the 2026 exam): in 07/2024 AWS stopped accepting new CodeCommit customers, but on 24/11/2025 AWS announced that CodeCommit is back to General Availability and reopened sign-ups for new customers (The Future of AWS CodeCommit). So do NOT eliminate an option just because it contains CodeCommit. Choose by the stem's requirements: an AWS-managed Git repo with IAM authorization, VPC endpoint access, CloudTrail logging and no third-party dependency points to CodeCommit; code that already lives in GitHub, GitLab or Bitbucket connects to CodePipeline/CodeBuild through AWS CodeConnections (formerly CodeStar Connections). Questions written between 07/2024 and 11/2025 may still treat CodeCommit as legacy, so always read the requirements instead of choosing by service name.

Third-partyrepos(codealreadyinGitHub/GitLab/Bitbucket):├──GitHub/GitLab/Bitbucket+CodeConnections│├──OAuth/app-basedconnection,managedwithIAM│├──TriggerCodePipelineonpush/PR│└──NocredentialstomanageinthepipelineCodeCommit(AWS-managed,backtoGAsince11/2025):├──Fullymanagedsourcecontrol,encrypted├──IntegrateswithIAM├──Pullrequests,branches,triggers└──VPCendpoints,CloudTrail,nothird-partydependencyBestPractices:-Branchprotectionrules-CodereviewviaPRs-IntegratewithCodeGuruReviewer

2. AWS CodeBuild

┌─────────────────────────────────────────────────────────────┐│CODEBUILD││││Managedbuildservice:││├──Compilessourcecode││├──Runstests││├──Producesartifacts││└──Scalesautomatically││││BuildEnvironments:││├──Managedimages(AmazonLinux,Ubuntu,Windows)││├──CustomDockerimages││└──GPU-enabledbuilds││││buildspec.yml:││├──phases:install,pre_build,build,post_build││├──artifacts:outputfiles││└──cache:speedupbuilds│└─────────────────────────────────────────────────────────────┘

buildspec.yml Example:

version: 0.2
phases:
  install:
    runtime-versions:
      nodejs: 18
  pre_build:
    commands:
      - npm install
  build:
    commands:
      - npm run build
      - npm test
  post_build:
    commands:
      - echo "Build completed"
artifacts:
  files:
    - '**/*'
  base-directory: dist
cache:
  paths:
    - node_modules/**/*

3. AWS CodeDeploy

┌─────────────────────────────────────────────────────────────┐│CODEDEPLOY││││DeploymentTargets:││├──EC2/On-premises││├──ECS(Blue/Green)││└──Lambda(Trafficshifting)││││DeploymentStrategies:││├──In-place(EC2)││├──Blue/Green(EC2,ECS)││├──Canary(Lambda:10%,wait,100%)││├──Linear(Lambda:10%everyXminutes)││└──All-at-once│└─────────────────────────────────────────────────────────────┘DeploymentConfiguration:-Minimumhealthyhosts-Rollbacksettings-Lifecyclehooks

appspec.yml (EC2):

version: 0.0
os: linux
files:
  - source: /
    destination: /var/www/html
hooks:
  BeforeInstall:
    - location: scripts/before_install.sh
  AfterInstall:
    - location: scripts/after_install.sh
  ApplicationStart:
    - location: scripts/start.sh
  ValidateService:
    - location: scripts/validate.sh

4. AWS CodePipeline

┌─────────────────────────────────────────────────────────────┐│CODEPIPELINE││││Orchestrationservice:││├──Visualworkflowdesigner││├──Stage-basedexecution││├──Parallelactions││└──Manualapprovalgates││││PipelineStructure:││┌──────────┐┌──────────┐┌──────────┐┌──────────┐│││Source│→│Build│→│Test│→│Deploy│││└──────────┘└──────────┘└──────────┘└──────────┘││││Integrations:││-GitHub,GitLab,Bitbucket││-Jenkins││-CloudFormation,CDK││-ECS,EKS,Lambda,S3│└─────────────────────────────────────────────────────────────┘

Deployment Strategies Deep Dive

1. Rolling Deployment

┌────────────────────────────────────────────────────────────┐│ROLLINGDEPLOYMENT││││Step1:[v1][v1][v1][v1]→Allrunningv1││Step2:[v2][v1][v1][v1]→Firstbatchupdated││Step3:[v2][v2][v1][v1]→Secondbatchupdated││Step4:[v2][v2][v2][v2]→Allrunningv2││││Pros:Noextrainfrastructure││Cons:Mixedversionsduringdeployment│└────────────────────────────────────────────────────────────┘

2. Blue/Green Deployment

┌────────────────────────────────────────────────────────────┐│BLUE/GREENDEPLOYMENT││││BLUE(Current)GREEN(New)││┌─────────────┐┌─────────────┐│││v1│v1││v2│v2│││└─────────────┘└─────────────┘││▲│││││[LoadBalancer]───Switchtraffic───►││││Step1:DeploytoGreen││Step2:TestGreen││Step3:SwitchtrafficBlue→Green││Step4:KeepBlueforrollback││││Pros:Instantrollback,nodowntime││Cons:Doubleinfrastructurecostduringdeploy│└────────────────────────────────────────────────────────────┘

3. Canary Deployment

┌────────────────────────────────────────────────────────────┐│CANARYDEPLOYMENT││││Step1:10%traffictov2,90%tov1││││┌───────────────────────────────────────┐│││[v1][v1][v1][v1][v1][v1][v1][v1][v1]│90%││└───────────────────────────────────────┘││┌─────┐│││[v2]│10%││└─────┘││││Step2:Monitormetrics,errors││Step3:IfOK,graduallyincreaseto100%││Step4:Ifissues,rollbackimmediately││││Pros:Earlydetectionofissues││Cons:Complexrouting,monitoringrequired│└────────────────────────────────────────────────────────────┘

Infrastructure as Code

AWS CloudFormation

┌─────────────────────────────────────────────────────────────┐│CLOUDFORMATION││││Template→Stack→Resources││││KeyConcepts:││├──Templates(YAML/JSON)││├──Stacks(resourcecollection)││├──StackSets(multi-account/region)││├──ChangeSets(previewchanges)││└──DriftDetection││││BestPractices:││├──Usenestedstacksformodularity││├──Parameterizetemplates││├──UseMappingsforregion-specificvalues││└──Enableterminationprotection│└─────────────────────────────────────────────────────────────┘

AWS CDK (Cloud Development Kit)

Defineinfrastructureusingprogramminglanguages:├──TypeScript├──Python├──Java├──C#└──GoCDK→CloudFormationtemplate→ResourcesBenefits:-Typesafety-IDEsupport-Reusableconstructs-Testingcapabilities

Terraform on AWS

Multi-cloudIaCtool:├──HCL(HashiCorpConfigurationLanguage)├──Statemanagement(local,S3,TerraformCloud)├──Providerecosystem└──ModulesforreusabilityAWSProviderfeatures:-AllAWSservicessupported-Importexistingresources-Driftdetection

CodeGuru

CodeGuru Reviewer

AI-poweredcodereview:├──Securityvulnerabilities├──Performanceissues├──Bestpractices├──AWSSDKusage└──IntegrateswithPRs

CodeGuru Profiler

Applicationperformance:├──CPUutilizationanalysis├──Memoryprofiling├──Heapusage├──Latencyidentification└──Costrecommendations

Exam Scenarios

Scenario 1: Zero-Downtime Deployment

Requirement:DeployupdateswithoutdowntimeSolution:├──ECSwithBlue/GreenviaCodeDeploy├──ALBfortrafficshifting├──Healthchecksbeforeswitch└──Automaticrollbackonfailure

Scenario 2: Multi-Account Pipeline

Requirement:DeploytoDev,Staging,ProdaccountsSolution:├──CodePipelineincentralaccount├──Cross-accountIAMroles├──ManualapprovalbeforeProd└──CloudFormationStackSets

Scenario 3: Container CI/CD

Requirement:BuildanddeploycontainersSolution:├──GitHub(CodeConnections)→CodeBuild(buildimage)├──PushtoECR├──CodeDeploytoECS├──Blue/Greendeployment└──Automatedrollback

Quick Reference

┌─────────────────────────────────────────────────────────────┐│CI/CDTOOLSELECTION││││Need│Service││────────────────────────┼───────────────────────││Sourcecontrol│GitHub/GitLab/Bitbucket│││+CodeConnections│││(orCodeCommit:AWS-managed,│││backtoGAsince11/2025)││Build/Test│CodeBuild││DeployEC2│CodeDeploy││DeployECS│CodeDeploy(Blue/Green)││DeployLambda│CodeDeploy(Canary/Linear)││DeployK8s│ArgoCD,Flux││Orchestratepipeline│CodePipeline││IaC│CloudFormation,CDK,Terraform││Multi-accountdeploy│StackSets,CodePipeline││Codereview│CodeGuruReviewer││Performanceanalysis│CodeGuruProfiler│└─────────────────────────────────────────────────────────────┘

CloudFormation Custom Resources & Resource Import

Custom Resources: running logic CloudFormation doesn't support

When a stack needs to do something for which CloudFormation has no corresponding resource type, use a Custom Resource: a "virtual" resource whose lifecycle (Create/Update/Delete) is handled by your code, either Lambda-backed (the most common) or SNS-backed (sends the event to a topic, typically for an on-premises/external system to handle).

┌─────────────────────────────────────────────────────────────┐│CUSTOMRESOURCEFLOW││││CFNStack──(Create/Update/Deleteevent)──►Lambda││▲││││▼││└──(SUCCESS/FAILEDresponse)◄──pre-signedS3URL││(cfn-response)││││Stackwaitsforaresponse;nonesent=hangsuntil││ServiceTimeout│└─────────────────────────────────────────────────────────────┘

How it works:

  • The template declares Custom::<Name> (or AWS::CloudFormation::CustomResource) with the required property ServiceToken pointing to a Lambda ARN (or an SNS topic ARN).
  • On stack Create/Update/Delete, CFN invokes the Lambda with an event containing RequestType (Create/Update/Delete), ResourceProperties, and ResponseURL, a pre-signed S3 URL.
  • The Lambda MUST send a response (SUCCESS/FAILED) to ResponseURL, using the cfn-response module (available when writing inline code) or the crhelper library. Forgetting to send the response = the stack hangs in CREATE_IN_PROGRESS/DELETE_IN_PROGRESS until ServiceTimeout expires (default 3600 seconds = 1 hour, configurable from 1 to 3600 seconds) and only then FAILS; a classic mistake. Set a short ServiceTimeout (e.g. 300) when the Lambda only needs a few seconds, so errors surface early.

Classic exam use cases:

  1. Empty an S3 bucket before deleting the stack: CFN cannot delete a bucket that still has objects; a custom resource receives the Delete event → deletes all objects (including versions) → the bucket can be deleted. (As of 2023 AWS::S3::Bucket has no auto-empty property; the custom resource is still the standard answer.)
  2. Call a third-party API during provisioning (register a license, create a record in a SaaS, look up the latest AMI ID...).
  3. Provision resources CFN doesn't support yet (new services, new features without a resource type).

YAML snippet (Lambda-backed, empty bucket on delete):

Resources:
  MyBucket:
    Type: AWS::S3::Bucket

  EmptyBucketOnDelete:
    Type: Custom::EmptyBucket
    Properties:
      ServiceToken: !GetAtt EmptyBucketFunction.Arn   # Lambda ARN, required
      BucketName: !Ref MyBucket
# Inside the Lambda handler (simplified)
import cfnresponse
def handler(event, context):
    if event['RequestType'] == 'Delete':
        empty_bucket(event['ResourceProperties']['BucketName'])
    cfnresponse.send(event, context, cfnresponse.SUCCESS, {})  # REQUIRED

Professional note: when you need reuse across many accounts/teams, consider upgrading the custom resource to a CloudFormation Registry private resource type / hook; but when the question only asks for "one-off logic in a stack", a custom resource is the leanest answer.

Resource Import: bringing manually created resources into a stack

Problem: legacy infrastructure created by hand (console/CLI) lives outside IaC, and you want to manage it with CloudFormation without recreating it (no downtime, no ARN change).

Solution: Resource Import (cloudformation import, console: Stack actions → Import resources into stack):

ManuallycreatedTemplatedescribesresourceStackmanagesS3bucket──import──►(matchesactualconfig,──►bucketlikeany(outsideIaC)hasDeletionPolicy)otherresource
  • The template must describe the resource with its actual identifier (e.g. BucketName), and every imported resource MUST have a DeletionPolicy (usually Retain); this is a hard requirement of the import operation.
  • The resource type must support import (most common resources do).
  • You can import into a new stack or an existing stack; import does not change the resource, it only attaches it to the stack.
  • Best practice after import: run Drift Detection immediately to confirm the template matches 100% of the actual configuration; hand-written templates easily miss properties, and drift detection exposes the differences before a stack update causes unintended changes.

Use case: bring legacy infrastructure into IaC on a roadmap (governance, review via change sets) without migrating/recreating resources.

Exam keywords

Exam keywordAnswer
"Delete stack fails because S3 bucket is not empty"Lambda-backed custom resource that empties the bucket on the Delete event
"Provision resource/call API CloudFormation doesn't support"Custom resource (ServiceToken → Lambda/SNS)
"Bring existing resources under CloudFormation management without recreating"Resource Import (+ required DeletionPolicy, drift detection after import)
"Stack stuck in CREATE_IN_PROGRESS with custom resource"The Lambda forgot to send cfn-response to the pre-signed URL

EC2 Image Builder

Problem: the organization needs a golden image (a hardened AMI/container image with agents preinstalled and the latest patches) rebuilt periodically and distributed to many regions and many accounts; doing it by hand with Packer/scripts + Lambda + EventBridge involves many moving parts. EC2 Image Builder is a managed service that handles this whole pipeline.

┌──────────────────────────────────────────────────────────────┐│EC2IMAGEBUILDERPIPELINE││││SOURCEBUILDTESTDISTRIBUTE││┌────────┐┌──────────────┐┌──────────┐┌──────────┐│││Base│──►│Build│──►│Test│─►│Multi-││││image││components││components││region││││(AMI/││(install││(smoke/││copy+││││ECR)││agents,││security││share││││││patch,harden)││tests)││accounts│││└────────┘└──────────────┘└──────────┘└──────────┘││▲│││Schedule:cron/whenthebaseimagehasanew│││version(e.g.monthlyafterPatchTuesday)│└──────────────────────────────────────────────────────────────┘

Main components:

  • Components: build steps (install software, hardening, patching) and test steps (validate the image before distribution), written as YAML documents; AWS provides many managed components (e.g. update-linux, STIG hardening, Inspector tests).
  • Image recipe (AMI) / container recipe (Docker image for ECR): base image + list of components + version.
  • Infrastructure configuration: instance type, subnet, IAM instance profile used for build/test.
  • Distribution configuration: copy the AMI to multiple regions, share cross-account (launch permissions for accounts/OUs, or via AWS RAM / AWS Organizations), attach license configurations, ECR output alias for containers.
  • Pipeline + schedule: runs on a cron (e.g. monthly when patches are released) or when a dependency has a new version (semantic versioning on the base image/components), so the golden image is always fresh without manual work.

Professional points to remember:

  • The build instance needs the Systems Manager Agent; Image Builder drives the build through SSM (AWS base images already include the SSM Agent; Image Builder installs it if missing).
  • Free: you only pay for the underlying resources (EC2 build instances, EBS, S3 logs, data transfer/AMI copies).
  • Builds both AMIs and container images (ECR output).
  • Combinations: the pipeline outputs a new AMI → EventBridge/SNS notification → update the Launch Template version for the ASG, or use it as the base for a CodePipeline.

Exam keyword: "automate golden AMI creation and distribution across accounts/regions with least operational overhead" → EC2 Image Builder (NOT a hand-built Packer + Lambda + Step Functions setup, which has more operational overhead); "monthly patched AMI shared to all accounts in the organization" → an Image Builder pipeline with a monthly schedule + a distribution configuration sharing via Organizations/RAM.


Review Questions

  1. CloudTrail vs Config: what is the core difference and when do you use both?

    Show answer

    CloudTrail answers "WHO called which API, when, from where" (an audit trail of API calls). Config answers "what configuration does/did the resource have, and is it compliant" (configuration timeline + rules). Example, a security group opened to 0.0.0.0/0: a Config rule detects the non-compliant state (+ auto-remediation), and CloudTrail tells you who called AuthorizeSecurityGroupIngress. A complete incident investigation needs both. A question asking "who made the change" → CloudTrail; "detect non-compliant configuration + remediate" → Config.

  2. When do you use a subscription filter instead of exporting to S3?

    Show answer

    Subscription filter: streams logs near real-time to Lambda (immediate processing), Kinesis Data Streams (multiple consumers), Firehose (delivery to S3/OpenSearch); used for real-time alerting and cross-account centralized logging (destination in the central log account). Export task to S3: batch, with up to 12 hours of delay; only for manual archiving. The standard multi-account pattern: each account has a subscription filter → Kinesis/Firehose in the log-archive account → S3 + Athena for analysis.

  3. What problem does a composite alarm solve?

    Show answer

    It combines multiple alarms with AND/OR to reduce alarm noise: alert only when (high CPU AND high latency), or suppress child alarms while a maintenance alarm is active. Professional use case: hundreds of microservices; instead of on-call receiving 50 alerts when one AZ fails, a composite alarm rolls them into one "AZ degradation" alert. Actions are still SNS/Auto Scaling like regular metric alarms.

  4. What advantage does a CloudTrail organization trail have over per-account trails?

    Show answer

    You create it once in the management account (or a delegated administrator) → it automatically applies to every member account, including accounts that join later, and members cannot turn it off; this guarantees 100% audit coverage regardless of individual teams. Logs go to one central S3 bucket (usually in the log-archive account) with log file validation + KMS. This is the standard answer for "ensure all accounts in Organization log API activity, prevent tampering".

  5. AWS announces that an EC2 instance is "scheduled for retirement". How do you get notified and handle it automatically before the deadline?

    Show answer

    This event appears in the AWS Health Dashboard: Your account health (Personal Health Dashboard) as a scheduled change, with the affected resources; it is not a CloudWatch metric, so regular alarms won't catch it. Solution: an EventBridge rule matching source = aws.health, eventTypeCode = AWS_EC2_INSTANCE_RETIREMENT_SCHEDULED → target SNS (notify ops) + Lambda that automatically stops → starts the instance (EBS-backed) so it moves to a new host before the deadline. To aggregate events across the Organization → enable the organizational view with a delegated administrator (the Health API requires Business/Enterprise Support).

  6. A multi-Region application must fail over to the secondary Region based on an operator's decision during a large-scale incident, without automatic health check flapping. What do you use?

    Show answer

    Amazon Application Recovery Controller (ARC) routing control (or Region switch to orchestrate the whole application): the on/off state is changed through a cluster of 5 endpoints in 5 Regions, tied to Route 53 health checks so DNS shifts as soon as the operator flips the switch; this operation does not require editing DNS records (which is a control plane action). Regular health check failover (Week 2 Day 4) also runs on the data plane but is automatic based on health checks, which is hard to control during partial failures. Within a Region, use zonal shift to move traffic away from an impaired AZ. Note: ARC readiness check no longer accepts new customers.

  7. How does EventBridge differ from SNS for event routing?

    Show answer

    EventBridge: content-based filtering on the entire event payload (pattern matching), 130+ SaaS/AWS sources, schema registry, archive + replay, input transformation, cross-account event buses. SNS: simple pub/sub, filtering on message attributes, fan-out to millions of subscribers (including email/SMS/mobile push), lower latency and higher throughput. Professional note: EventBridge does not guarantee ordering and delivery is at-least-once; if you need ordering, use SNS FIFO/SQS FIFO. Keyword "route events from SaaS app" or "filter on complex event content" → EventBridge.

  8. How does Session Manager replace SSH, and why is it "most secure"?

    Show answer

    Session Manager provides shell access without opening port 22, without a bastion host, without SSH keys; the instance only needs the SSM Agent + an IAM role, connecting outbound to the SSM endpoints (via VPC endpoints for private subnets). Access is controlled with IAM policies (who can access which instance), and sessions are fully logged to CloudTrail + S3/CloudWatch Logs (every command audited). The standard answer for "secure shell access, no inbound ports, full audit trail".

  9. What do you use to automatically patch a multi-account EC2 fleet?

    Show answer

    Patch Manager with a patch baseline + maintenance window; scale to multi-account/multi-region with Systems Manager Automation + AWS Organizations integration (targeting OUs) or Quick Setup. The full pattern: EventBridge schedule → SSM Automation runbook → Run Command patching by tag, reporting compliance to SSM Compliance + Security Hub. A question asking to "automate patching across all accounts with least operational overhead" → Patch Manager + Organizations, not custom scripts/Lambda.

  10. When do you choose StackSets over a regular stack?

Show answer

StackSets deploy the same template to many accounts/regions from a single point of management; with service-managed permissions integrated with Organizations, they automatically deploy to accounts that join an OU (auto-deployment). Use case: a security baseline (Config rules, IAM roles, GuardDuty) for the whole Organization. A regular stack lives in only 1 account/region. Keyword "deploy IAM roles to every account in the Organization automatically" → service-managed StackSets.

  1. On the 2026 exam, when do you choose CodeCommit and when GitHub/GitLab/Bitbucket + CodeConnections?
Show answer

CodeCommit stopped accepting new customers in 07/2024 but has been back in General Availability since 24/11/2025, so it is no longer an option to eliminate by default. Choose CodeCommit when the stem needs an AWS-managed Git repo: IAM authorization, private access through VPC endpoints, CloudTrail logging, no external vendor dependency. Choose GitHub/GitLab/Bitbucket + AWS CodeConnections (formerly CodeStar Connections) when the code already lives on those platforms: the connection is managed with IAM and no credentials are stored in the pipeline. Unlike the SMS → MGN pair (SMS is fully discontinued), CodeCommit is a fully supported service.

  1. What is the trade-off between Blue/Green and Canary?
Show answer

Blue/Green: shifts 100% of traffic at once after testing Green; rollback is instant (switch back), but it costs double the infrastructure during deployment, and a bug (if it slips past testing) affects all users. Canary: sends 10% of traffic to the new version, monitors, then increases gradually; detects errors early with a small blast radius, but needs more complex routing + monitoring and deploys more slowly. Lambda uses canary/linear through alias traffic shifting; ECS uses blue/green through CodeDeploy + ALB.

  1. What pieces does a multi-account pipeline (dev → staging → prod) need?
Show answer

(1) CodePipeline in a central account (tooling/shared services), (2) cross-account IAM roles that deploy actions assume in each target account, (3) an artifact bucket + KMS key that target accounts are allowed to read (bucket policy + key policy), (4) a manual approval gate before prod, (5) CloudFormation StackSets if you deploy standardized infrastructure to many accounts. A common trap: forgetting to grant the KMS key cross-account → deployment fails even though the roles are correct.

  1. Which compute targets does CodeDeploy support, and with which strategies?
Show answer

(1) EC2/on-premises: in-place (per deployment config: OneAtATime, HalfAtATime, AllAtOnce) or blue/green with a new ASG; hooks in appspec.yml. (2) ECS: blue/green through ALB target groups (new task set, test listener, switch). (3) Lambda: canary (10% then 100%) or linear (10% every X minutes) through an alias, with alarms + hooks (BeforeAllowTraffic/AfterAllowTraffic) for auto-rollback. Choose based on the compute in the question; there is no "CodeDeploy for an S3 static site" (that is a pipeline + S3 deploy action).

  1. Delete stack fails because an S3 bucket still has objects: how do you solve it with CloudFormation? And what if you want to bring a manually created bucket into a stack?
Show answer

Bucket not empty: CloudFormation cannot delete a bucket that still has objects → use a Lambda-backed custom resource (Custom::EmptyBucket with ServiceToken pointing to the Lambda ARN); the Lambda receives the Delete event, deletes all objects (including versions) and then must send a response (cfn-response) to the pre-signed S3 URL; forgetting it = the stack hangs until timeout. Manually created bucket: use Resource Import (cloudformation import); the template describes the bucket with its actual configuration and must have a DeletionPolicy; import does not recreate/change the resource, and after import you run drift detection to confirm the template matches reality.

  1. The requirement is "golden AMI patched monthly, distributed to every region and every account in the Organization, least operational overhead". What do you choose, and why not build it yourself?
Show answer

EC2 Image Builder: a managed build → test → distribute pipeline; an image recipe (base image + build/test components), a monthly cron schedule (or a trigger when the base image has a new version), and a distribution configuration that copies the AMI multi-region + shares it cross-account via AWS RAM/Organizations. Builds run through the SSM Agent, and the service is free (you only pay for EC2/EBS/S3 during the build). A hand-built Packer + Lambda + EventBridge + AMI copy/share scripts would produce the same result but with more operational overhead, which misses the question's keyword. Image Builder can also build container images to ECR.

Hands-on Exercises

Part 1: Monitoring and Logging

  1. Metric filter + alarm: create a metric filter counting the ERROR pattern in a Lambda's log group, attach an alarm with a threshold of ≥ 5 errors/5 minutes that sends an SNS email; inject test errors to verify.

  2. Cross-account subscription filter: create a CloudWatch Logs destination (Kinesis) in account B and a subscription filter in account A pointing to it; verify log events flow cross-account. This is the backbone of centralized logging.

  3. Config rule + timeline: enable the Config recorder, deploy the managed rule encrypted-volumes; create an unencrypted EBS volume and watch the resource timeline turn NON_COMPLIANT.

  4. X-Ray tracing: enable Active tracing on a Lambda behind API Gateway, send a few requests and read the service map to find the bottleneck.

Part 2: EventBridge and Automation

  1. Automation EventBridge rule: create a rule that catches the EC2 Instance State-change Notification event with state stopped, targeting a Lambda that tags the instance with stopped-at; stop an instance and verify.

  2. Session Manager without SSH: launch an EC2 instance in a private subnet without a key pair, attach the AmazonSSMManagedInstanceCore role, connect with Session Manager and enable session logging to CloudWatch Logs.

  3. SSM Automation runbook: run the AWS-RestartEC2Instance runbook on an EventBridge schedule; then write a 2-step custom runbook (create AMI → restart) to understand the document structure.

Part 3: CI/CD and DevOps on AWS

  1. GitHub → CodeBuild → S3 pipeline: create a CodeConnections connection to a personal GitHub repository, build a 3-stage CodePipeline (Source → Build → Deploy S3 static site); push a commit and watch the pipeline run automatically.

  2. Lambda canary deployment: deploy a Lambda with a live alias, configure CodeDeploy Canary10Percent5Minutes with a CloudWatch error-rate alarm; deploy a deliberately broken version and observe the auto-rollback.

  3. Blue/Green ECS: with the ECS service from the week 5 lesson, create a blue/green CodeDeploy application through an ALB with 2 target groups; deploy a new image and try a manual rollback before the termination wait time ends.

References


Next lesson →