Amazon DOP-C02: CI/CD Pipelines and Deployment Strategies — Study Guide
Part of the AWS DevOps Engineer Professional DOP-C02 — Study Guide. Practice with verified answers in the Amazon exam hub, or take timed practice tests on ExamRoll.io.
Overview
A robust CI/CD system on AWS ties together source control, build, test, artifact governance, deployment orchestration, and safe release strategies across multiple accounts and Regions. The core managed services—CodeCommit, CodeArtifact, CodeBuild, CodePipeline, and CodeDeploy—remove server maintenance, integrate tightly with IAM and KMS, and provide first-class support for blue/green, canary, rolling, and in-place deployments to EC2/Auto Scaling, ECS, and Lambda. Effective pipelines also rely on precise triggers (webhooks, EventBridge, schedules), disciplined artifact management, build caching for speed, and opinionated traffic shifting with health alarms for automatic rollback. For enterprises, cross-account and cross-Region patterns are mandatory, requiring role assumption, regional artifact stores, and consistent encryption policies.
Orchestration with AWS Developer Tools
Use CodeCommit as a private, highly available Git service. It integrates with EventBridge for repository and pull request events, supports approval rule templates, and uses IAM for fine-grained authorization. For third-party Git (GitHub/Bitbucket), configure CodePipeline source actions with webhooks for near-real-time triggers.
CodeArtifact centralizes package management for multiple ecosystems (npm, Maven, PyPI, NuGet). It supports upstream connections to public registries with caching, per-repository KMS encryption, and scoped auth tokens that expire automatically. Integrate in CodeBuild by invoking aws codeartifact login during pre_build to configure package managers without embedding long-lived secrets.
CodeBuild provides ephemeral, containerized builds without managing workers. Key capabilities:
- Environment isolation and VPC support for private dependencies. Enable privileged mode for Docker builds and enable local Docker layer caching to speed image builds.
- Environment variables from three sources: plaintext, SSM Parameter Store, and Secrets Manager (secure by default, no hardcoded secrets). You can also pass variables from CodePipeline.
- Caching to reduce build times:
- Local caching: source cache, Docker layer cache, and custom directories on the build host.
- S3 caching: reusable dependency sets shared across builds.
- Artifact management: specify primary and secondaryArtifacts to publish multiple outputs (e.g., app bundle and CloudFormation template). Encrypt artifacts with KMS keys and avoid public ACLs.
- Reporting: send logs to CloudWatch Logs/S3. Use reports for test results and CodeBuild badges for PR feedback.
CodePipeline is the orchestrator. Define stages (source, build, test, deploy, approval) with actions that can run in parallel or sequence. Best practices:
- Triggers:
- Webhooks for GitHub/Bitbucket sources.
- EventBridge rules for CodeCommit branch changes; verify rule existence when pipelines fail to start.
- Scheduled pipelines via EventBridge schedule rules that call StartPipelineExecution.
- Artifact stores: an S3 bucket per Region used by the pipeline; use a customer-managed KMS key. For cross-Region actions, add regional artifact stores.
- Manual approvals with SNS or EventBridge to integrate chat/webhooks for near-real-time notifications.
- Fine-grained IAM: a pipeline service role with least privilege; per-action roles are assumed for cross-account operations.
CodeDeploy is the deployment engine supporting EC2/on-prem, ECS, and Lambda targets. It manages lifecycle hooks, traffic shifting, health checks, and automatic rollback via CloudWatch alarms. Ensure EC2 instances run the CodeDeploy agent, have an instance profile, and outbound connectivity to CodeDeploy endpoints (or egress via NAT). Skipped events and no-op deployments often indicate agent/permission/connectivity problems.
Deployment Strategies and CodeDeploy Lifecycle
Choose the strategy by risk, capacity, and platform:
- In-place (EC2/on-prem): Update the app on existing instances. Combine with OneAtATime, HalfAtATime, or AllAtOnce deployment configurations. Attach an ELB to drain and re-register instances.
- Rolling (ECS): Replace tasks in batches on the same service. Native ECS rolling or managed via CodeDeploy as blue/green with controlled shift.
- Blue/green:
- EC2/Auto Scaling: Provision a green ASG, validate, then cut traffic from blue to green. Optionally terminate or retain the blue environment.
- ECS: Create a replacement task set behind a second target group; validate, then switch listeners.
- Lambda: Shift alias traffic to a new function version and monitor.
- Canary: Shift a small percentage first (e.g., 10%), observe for a window, then complete.
- Linear: Increase traffic in equal steps (e.g., 10% every 5 minutes).
CodeDeploy appspec.yml defines what to install and when to run scripts:
- For EC2/On-Prem (YAML):
- files: where to place files.
- permissions: file ownership/mode updates without custom scripts.
- hooks (common): ApplicationStop, BeforeInstall, Install, AfterInstall, ApplicationStart, ValidateService.
- Traffic control hooks (when using a load balancer): BeforeBlockTraffic, AfterBlockTraffic, BeforeAllowTraffic, AfterAllowTraffic.
- Use predefined environment variables (e.g., DEPLOYMENT_GROUP_NAME, DEPLOYMENT_ID, LIFECYCLE_EVENT) to modify behavior dynamically without separate revisions, such as toggling Apache log levels per deployment group.
- For ECS:
- resources: TargetService with TaskDefinition and LoadBalancerInfo.
- hooks: BeforeInstall, AfterInstall, AfterAllowTestTraffic, BeforeAllowTraffic, AfterAllowTraffic.
- AfterAllowTestTraffic is ideal for smoke/integration tests on the green task set with a test listener.
- For Lambda:
- resources define the function, version, and alias to shift.
- hooks: BeforeAllowTraffic and AfterAllowTraffic.
Traffic shifting and rollback:
- Configure deployment configurations:
- Lambda/ECS: Canary10Percent15Minutes, Canary10Percent5Minutes, Linear10PercentEvery1Minute, AllAtOnce, or custom.
- EC2 Blue/Green: All-at-once, canary, or linear traffic rerouting via the load balancer listeners/target groups.
- Add CloudWatch alarms to the deployment group to auto-rollback on errors, 5xx, or custom metrics. For ECS, alarms can watch target group 5xx or service metrics; for Lambda, watch function Errors/Throttles with alias/version dimensions.
- Use lifecycle hooks (e.g., AfterAllowTestTraffic) to run validation via Lambda or SSM; non-zero exits cause rollback.
Blue/Green and Traffic Shifting for EC2, ECS, and Lambda
EC2/Auto Scaling:
- Blue/green with CodeDeploy provisions a new Auto Scaling group for green, associates it with a separate target group, then switches ALB listeners. You can choose to terminate blue automatically or retain it for quick rollback.
- For in-place on EC2, combine with an ELB to gracefully deregister/register instances and protect availability. The deployment config dictates batch sizes and pacing.
ECS:
- CodeDeploy integrates with ECS services using two target groups behind an ALB. A replacement task set (green) is created with the new task definition.
- Test traffic flows to the green target group via a dedicated test listener; production traffic stays on blue until promotion.
- Canary or linear shifts progress traffic to green while monitoring CloudWatch alarms. Use AfterAllowTestTraffic to execute validation (for example, a Lambda function calling synthetic checks) before production cutover.
Lambda:
- CodeDeploy updates a function alias to a new version with weighted routing. Canary and linear patterns gradually move percentage traffic. CloudWatch alarms on the alias drive automatic rollback.
- With AWS SAM or CDK, set AutoPublishAlias and DeploymentPreference in templates to encode canary/linear policy and alarms per function.
Weighted routing beyond CodeDeploy:
- For multi-Region or multi-stack balancing, Route 53 weighted records with health checks provide regional traffic splitting (for example, 1% to a secondary Region) and failover. This complements but does not replace CodeDeploy’s per-service traffic shifting.
Multi-Account and Multi-Region Delivery
Enterprise pipelines typically reside in a centralized “tooling” account, deploying to dev/test/prod accounts across multiple Regions:
- Cross-account:
- In CodePipeline actions, specify a RoleArn in the target account that trusts the pipeline role’s principal. Use least-privilege permissions per action (CloudFormation, CodeDeploy, ECS, Lambda).
- For CodeBuild that must access target account resources, have the build assume a role (STS) or use a per-account action role, not broad AdministratorAccess.
- For CodeDeploy to EC2, the target account manages the application/deployment group and service role; the pipeline assumes a role to call CreateDeployment.
- Cross-Region:
- Add an artifact store per Region in the pipeline configuration (an S3 bucket with a regional KMS key). Update bucket policies to allow the pipeline role and per-action roles to read/write.
- Build region-specific artifacts when necessary (for example, packaging Lambda code with aws cloudformation package targeting a Region-local S3 bucket).
- CloudFormation deploy actions in a remote Region must reference the Region’s artifact store and can specify a stack execution role in the target account for least privilege.
Security, artifacts, and governance:
- Keep artifact buckets private; avoid public ACLs such as authenticated-read. Rely on bucket policies scoped to pipeline and action roles, with KMS encryption.
- Standardize buildspecs to push artifacts predictably (e.g., application bundle for EC2/CodeDeploy, taskdef.json and appspec for ECS, packaged templates for Lambda).
- Promote immutability with AMI pre-baking for EC2 so the CodeDeploy agent and base runtime are consistent; this reduces drift and deployment time.
- Use EventBridge rules to mirror pipeline events into notifications, chat ops, or ticketing, and to orchestrate manual gates.
Practical Problem Scenario
Spotify needs safer releases across hundreds of microservices with a mixed compute substrate (ECS on Fargate, EC2-based services, and Lambda). They require canary and blue/green deployments with automated tests before production traffic, artifact governance, and multi-Region promotion while keeping prod in a separate account.
- Establish repositories and packages
- Use CodeCommit for private repos and EventBridge-driven PR/test automation. CodeArtifact hosts npm, Maven, and PyPI dependencies with upstreams and KMS encryption to standardize supply-chain controls. Why: Central IAM/KMS integration and no external webhooks needed for critical repos; CodeArtifact gives cached, curated packages.
- Build and test
- Create CodeBuild projects per service with VPC integration, local caching (Docker layer and source), and environment variables sourced from Secrets Manager/Parameter Store. Build images and push to ECR; generate secondary artifacts (taskdef.json/appspec.yaml or packaged CloudFormation templates). Why: Ephemeral, isolated builds, strong secret handling, faster cycles via caching, and multiple outputs support both containers and serverless packaging.
- Orchestrate pipelines
- Create a centralized CodePipeline in a tooling account with stages: Source, Build, Unit Tests, Deploy-to-Staging, Automated Tests, Manual Approval, Deploy-to-Prod. Triggers come from EventBridge on CodeCommit updates; a nightly scheduled EventBridge rule kicks off integration tests. Why: Opinionated, auditable flow with gates and both event- and schedule-driven executions.
- Blue/green and canary deployments
- ECS services use CodeDeploy blue/green with two target groups and canary traffic shifting; validation runs in AfterAllowTestTraffic via a Lambda that executes contract tests and synthetic checks. EC2 services use CodeDeploy in-place with OneAtATime or blue/green ASG swaps when capacity permits. Lambda functions deploy with CodeDeploy using Canary10Percent15Minutes and CloudWatch alarms on Errors and 5xx from API Gateway. Why: First-class traffic controls per runtime and automatic rollback on alarm breaches minimize customer impact.
- Cross-account and cross-Region promotion
- The pipeline assumes per-environment roles in dev/test/prod accounts. For us-east-1 and eu-west-1, configure regional artifact stores and regional KMS keys; CodeBuild produces region-specific packaged templates and uploads artifacts to Region-local buckets. CloudFormation actions in each account/Region use stack execution roles; CodeDeploy actions target environment-specific applications/deployment groups. Why: Strong isolation of prod, least privilege via role assumption, and compliant encryption with low operational overhead.
- Artifact governance and security
- Enforce private S3 artifact buckets with restrictive policies and remove any public ACLs. Sign container images and templates; store SBOMs as build artifacts. Use IAM condition keys to limit production actions to pipelines in the tooling account. Why: Prevents data leakage, improves provenance, and aligns with supply-chain best practices.
- Observability and notifications
- Attach CloudWatch alarms to all deployment groups; EventBridge rules forward CodePipeline execution and approval events to an SNS topic and a Lambda that posts to Slack. Why: Faster feedback, automated rollbacks, and human-in-the-loop approvals where needed.
This design unifies heterogeneous runtimes under a single managed toolchain, provides safe rollout strategies with automated verification, reduces maintenance by eliminating self-hosted CI/CD infrastructure, and scales globally with clear separation of duties.
All domains · Infrastructure as Code and Configuration Management →
Practice these questions → · Timed practice on ExamRoll.io →
Pass the whole exam — not just this question
You found this answer. Get every verified question and explanation in one place, and save hours of prep. Free to start.
Pass your exam →