CI/CD (CodeCommit, CodeBuild, CodeDeploy, CodePipeline) — DVA-C02 Mastery Guide
- Sources: course chapter 17 (CI/CD), used as the syllabus only; all wording here is original. CodeGuru, CodeConnections and the service-status facts come from the module scope and current AWS documentation (they are not in the slides).
- Written 2026-10-12; values checked against AWS docs on 2026-10-12. The marker
⚠️ Changed: <current>. Older material may say <old>.flags a value or behaviour that differs from the course or older practice tests: learn the current value.⚠️ unverifiedmarks something the documentation does not confirm: don't rely on it. Every change is listed in Changed vs older material; confirmed rows go tonotes/current-facts.md.- Tier 2 (deployment and messaging), bank target 35 questions. Domain: Deployment.
- How to use it:
/explain <topic>teaches from these sections (concept → exam facts → developer angle → traps → 3 check questions);/quiz cicdasks bank questions whosesource_notelinks point at the## N.headings below;/drill cicdfires short recall prompts fromnotes/cicd-cheat-sheet.md. Suggested loop: read a section, answer its two practice questions before opening the answers, then/quiz cicdand/drill cicd.
How CI/CD appears on DVA-C02
Most of the Deployment domain (24 % of the exam) is about this module. Its four task statements map onto the services:
- Prepare application artifacts: buildspec
artifacts, CodeArtifact repositories for dependencies, AppSpec files and revision bundles,imagedefinitions.jsonfor ECS. - Test in development environments: CodeBuild test reports, CodeDeploy test listeners and validation hooks, local builds with the CodeBuild agent.
- Automate deployment testing: test stages in CodePipeline,
BeforeAllowTraffic/AfterAllowTraffichooks, alarm-driven rollbacks, stage conditions. - Deploy code with AWS CI/CD services: CodeDeploy deployment configurations for EC2, Lambda and ECS, CodePipeline stages, manual approvals, connections to GitHub.
Security and troubleshooting questions land here too: secrets in builds, service roles versus instance profiles, cross-account pipelines, and CodeDeploy error codes. Typical question shapes: pick the deployment configuration that meets an availability or speed constraint; place a file or setting (buildspec, AppSpec, hook) correctly; diagnose a failed build, deployment or pipeline action from its error; choose the least-privilege permission (approval, connections, CodeArtifact tokens); "Which TWO steps…" for cross-account or rollback setups.
Domain map: Deployment → all topics · Security angles → §2, §5, §10 (cross-account), §13, §14 · Troubleshooting angles → §3, §9, §12.
Out of scope: OS administration (agent installation beyond the commands shown, shell scripting inside hooks) and network design. VPC settings for CodeBuild and VPC endpoints for CodeArtifact appear only as settings to recognise; routing and subnets live in notes/vpc-guide.md.
| # | Topic | Why it is on the exam |
|---|---|---|
| 1 | The AWS CI and CD toolchain | Which service does which job, and which tools are closed or gone (CodeStar, Cloud9, CodeCatalyst, CodeGuru Reviewer) |
| 2 | CodeCommit repositories and access | The right Git credential, branch protection with IAM, cross-account access, triggers |
| 3 | CodeBuild projects and build environments | Compute choice, queueing and timeouts, service role, Docker builds, webhooks |
| 4 | The buildspec file | Phases, failure handling, artifacts and test reports |
| 5 | CodeBuild variables secrets and caching | Secrets from Parameter Store and Secrets Manager, precedence, S3 versus local cache |
| 6 | CodeDeploy on EC2 and on premises | Agent, roles, deployment configurations, in-place versus blue/green, Auto Scaling |
| 7 | AppSpec files and lifecycle hooks | Hook order, reserved events, validation hooks for Lambda and ECS |
| 8 | CodeDeploy for Lambda and ECS | Canary, linear and all-at-once configurations; ECS blue/green requirements |
| 9 | CodeDeploy rollbacks and troubleshooting | Automatic rollbacks, alarms, error codes, common failures |
| 10 | CodePipeline stages actions and artifacts | Pipeline structure, artifact store, cross-account and cross-Region, change detection |
| 11 | CodePipeline V2 triggers variables and execution modes | Git tag and branch triggers, QUEUED and PARALLEL, stage conditions and rollback |
| 12 | Manual approvals and pipeline monitoring | Approval permissions and timeouts, EventBridge events, retries and stops |
| 13 | Connections to GitHub Bitbucket and GitLab | CodeConnections, IAM permissions, full clone, pending connections |
| 14 | CodeArtifact | Domains, upstreams, external connections, tokens, resource policies |
1. The AWS CI and CD toolchain
Concept
- Continuous integration means every change is merged often and verified automatically (build plus tests), so a defect surfaces minutes after the commit that caused it. Continuous delivery keeps every verified change releasable through automated deployment stages, with an optional human gate before production; continuous deployment removes that gate.
- AWS splits the work into one service per step: a source (CodeCommit, or a GitHub, Bitbucket or GitLab repository reached through CodeConnections, or S3 or ECR), a build and test service (CodeBuild), a deployment engine (CodeDeploy, or deploy actions for Elastic Beanstalk, CloudFormation, ECS, S3 and others) and an orchestrator (CodePipeline) that moves artifacts from step to step.
- Supporting tools: CodeArtifact stores package dependencies; CodeGuru Profiler profiles running code; Developer Tools notification rules and EventBridge report what happened.
- Several tools that older courses present are no longer options for new projects, and exam distractors may still name them.
Exam facts
| Service | Job | Status in October 2026 |
|---|---|---|
| CodeCommit | Managed private Git repositories | ⚠️ Changed: generally available and open to new customers again since 2025-11-24. Older material may say it closed to new customers on 2024-07-25. |
| CodeBuild | Managed builds and tests in fresh environments | Active |
| CodeDeploy | Deployments to EC2/on-premises, Lambda and ECS | Active |
| CodePipeline | Release orchestration (V1 and V2 pipeline types) | Active |
| CodeArtifact | Package repositories (npm, PyPI, Maven, NuGet, Swift, Ruby, Cargo, generic) | Active |
| CodeConnections | Links pipelines and builds to GitHub, Bitbucket, GitLab | ⚠️ Changed: renamed from AWS CodeStar Connections on 2024-03-29 (codeconnections prefix). Older material may say AWS CodeStar Connections. |
| CodeGuru Profiler | Runtime CPU and latency profiling (all JVM languages, Python 3.6+) | Active |
| CodeGuru Reviewer | Automated code review of repositories | ⚠️ Changed: maintenance; no new repository associations since 2025-11-07, existing ones keep working. Older material may present it as available to any repository. |
| CodeStar | Project templates and dashboard | ⚠️ Changed: fully shut down, end of support 2024-07-25; repositories and pipelines it created still run. Older material may present it as current. |
| Cloud9 | Browser IDE | ⚠️ Changed: closed to new customers since 2024-07-25 (maintenance); AWS points to the IDE Toolkits and CloudShell. Older material may present it as available to any account. |
| CodeCatalyst | Hosted DevOps spaces | ⚠️ Changed: closed to new customers since 2025-11-07; existing customers can't create new spaces. Older material may present it as the open successor to CodeStar. |
- Replacements AWS names for CodeGuru Reviewer: Amazon Q Developer code reviews and Amazon Inspector code security.
- CodeGuru Profiler: create a profiling group, run the Profiler agent inside the application, read flame graphs and recommendations. The agent samples once per second and aggregates into 5-minute buckets, so rarely invoked Lambda functions produce little data.
- Profiler agent permissions (AWS managed policy
AmazonCodeGuruProfilerAgentAccess):codeguru-profiler:ConfigureAgent,codeguru-profiler:PostAgentProfile,codeguru-profiler:CreateProfilingGroup. - Lambda console shortcut: Configuration → Monitoring and operations tools → Code profiling creates the profiling group on the first profile and adds the managed policy to the execution role (Python 3.8 and 3.9, Java 8 on Amazon Linux 2, Java 11 and Java 17).
- Profiler versus X-Ray: Profiler shows which code paths burn CPU inside one process; X-Ray traces a request across services (see
notes/monitoring-guide.md). - Event plumbing shared by the Code services: notification rules for people (SNS topics or chat clients), EventBridge rules for automation, CloudTrail for the API audit trail.
- ⚠️ Changed: notification rules reach Slack or Microsoft Teams through Amazon Q Developer in chat applications (renamed on 2025-02-19; some Developer Tools pages still use the old name). Older material may say AWS Chatbot.
Developer angle
- CLI namespaces don't always match the service names:
aws codecommit,aws codebuild,aws deploy(CodeDeploy),aws codepipeline,aws codeartifact,aws codeconnections(older scripts:aws codestar-connections),aws codeguruprofiler create-profiling-group --profiling-group-name orders-api. - IAM action prefixes:
codecommit:,codebuild:,codedeploy:,codepipeline:,codeartifact:,codeconnections:(plus the legacycodestar-connections:),codeguru-profiler:,codeguru-reviewer:. - Infrastructure as code replaces the old CodeStar templates: define the CodeBuild project, CodeDeploy application and pipeline in CloudFormation, SAM or CDK (see
notes/cloudformation-guide.md,notes/sam-guide.md,notes/cdk-guide.md).
Traps
- Trap: "Create a CodeStar project to get a ready-made pipeline." → Reality: CodeStar is shut down; create the CodeBuild project, CodeDeploy application and pipeline directly or as infrastructure as code.
- Trap: "CodeCommit can't be used by a new account." → Reality: the 2024 closure was reversed on 2025-11-24.
- Trap: "Associate the new repository with CodeGuru Reviewer." → Reality: new associations are blocked; existing ones keep working.
- Trap: "CodeGuru Profiler and X-Ray answer the same question." → Reality: Profiler finds expensive methods in one process; X-Ray follows a request across services.
- Trap: "
aws codedeploy create-deployment." → Reality: the CLI namespace isaws deploy; the IAM prefix iscodedeploy:. - Trap: "Connections with
codestar-connectionsARNs must be recreated." → Reality: old-prefix resources are still supported (§13).
Practice questions
-
A developer runs a Java order service on Amazon ECS. CPU utilization is high in production, and the team wants to find which methods consume the most CPU time under real traffic, with the fewest code changes. What should the developer use?
- A. Instrument the service with the AWS X-Ray SDK and add a subsegment around every method.
- B. Create a CodeGuru Profiler profiling group and run the Profiler agent with the service.
- C. Associate the service's repository with CodeGuru Reviewer and enable full repository scans.
- D. Turn on CloudWatch Container Insights for the ECS cluster and read the task CPU graphs.
-
A team follows a 2023 onboarding document that says: "Create a CodeStar project, connect GitHub with CodeStar Connections, and enable CodeGuru Reviewer on pull requests." Which TWO statements describe what the team must do differently in 2026? (Select TWO.)
- A. Build the pipeline directly with CodePipeline and CodeBuild, because CodeStar projects can no longer be created.
- B. Delete and recreate every connection, because ARNs with the
codestar-connectionsprefix stopped working. - C. Use Amazon Q Developer code reviews or Amazon Inspector code security, because new CodeGuru Reviewer associations can't be created.
- D. Move the code from GitHub to CodeCommit, because pipelines can no longer use GitHub sources.
- E. Create the project in a new Amazon CodeCatalyst space, because CodeCatalyst replaces CodeStar for new accounts.
Answers
- B. CodeGuru Profiler samples the running process and ranks the most expensive code paths, and its agent needs no per-method code. A demands heavy instrumentation and measures request timing, not CPU per method; C reviews source code statically (and accepts no new associations); D shows CPU per task, not per method.
- A, C. CodeStar is shut down, and CodeGuru Reviewer accepts no new repository associations. B is wrong because old-prefix connections are still supported; D is wrong because GitHub sources work through CodeConnections; E is wrong because CodeCatalyst is closed to new customers.
2. CodeCommit repositories and access
Concept
- CodeCommit hosts private Git repositories inside your account: developers push and pull with a normal Git client, IAM decides who may do what, KMS encrypts the data, and CloudTrail records the API calls.
- The practical decisions are how developers authenticate (four methods), how to protect important branches, how another account gets in, and what reacts to a push.
Exam facts
- ⚠️ Changed: generally available and open to new customers again since 2025-11-24 (the 2024-07-25 closure was reversed). Older material may say CodeCommit is closed to new customers.
- Authentication methods:
| Method | URL style | Use it for | Notes |
|---|---|---|---|
| Git credentials | https://git-codecommit.<region>.amazonaws.com/v1/repos/<repo> |
IAM users; IDEs that ask for a user name and password | Static user name and password generated in IAM for one user; not available to federated or temporary identities |
| SSH keys | ssh://git-codecommit.<region>.amazonaws.com/v1/repos/<repo> |
IAM users who prefer SSH | Public key uploaded to the IAM user; the SSH key ID is the SSH user name |
| git-remote-codecommit (GRC) | codecommit::<region>://<profile>@<repo> |
Federated users, IAM Identity Center, assumed roles, cross-account | Uses the CLI profile's temporary credentials; needs Python 3 and pip 9.0.3+; AWS CLI v2 for SSO profiles |
| AWS CLI credential helper | HTTPS URL | Temporary credentials or an EC2 instance role when GRC isn't an option | Can clash with operating-system credential helpers |
- ⚠️ Changed: for federated access and temporary credentials AWS recommends git-remote-codecommit. Older material may say HTTPS users pick either Git credentials or the AWS CLI credential helper.
- Authorization is IAM: identity policies on users, groups or roles with
codecommit:actions (GitPull,GitPush,CreatePullRequest, theMergePullRequestBy…family). Another account gets in through a role in the repository's account that its principals assume. - Branch protection: a
Denyoncodecommit:GitPush,PutFile,DeleteBranch,DeleteFileand theMerge…actions withStringEqualsIfExistsoncodecommit:References(refs/heads/main) plus the condition"Null": {"codecommit:References": "false"}(the key must be present); theNullpart is required in anyDenythat includesGitPush. Without it,StringEqualsIfExistsalso matches every request that carries nocodecommit:Referencesvalue (IAM evaluates an…IfExistscondition as true when the key is missing), so theDenywould also blockGitPushrequests that name no branch; the CodeCommit guide ties the requirement to how Git andgit-receive-packpush. - Encryption: at rest with the AWS managed key
aws/codecommit(created with the first repository in a Region) or a customer managed symmetric key with "Encrypt and decrypt" usage in the repository's Region; the encryption context is the repository ID; in transit only over HTTPS or SSH. - Reacting to changes: repository triggers (up to 10 per repository; target an SNS topic or Lambda function in the same Region; events such as a push to a branch or creating or deleting a branch or tag), notification rules (SNS or Amazon Q Developer in chat applications) and EventBridge events (how CodePipeline detects CodeCommit pushes).
- Pull requests support approval rules and approval rule templates (up to 1,000 templates per Region; up to 30 rules on one pull request, 25 of them from templates).
- Quotas: 5,000 repositories per account (adjustable); 6 MB per file through the console, APIs or CLI; 2 GB per Git blob through
git push; 4,000 references per push; the quotas page lists no limit on total repository size. - ⚠️ unverified: Git LFS (announced for Q1 2026) and the eu-south-2 and ca-west-1 Regions (announced for Q3 2026) do not appear in the documentation as of October 2026.
Developer angle
# IAM user, HTTPS: generate static Git credentials
aws iam create-service-specific-credential --user-name dev1 --service-name codecommit.amazonaws.com
# IAM user, SSH: upload the public key; the returned SSHPublicKeyId is the SSH user name
aws iam upload-ssh-public-key --user-name dev1 --ssh-public-key-body file://~/.ssh/codecommit_rsa.pub
# Federated or role-based access (recommended): git-remote-codecommit with a CLI profile
pip install git-remote-codecommit
git clone codecommit::eu-west-1://dev-sso@orders-service
# Credential helper alternative for HTTPS with temporary credentials
git config --global credential.helper '!aws codecommit credential-helper $@'
git config --global credential.UseHttpPath true
Branch protection for the developers' role (feature branches and pull requests stay possible; pushes and merges to main don't):
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Deny",
"Action": ["codecommit:GitPush", "codecommit:PutFile", "codecommit:DeleteBranch", "codecommit:DeleteFile",
"codecommit:MergeBranchesBy*", "codecommit:MergePullRequestBy*"],
"Resource": "arn:aws:codecommit:eu-west-1:111122223333:orders-service",
"Condition": {
"StringEqualsIfExists": { "codecommit:References": ["refs/heads/main"] },
"Null": { "codecommit:References": "false" }
}
}]
}
- Cross-account: the repository account's role trusts the developer account; developers add a CLI profile with
role_arnandsource_profileand clone withcodecommit::<region>://<that-profile>@<repo>. - Trigger permissions: a same-account SNS topic needs nothing extra; a Lambda trigger created from the Lambda console gets its resource-based policy automatically, one created from CodeCommit needs a policy that lets CodeCommit invoke the function.
Traps
- Trap: "Give the partner team an IAM user's SSH key or access keys." → Reality: create a role in the repository account and let them assume it (GRC with a role profile); never share long-term credentials.
- Trap: "Federated developers can generate Git credentials." → Reality: Git credentials and SSH keys belong to IAM users; federated and SSO identities use GRC or the credential helper.
- Trap: "A
DenyonGitPushneeds onlyStringEqualsIfExistsoncodecommit:References." → Reality: add theNullcondition (key present):…IfExistsalso matches requests without acodecommit:Referencesvalue, so theDenywould block more thanmain(AWS ties this to how Git andgit-receive-packhandle a push). - Trap: "Point a trigger at an SNS topic in another Region." → Reality: trigger targets must be in the repository's Region.
- Trap: "Upload a 50 MB binary through the console." → Reality: console and API uploads stop at 6 MB per file;
git pushhandles blobs up to 2 GB.
Practice questions
-
A company signs developers in through IAM Identity Center; nobody has an IAM user. Developers must clone and push to CodeCommit repositories without long-term credentials, following AWS recommendations. What should the developers do?
- A. Ask an administrator to create Git credentials for a shared IAM user and store them in each IDE.
- B. Install git-remote-codecommit and clone with
codecommit::URLs that reference their SSO CLI profile. - C. Upload each developer's SSH public key to IAM Identity Center and clone over SSH.
- D. Put a shared IAM user's access keys in
~/.aws/credentialsand configure the AWS CLI credential helper.
-
A team lead must stop most developers from pushing directly to the
mainandreleasebranches of a CodeCommit repository, while still letting them push feature branches and open pull requests. Which TWO elements belong in the IAM policy attached to the developers' role? (Select TWO.)- A. A
Denystatement forcodecommit:GitPush,PutFileand theMerge…actions withStringEqualsIfExistsoncodecommit:Referencesforrefs/heads/mainandrefs/heads/release. - B. A
Nullcondition that setscodecommit:Referencestofalseinside the sameDenystatement. - C. A repository resource policy that denies
codecommit:GitPushonmainfor the developers' role. - D. A repository trigger that invokes a Lambda function to revert any commit pushed to
main. - E. An approval rule template that requires two approvals before a pull request can merge into
main.
- A. A
Answers
- B. GRC uses the profile's temporary SSO credentials and is AWS's recommended method for federated users. A and D rely on shared long-term credentials; C is impossible because CodeCommit SSH keys attach to IAM users, not to Identity Center users.
- A, B. The conditional
Denyoncodecommit:Referencesblocks updates to the named branches, and theNullcondition is required whenever aDenyincludesGitPush. C fails because CodeCommit access is controlled with IAM identity policies, not repository policies; D reacts after the push instead of preventing it; E governs pull request merges but doesn't block direct pushes.
3. CodeBuild projects and build environments
Concept
- A build project defines where the source comes from, which environment runs the build (image, compute type, operating system), which service role the build uses, where the buildspec is, and where artifacts and logs go. Every build starts in a fresh environment, so results don't depend on leftovers from earlier builds.
- Builds start from the console,
start-build, a CodePipeline build or test action, a webhook from the Git provider or an EventBridge rule (for example on a schedule). The CodePipeline Commands action (§11) runs commands on CodeBuild compute without any project. - Compute choices: on-demand EC2 compute (general purpose), Lambda compute (fast start, restricted) and reserved capacity fleets (instances kept warm for you, including macOS).
Exam facts
- ⚠️ Changed: sources are CodeCommit, CodePipeline, GitHub, GitHub Enterprise Server, GitLab, GitLab self-managed, Bitbucket, S3 or none (
NO_SOURCE), with up to 12 secondary sources and 12 secondary artifacts. Older material may list only CodeCommit, S3, Bitbucket and GitHub. - On-demand EC2 compute types:
BUILD_GENERAL1_SMALL(4 GiB, 2 vCPUs on Linux),MEDIUM(8 GiB, 4 vCPUs),LARGE(16 GiB, 8 vCPUs),XLARGE(72 GiB, 36 vCPUs),2XLARGE(144 GiB, 72 vCPUs, 824 GB SSD); Linux, ARM, GPU and Windows environment types. - Lambda compute (
BUILD_LAMBDA_1GBtoBUILD_LAMBDA_10GBonLINUX_LAMBDA_CONTAINERorARM_LAMBDA_CONTAINER): faster start and no waiting in a queue, but no Docker builds or runs, no root tools (yum,rpm), writes only under/tmp, no caching, no custom build or queue timeouts, no privileged mode, no VPC, no build badges, and nothing longer than 15 minutes. - ⚠️ Changed: on-demand EC2 builds are billed per build minute (rounded up), Lambda compute per second, reserved capacity per instance-minute with a 60-minute minimum; the free tier is 100 build minutes per month on
general1.smallorarm1.small. Older material may say every build is billed per minute. - ⚠️ Changed: build timeout 5 to 2,160 minutes (36 hours), default 60 minutes (maximum raised on 2024-05-01). Older material may say the maximum is 8 hours.
- ⚠️ Changed: builds do queue. A build waits in
QUEUEDwhen the account's concurrent-build quota for that compute type is reached (small defaults that vary by type: the quotas page lists 1 for most types and 0 for Linux2XLARGEand GPU; raise them in Service Quotas; error "Cannot have more than X active builds for the account");concurrentBuildLimitcaps one project further;queuedTimeoutInMinutesis 5 to 480. Older material may say CodeBuild has no build queue. - Build phases in order:
SUBMITTED,QUEUED,PROVISIONING,DOWNLOAD_SOURCE,INSTALL,PRE_BUILD,BUILD,POST_BUILD,UPLOAD_ARTIFACTS,FINALIZING,COMPLETED; each phase endsSUCCEEDED,FAILED,FAULT,TIMED_OUTorSTOPPED. - Service role: trusted by
codebuild.amazonaws.com; restrict the trust withaws:SourceArn(project ARN) oraws:SourceAccount; it needs CloudWatch Logs, S3 artifact access,codecommit:GitPullfor CodeCommit sources and ECR pull permissions for private images. Webhook-triggered builds use the same role, so keep it minimal. privilegedMode: trueruns a Docker daemon in the build container and is required to build Docker images (defaultfalse).imagePullCredentialsType(how CodeBuild pulls the build environment image):CODEBUILDfor curated images;SERVICE_ROLEfor cross-account ECR or private registry images. Images that your owndocker buildordocker pullcommands fetch, such as a private base image, need adocker loginin the buildspec (for ECR:aws ecr get-login-password, with ECR pull rights for the service role).vpcConfig(up to 16 subnets and 5 security groups) lets a build reach private resources; how those subnets reach the internet or AWS APIs is network design (seenotes/vpc-guide.md).- Webhooks (GitHub, GitHub Enterprise Server, GitLab, GitLab self-managed, Bitbucket; not CodeCommit): a build starts if any filter group matches, and a group matches only when all its filters match; filter types include
EVENT(PUSH,PULL_REQUEST_CREATED,PULL_REQUEST_UPDATED,PULL_REQUEST_MERGED, …),HEAD_REF,BASE_REF,FILE_PATH,COMMIT_MESSAGE,ACTOR_ACCOUNT_ID; patterns use RE2 (no lookahead; useexcludeMatchedPatterninstead). - Observability: logs to CloudWatch Logs and/or S3; build history kept 1 year. For an alert on every failed build, an EventBridge rule on source
aws.codebuild, detail-typeCodeBuild Build State Change,build-statusFAILED; for "more than N failures", a CloudWatch alarm on theFailedBuildsmetric (namespaceAWS/CodeBuild; others includeBuilds,SucceededBuilds,Duration,QueuedDuration). autoRetryLimitretries a failed build automatically (CodeBuild callsRetryBuild).- Local builds: the CodeBuild agent image (
public.ecr.aws/codebuild/local-builds) pluscodebuild_build.shrun a buildspec on your machine with Docker.
Developer angle
aws codebuild create-project --name orders-build \
--source type=CODECOMMIT,location=https://git-codecommit.eu-west-1.amazonaws.com/v1/repos/orders-service \
--artifacts type=S3,location=orders-artifacts,packaging=ZIP \
--environment type=LINUX_CONTAINER,computeType=BUILD_GENERAL1_MEDIUM,image=aws/codebuild/standard:7.0,privilegedMode=true \
--service-role arn:aws:iam::111122223333:role/orders-codebuild-role \
--timeout-in-minutes 30 --queued-timeout-in-minutes 60
# One-off run with overrides (they beat the project settings and the buildspec)
aws codebuild start-build --project-name orders-build --source-version main \
--environment-variables-override name=STAGE,value=test,type=PLAINTEXT --buildspec-override buildspec-integration.yml
- Confused-deputy protection: in the role's trust policy, add
"Condition": {"StringEquals": {"aws:SourceArn": "arn:aws:codebuild:<region>:<account>:project/orders-build"}}(oraws:SourceAccount). - Public repositories with webhooks: add
ACTOR_ACCOUNT_IDandFILE_PATHfilters (for example exclude changes tobuildspec.ymlwithexcludeMatchedPattern), keep the buildspec inline or in S3 so a pull request can't rewrite it, and give webhook-triggered projects a minimal role.
Traps
- Trap: "Use Lambda compute to build and push the container image." → Reality: Lambda compute can't run Docker; use EC2 compute with
privilegedMode. - Trap: "CodeBuild scales without limits, so builds never wait." → Reality: per-compute-type concurrency quotas put builds in
QUEUED; raise the quota. - Trap: "Raise
concurrentBuildLimitto fix account-level queueing." → Reality: the project limit can only lower concurrency; the account quota must go up. - Trap: "'Cannot connect to the Docker daemon' means an IAM permission is missing." → Reality: enable privileged mode.
- Trap: "
CODEBUILDpull credentials work for a build image in another account's ECR." → Reality: useSERVICE_ROLEand give the role ECR access; a base image pulled bydocker buildneeds adocker logininstead. - Trap: "Add a CodeBuild webhook to the CodeCommit repository." → Reality: webhooks cover GitHub, GitLab and Bitbucket; CodeCommit builds start from CodePipeline or an EventBridge rule.
Practice questions
-
During release days a team's builds sit in the
QUEUEDphase for several minutes, and the build details show "Cannot have more than 1 active builds for the account." The project usesBUILD_GENERAL1_MEDIUMon Linux. What should the developer do?- A. Move the project to Lambda compute and raise its build timeout to 60 minutes.
- B. Request an increase of the concurrently running builds quota for that compute type in Service Quotas.
- C. Raise the project's
queuedTimeoutInMinutesto 480 so that queued builds aren't cancelled. - D. Raise the project's
concurrentBuildLimitto 10.
-
A CodeBuild project must build a Docker image whose base image lives in a private Amazon ECR repository in a shared-services account, then push the result to ECR. Which TWO steps are required? (Select TWO.)
- A. Set
privilegedModetotruein the project environment. - B. Sign Docker in to the shared account's registry in
pre_buildwithaws ecr get-login-password, and allow the service role (and the repository policy) to pull the image. - C. Switch the environment to
LINUX_LAMBDA_CONTAINERwithBUILD_LAMBDA_4GB. - D. Set
imagePullCredentialsTypetoSERVICE_ROLEand leave the buildspec unchanged. - E. Store the shared account's access keys as
PLAINTEXTenvironment variables fordocker login.
- A. Set
Answers
- B. The message names the account-level quota for that compute type; only a quota increase lets more builds run at once. A trades the queue for Lambda compute's restrictions (and Lambda compute ignores custom timeouts); C only lets builds wait longer; D can't exceed the account quota.
- A, B. Building images needs the Docker daemon (privileged mode), and
docker buildpulls the base image with Docker's own registry login, which the service role's ECR token provides. C can't run Docker; D only changes how CodeBuild pulls the build environment image, sodocker buildstill has no registry credentials; E puts long-term secrets in plain text.
4. The buildspec file
Concept
- The buildspec is a YAML document that tells CodeBuild what to run in each phase and what to keep afterwards (artifacts, test reports, cache). It usually lives with the code, so the build logic is versioned with the application.
- A project uses one buildspec at a time; the project, or a single build, can point at a different file, an inline definition or an S3 object.
Exam facts
- Default: a file named
buildspec.ymlat the root of the source. Overrides: the project'sbuildspecsetting (a path relative toCODEBUILD_SRC_DIR, inline YAML, or an S3 object ARN in the project's Region),start-build --buildspec-override, CloudFormationSource.BuildSpec. - Use
version: 0.2: all commands share one shell, socdandexportcarry over; version 0.1 runs every command in its own shell. - Phases (each optional, names fixed):
install(runtimes and tools,runtime-versionssuch asnodejs: 20orpython: 3.x),pre_build(sign in to ECR, fetch dependencies),build(compile and test),post_build(package, push images, notify). - Inside a phase:
commandsrun in order and the first failure fails the phase;finallycommands run even when a command failed;run-aspicks a Linux user (default root);on-failureisABORT,CONTINUE,RETRY(up to 3 times),RETRY-<count>(0–100),RETRY-<regex>orRETRY-<count>-<regex>, and works only on CodeBuild-provided EC2 images (not Lambda compute or reserved capacity). - When
BUILDfails,POST_BUILDstill runs andUPLOAD_ARTIFACTSis still attempted, while a failure inDOWNLOAD_SOURCE,INSTALLorPRE_BUILDskips straight toFINALIZING(default transitions; a phase'son-failuresetting overrides them);CODEBUILD_BUILD_SUCCEEDING(1or0) tells those later commands whether the build is still succeeding. artifacts:files(required; globs such as'**/*'),name(may contain shell expressions such as a date or$CODEBUILD_BUILD_NUMBER; used withoverrideArtifactNameor semantic versioning),discard-paths(flatten),base-directory,exclude-paths,enable-symlinks,s3-prefix,secondary-artifacts(keys match the project'sartifactIdentifiervalues;filesstays required). A build that only pushes an image or runs tests needs noartifactssection.- Artifacts are encrypted with the project's KMS
encryptionKey(key ARN or alias); a key from another account works if the service role may use it. reports: up to 5 report groups per project;file-formatdefaults toJUNITXML; test formatsCUCUMBERJSON,JUNITXML,NUNITXML,NUNIT3XML,TESTNGXML,VISUALSTUDIOTRX; coverage formatsCLOVERXML,COBERTURAXML,JACOCOXML,SIMPLECOV; reports are kept 30 days with up to 500 test cases each.batch: several builds from one buildspec (build-list,build-matrix,build-graph,build-fanout;fast-fail).- Without a buildspec file the console accepts only
buildcommands (one line, joined with&&). - The ECS deploy action in CodePipeline expects an
imagedefinitions.jsonartifact ([{"name": "<container>", "imageUri": "<image>"}], at most 100 KB).
Developer angle
A service that tests, builds and pushes an image, then hands the ECS deploy action its image definition:
version: 0.2
phases:
install:
runtime-versions:
nodejs: 20
commands:
- npm ci
pre_build:
commands:
- npm test
- aws ecr get-login-password --region "$AWS_REGION" | docker login --username AWS --password-stdin "$REGISTRY"
build:
commands:
- docker build -t "$IMAGE_REPO:$CODEBUILD_RESOLVED_SOURCE_VERSION" .
finally:
- echo "build phase done, succeeding=$CODEBUILD_BUILD_SUCCEEDING"
post_build:
commands:
- |
if [ "$CODEBUILD_BUILD_SUCCEEDING" = "1" ]; then
docker push "$IMAGE_REPO:$CODEBUILD_RESOLVED_SOURCE_VERSION"
printf '[{"name":"web","imageUri":"%s"}]' "$IMAGE_REPO:$CODEBUILD_RESOLVED_SOURCE_VERSION" > imagedefinitions.json
fi
reports:
unit-tests:
files:
- "reports/junit.xml"
file-format: JUNITXML
artifacts:
files:
- imagedefinitions.json
REGISTRY and IMAGE_REPO come from the project or the env section (§5).
Traps
- Trap: "Keep
buildspec.ymlinci/and CodeBuild will find it." → Reality: the default location is the source root; anything else must be set on the project or the build. - Trap: "The buildspec can sit in an S3 bucket in any Region." → Reality: the bucket must be in the project's Region.
- Trap: "Use buildspec version 0.1 so variables persist between commands." → Reality: 0.2 shares one shell; 0.1 isolates each command.
- Trap: "A failed build never uploads artifacts." → Reality: after a
BUILDfailure,post_buildstill runs andUPLOAD_ARTIFACTSis still attempted; guard publishing steps withCODEBUILD_BUILD_SUCCEEDING. - Trap: "Add
on-failure: RETRYto a Lambda-compute project." → Reality:on-failureworks only on CodeBuild-provided EC2 images. - Trap: "Use two buildspec files in one project, one per artifact." → Reality: one buildspec per project; use
secondary-artifactsor a batch build.
Practice questions
-
A repository holds two services, each with its own buildspec at
services/billing/buildspec.ymlandservices/catalog/buildspec.yml. A developer creates one CodeBuild project per service and wants each project to use its own file with the fewest changes to the repository. What should the developer do?- A. Move both files to the repository root, rename them
buildspec.yml, and keep each service on its own branch. - B. Set each project's
buildspecvalue to the file's path relative toCODEBUILD_SRC_DIR. - C. Copy both files to an S3 bucket in another Region and reference their object ARNs.
- D. Merge both files into one buildspec that uses a
batchbuild matrix for the two services.
- A. Move both files to the repository root, rename them
-
A team wants unit-test results to appear in the CodeBuild console with pass and fail counts, and wants each build to publish the application ZIP and a separate documentation ZIP to two different S3 locations. Which TWO buildspec elements meet these requirements? (Select TWO.)
- A. A
reportssection that names a report group and the JUnit XML files withfile-format: JUNITXML. - B. A
secondary-artifactsblock whose identifiers match the project's secondary artifact definitions. - C. A second buildspec file in the same project that produces the documentation ZIP.
- D.
discard-paths: yes, which splits the output into one ZIP per top-level folder. - E. A
finallyblock that writes the test results to CloudWatch Logs.
- A. A
Answers
- B. The project's
buildspecsetting takes a path relative toCODEBUILD_SRC_DIR, so no files move. A restructures the repository; C fails because an S3-hosted buildspec must be in the project's Region; D rewrites the build logic for a problem that a setting solves. - A, B. Report groups turn test files into console reports, and secondary artifacts publish extra outputs to their own locations. C is impossible (one buildspec per project); D only flattens paths; E produces log lines, not test reports.
5. CodeBuild variables secrets and caching
Concept
- A build receives configuration from three places: the buildspec
envsection, the project's environment variables and the overrides passed to onestart-build(or by a pipeline action). Secrets shouldn't be stored in any of them as plain text: reference a Systems Manager Parameter Store parameter or a Secrets Manager secret, and CodeBuild resolves it at run time and masks it in the logs. - Caching keeps reusable files (dependencies, Git metadata, Docker layers) between builds: an S3 cache is shared by every build host; a local cache stays on the host that created it.
Exam facts
- Precedence for one variable name:
start-buildoverride > project definition > buildspec. - Project variable types:
PLAINTEXT(default; readable in the console and CLI, never for secrets),PARAMETER_STORE(value = parameter name),SECRETS_MANAGER(value = secret reference). - Buildspec mappings:
env/variables(plain text),env/parameter-store(NAME: /path/param; the service role needsssm:GetParameters),env/secrets-manager(NAME: secret-id:json-key:version-stage:version-id; only the secret ID is required, the default stage isAWSCURRENT, use the full ARN for another account's secret; the role needssecretsmanager:GetSecretValue),env/exported-variables,env/git-credential-helper: yes,env/shell. - A secret or
SecureStringparameter encrypted with a customer managed KMS key also needskms:Decryptfor the service role (key policies and cross-account secrets: seenotes/security-encryption-guide.md). - Masking: AWS access key IDs and values that come from Parameter Store or Secrets Manager are hidden in the logs, but only the exact stored string; a transformed copy (Base64, reversed, concatenated) is printed.
- Names starting with
CODEBUILD_are reserved. A variable you set replaces the image's value literally (PATH=$PATH:/xisn't expanded). exported-variableshand values to later pipeline actions through the action namespace (#{BuildVariables.IMAGE_TAG}); values are final afterpost_build; project-defined Parameter Store and Secrets Manager values and names starting withAWS_can't be exported.- Built-in variables:
CODEBUILD_RESOLVED_SOURCE_VERSION(commit ID for Git sources; set afterDOWNLOAD_SOURCE; not set for S3),CODEBUILD_SOURCE_VERSION,CODEBUILD_BUILD_ID,CODEBUILD_BUILD_NUMBER,CODEBUILD_BUILD_SUCCEEDING,CODEBUILD_INITIATOR(codepipeline/<pipeline>when a pipeline started it),CODEBUILD_WEBHOOK_TRIGGER(pr/<n>,branch/<name>,tag/<name>),CODEBUILD_SRC_DIR,AWS_REGION,AWS_DEFAULT_REGION. - S3 cache: list folders under
cache.paths; an optionalkey(exact match) with up to 5fallback-keys(prefix match);codebuild-hash-files <glob>builds a key from file contents;action: restoreorsave(default both); share across projects with the samecacheNamespace, key, paths and bucket. Best for small to medium items that are slower to rebuild than to download, and when builds run on many hosts. - Local cache (modes
LOCAL_SOURCE_CACHE,LOCAL_DOCKER_LAYER_CACHE,LOCAL_CUSTOM_CACHE): only builds on the same host benefit, so it suits frequent builds; the Docker layer cache is Linux-only and needs privileged mode; the custom cache takes directories only (symlinked into the build); not available withLINUX_GPU_CONTAINERorBUILD_GENERAL1_2XLARGE. - Lambda compute supports no caching.
Developer angle
version: 0.2
env:
variables:
STAGE: "test"
parameter-store:
API_BASE_URL: /orders/test/api-base-url
secrets-manager:
DB_PASSWORD: "orders/test/db:password"
PARTNER_TOKEN: "arn:aws:secretsmanager:eu-west-1:444455556666:secret:partner-token-AbCdEf"
exported-variables:
- IMAGE_TAG
phases:
build:
commands:
- export IMAGE_TAG="$(echo "$CODEBUILD_RESOLVED_SOURCE_VERSION" | cut -c1-8)"
- ./scripts/integration-tests.sh
cache:
key: npm-$(codebuild-hash-files package-lock.json)
fallback-keys:
- npm-
paths:
- "node_modules/**/*"
- Least-privilege service role for those references:
ssm:GetParametersonarn:aws:ssm:eu-west-1:111122223333:parameter/orders/test/*,secretsmanager:GetSecretValueon the two secret ARNs (…:secret:orders/test/db-*and the partner account's full ARN, which that account's secret policy must also allow), andkms:Decrypton any customer managed key that protects them.
# Local cache on the build host (Docker layers need privileged mode)
aws codebuild update-project --name orders-build \
--cache '{"type": "LOCAL", "modes": ["LOCAL_SOURCE_CACHE", "LOCAL_DOCKER_LAYER_CACHE"]}'
# Throw the cache away after a bad dependency got cached
aws codebuild invalidate-project-cache --project-name orders-build
Traps
- Trap: "A
PLAINTEXTproject variable is encrypted, so it's fine for a password." → Reality: plaintext variables are visible in the console and CLI; usePARAMETER_STOREorSECRETS_MANAGER. - Trap: "Secrets stay masked whatever the build does with them." → Reality: only the exact stored value is masked; an encoded or concatenated copy is printed.
- Trap: "Set the variable in the buildspec to override the value the pipeline passes." → Reality: start-build (and pipeline action) overrides beat the project, which beats the buildspec.
- Trap: "Export the database password to the deploy stage." → Reality: project-defined Parameter Store and Secrets Manager values can't be exported; let the next action read the secret itself.
- Trap: "A local cache speeds up every build in the account." → Reality: it lives on one host; use an S3 cache when builds land on different hosts or run rarely.
Practice questions
-
A build must call a partner API with a token stored in AWS Secrets Manager as the JSON key
tokenof the secretpartner-api. The token must not appear in the project configuration or the build logs, and the service role must follow least privilege. What should the developer configure?- A. A project environment variable of type
PLAINTEXTthat holds the token value. - B. An
env/secrets-managerentryTOKEN: "partner-api:token"andsecretsmanager:GetSecretValueon that secret's ARN for the service role. - C. A
pre_buildcommand that runsaws secretsmanager get-secret-valueand writes the token into a file in the artifact. - D.
secretsmanager:*on*for the service role, with the application reading the secret at startup.
- A. A project environment variable of type
-
A Java project spends most of each build downloading Maven dependencies and pulling a large base image. Builds run many times a day and can land on different build hosts; the base image layers rarely change. Which TWO cache settings help the most? (Select TWO.)
- A. An S3 cache with
pathsset to'/root/.m2/**/*'. - B. A local cache in
LOCAL_DOCKER_LAYER_CACHEmode with privileged mode enabled. - C. A move to Lambda compute with an S3 cache for the Maven directory.
- D. A
LOCAL_CUSTOM_CACHEthat lists each dependency JAR file individually. - E. A longer
queuedTimeoutInMinutesso that the cache has time to warm up.
- A. An S3 cache with
Answers
- B. The
secrets-managermapping resolves the JSON key at run time and masks it, and the role can read one secret only. A exposes the token in the console and CLI; C copies the secret into an artifact; D breaks least privilege. - A, B. The S3 cache is shared by all hosts, which suits the dependency folder, and frequent builds make hits on the host-local Docker layer cache likely (privileged mode required). C fails because Lambda compute has no caching; D fails because custom local caches take directories only; E has nothing to do with caching.
6. CodeDeploy on EC2 and on premises
Concept
- CodeDeploy pushes a revision (your files plus
appspec.yml, either a zip, tar or tar.gz bundle in S3 — tar formats not on Windows — or a GitHub commit) to the instances of a deployment group, following a deployment configuration that limits how many instances may be out of service at once. - On EC2 and on-premises servers an agent does the work on each host: it polls CodeDeploy, downloads the revision, copies files and runs your hook scripts. Lambda and ECS deployments need no agent.
- Two roles are involved: the service role (CodeDeploy reading tags, Auto Scaling groups, load balancers and alarms) and the instance profile (the agent downloading the revision).
Exam facts
- Building blocks: application (compute platform
Server,LambdaorECS) → deployment groups (targets by EC2 tags, Auto Scaling groups or on-premises tags; load balancer; configuration; alarms; rollback; triggers) → deployments of revisions. - Deployment types: in-place (stop, install and start on the existing instances, optionally taking each out of the load balancer meanwhile) or blue/green (new instances, traffic switched at the load balancer). Blue/green works with EC2 instances only, never on-premises servers.
- Predefined configurations:
CodeDeployDefault.OneAtATime(used when none is set; the overall deployment still succeeds if only the last instance fails),CodeDeployDefault.HalfAtATime(up to half the instances at a time, rounded down; at least half, rounded up, must succeed),CodeDeployDefault.AllAtOnce(succeeds if at least one instance succeeds). - Custom configurations: minimum healthy hosts as
HOST_COUNTorFLEET_PERCENT; an optional zonal configuration deploys one Availability Zone at a time (monitorDurationInSeconds,firstZoneMonitorDurationInSeconds,minimumHealthyHostsPerZone, default 0 %) for in-place EC2 deployments only and never on predefined configurations; up to 50 custom configurations per account. - Agent: needed for EC2/on-premises only; talks outbound over HTTPS on 443; reads instance metadata on EC2; install or update it with Systems Manager Distributor (
AWSCodeDeployAgentfor 1.8.x,AWSCodeDeployAgentV2for 2.x) or the install script in the Regionalaws-codedeploy-<region>bucket; minimum supported version 1.8.x. - ⚠️ Changed: agent 2.x (2.0.0 released 2026-07-15) is a Rust-based single binary that no longer needs Ruby; it is an opt-in upgrade with no automatic path from 1.8.x and is still rolling out by Region. Older material may say the agent requires Ruby.
- Agent files on Linux: logs in
/var/log/aws/codedeploy-agent/; each deployment in/opt/codedeploy-agent/deployment-root/<group-id>/<deployment-id>/withlogs/scripts.log; five archived revisions kept by default (:max_revisions:). - Instance profile:
s3:Get*ands3:List*on the revision bucket (plus theaws-codedeploy-<region>bucket to install or update the agent, andAmazonSSMManagedInstanceCoreif Systems Manager installs it); GitHub revisions need no extra permission. Instance profile mechanics: seenotes/ec2-mastery-guide.md§1. - Service role: trusted by
codedeploy.amazonaws.com; AWS managed policyAWSCodeDeployRolefor EC2/on-premises; when blue/green copies an Auto Scaling group that uses a launch template, addec2:RunInstances,ec2:CreateTagsandiam:PassRole. - On-premises registration:
register-on-premises-instancewith an IAM session ARN and periodically refreshed STS credentials (recommended, most secure) or with an IAM user ARN (theregistercommand, not recommended for production); then tag the server and install the agent. - Blue/green on EC2: needs a Classic, Application or Network Load Balancer; the replacement fleet is a copy of an Auto Scaling group (named
CodeDeploy_<group>_<deployment-id>) or instances you pick by tag; traffic moves at once (CONTINUE_DEPLOYMENT) or waits for you (STOP_DEPLOYMENT, thencontinue-deployment, within 48 hours); original instances are terminated after a wait of up to 2,880 minutes (2 days) or kept running (KEEP_ALIVE). - Auto Scaling: CodeDeploy installs a launch lifecycle hook, so new instances automatically receive the last successful revision; a scale-out during a deployment gets the previous revision, and CodeDeploy follows up with a deployment to the outdated instances; an optional termination hook runs
ApplicationStopand the block-traffic hooks during scale-in. Avoid attaching several deployment groups to one Auto Scaling group. Lifecycle hooks in general: seenotes/ec2-mastery-guide.md§10. - Limits: an in-place deployment runs at most 12 hours (8 hours for custom configurations created before June 2023), a blue/green deployment 109 hours; one deployment at a time per deployment group.
Developer angle
# Zip the folder that holds appspec.yml, upload it and register the revision, then deploy it
aws deploy push --application-name orders-app --s3-location s3://orders-revisions/orders-app-v42.zip --source ./build
aws deploy create-deployment --application-name orders-app --deployment-group-name orders-prod \
--deployment-config-name CodeDeployDefault.HalfAtATime \
--s3-location bucket=orders-revisions,key=orders-app-v42.zip,bundleType=zip
# Keep 75 % healthy overall and roll through one Availability Zone at a time
aws deploy create-deployment-config --deployment-config-name Healthy75OneZoneAtATime \
--minimum-healthy-hosts type=FLEET_PERCENT,value=75 \
--zonal-config '{"monitorDurationInSeconds":900,"minimumHealthyHostsPerZone":{"type":"FLEET_PERCENT","value":50}}'
# Install the 2.x agent on tagged instances with Systems Manager Distributor
aws ssm send-command --document-name AWS-ConfigureAWSPackage --targets Key=tag:App,Values=orders \
--parameters '{"action":["Install"],"name":["AWSCodeDeployAgentV2"]}'
Traps
- Trap: "Use blue/green for the on-premises servers." → Reality: blue/green needs EC2 instances; on-premises servers get in-place deployments.
- Trap: "Give the CodeDeploy service role S3 read access so instances can download the bundle." → Reality: the agent downloads with the instance profile.
- Trap: "
AllAtOncefails unless every instance succeeds." → Reality: it succeeds when at least one instance succeeds;OneAtATimeeven tolerates a failure on the last instance. - Trap: "Instances launched by a scale-out during a deployment get the new version." → Reality: they get the last successful revision; CodeDeploy then deploys to them again.
- Trap: "Add a zonal configuration to
HalfAtATime." → Reality: zonal settings exist only on custom configurations. - Trap: "Register the data-centre servers with an IAM user's access keys." → Reality: prefer an IAM session ARN with refreshed STS credentials.
Practice questions
-
Twelve EC2 instances behind an Application Load Balancer run an API. During in-place deployments at least nine instances must keep serving traffic, and the deployment should finish as quickly as that allows. Which deployment configuration should the developer choose?
- A.
CodeDeployDefault.HalfAtATime. - B. A custom configuration with minimum healthy hosts
HOST_COUNT9. - C.
CodeDeployDefault.OneAtATime. - D.
CodeDeployDefault.AllAtOnce.
- A.
-
A blue/green deployment that copies an existing Auto Scaling group fails right after it starts with the error code
IAM_ROLE_PERMISSIONS. The Auto Scaling group uses a launch template. Which TWO changes fix the problem? (Select TWO.)- A. Add
ec2:RunInstancesandec2:CreateTagsto the CodeDeploy service role. - B. Allow the CodeDeploy service role to call
iam:PassRolefor the role in the launch template's instance profile. - C. Add
s3:GetObjecton the revision bucket to the instances' instance profile. - D. Reinstall the CodeDeploy agent with the
AWSCodeDeployAgentV2package. - E. Change the deployment configuration to
CodeDeployDefault.AllAtOnce.
- A. Add
Answers
- B. Nine healthy hosts let three instances update at a time, the fastest rollout that respects the constraint. A leaves only six serving; C meets the constraint but updates one instance at a time; D can take every instance out of service.
- A, B. Copying an Auto Scaling group that uses a launch template requires the service role to launch and tag instances and to pass the instance role. C concerns the agent's revision download, which comes later; D and E don't change the service role's permissions.
7. AppSpec files and lifecycle hooks
Concept
- The AppSpec file is the per-revision contract with CodeDeploy. On EC2/on-premises it maps files from the bundle to paths on the instance, sets permissions and names the scripts to run at each lifecycle event. For Lambda and ECS it names what to deploy (a function version or a task definition) and the Lambda functions that validate the deployment.
- Lifecycle events run in a fixed order; some belong to CodeDeploy, the others are hooks where your code runs.
Exam facts
- EC2/on-premises: YAML only, named
appspec.ymlat the root of the revision (agent 1.3.2 and later also accept the.yamlextension; local deployments may use another name); sectionsversion: 0.0,os(linuxorwindows),files(sourcerelative to the bundle root → absolutedestination),permissions,hooks, optional top-levelfile_exists_behavior. - Lambda and ECS: YAML or JSON, stored in S3 or typed into the console or an
AppSpecContentrevision. - In-place order on EC2:
ApplicationStop→DownloadBundle→BeforeInstall→Install→AfterInstall→ApplicationStart→ValidateService. With a load balancer,BeforeBlockTraffic→BlockTraffic→AfterBlockTrafficcome first andBeforeAllowTraffic→AllowTraffic→AfterAllowTrafficcome last. - Reserved events (no scripts):
DownloadBundle,Install,BlockTraffic,AllowTraffic(plusStartandEnd); thefilessection controls whatInstallcopies. ApplicationStop,BeforeBlockTrafficandAfterBlockTrafficrun scripts from the previous successful revision;ApplicationStopdoesn't run on the first deployment to an instance. A broken old script is bypassed withignoreApplicationStopFailures(--ignore-application-stop-failures), which skips failures of all three of these events.- Hook entry:
location(relative to the bundle root),timeoutin seconds (default 3,600; 3,600 is also the maximum for all scripts of one event together),runas(Amazon Linux and Ubuntu Server only). A script succeeds by exiting with 0. - Hook scripts see
APPLICATION_NAME,DEPLOYMENT_ID,DEPLOYMENT_GROUP_NAME,DEPLOYMENT_GROUP_IDandLIFECYCLE_EVENT, plusBUNDLE_BUCKET,BUNDLE_KEY,BUNDLE_VERSION,BUNDLE_ETAG(S3 bundle) orBUNDLE_COMMIT(GitHub). file_exists_behaviorfor files at the destination that the last successful deployment didn't install:DISALLOW(default, the deployment fails),OVERWRITE,RETAIN; the AppSpec value wins over--file-exists-behavior.- Lambda AppSpec:
resourceswithtype: AWS::Lambda::Functionandname,alias,currentversion,targetversion(all required; versions are integers); hooksBeforeAllowTrafficandAfterAllowTrafficname Lambda functions. - ECS AppSpec:
TargetServiceofType: AWS::ECS::ServicewithTaskDefinition(ARN),LoadBalancerInfo(ContainerName,ContainerPort), optionalPlatformVersion,NetworkConfiguration(subnets, security groups and public IP setting together or not at all) andCapacityProviderStrategy; hooksBeforeInstall,AfterInstall,AfterAllowTestTraffic,BeforeAllowTraffic,AfterAllowTraffic. - A validation function reports with
PutLifecycleEventHookExecutionStatus(SucceededorFailed), using theDeploymentIdandLifecycleEventHookExecutionIdfrom its event; without a report within one hour the deployment fails. Its role needscodedeploy:PutLifecycleEventHookExecutionStatus.
Developer angle
EC2 appspec.yml:
version: 0.0
os: linux
files:
- source: /app
destination: /opt/orders
file_exists_behavior: OVERWRITE
hooks:
ApplicationStop:
- location: scripts/stop.sh
AfterInstall:
- location: scripts/configure.sh
runas: orders
ValidateService:
- location: scripts/health_check.sh
timeout: 600
Lambda AppSpec and its validation function:
version: 0.0
resources:
- ordersFunction:
type: AWS::Lambda::Function
properties:
name: orders-handler
alias: live
currentversion: "7"
targetversion: "8"
hooks:
- BeforeAllowTraffic: orders-pretraffic-check
- AfterAllowTraffic: orders-posttraffic-check
import boto3
codedeploy = boto3.client("codedeploy")
def handler(event, context):
passed = True # call the new version here and check the results
codedeploy.put_lifecycle_event_hook_execution_status(
deploymentId=event["DeploymentId"],
lifecycleEventHookExecutionId=event["LifecycleEventHookExecutionId"],
status="Succeeded" if passed else "Failed",
)
- The ECS AppSpec has the same shape with capitalised keys:
Resources→TargetService(Type: AWS::ECS::Service,PropertieswithTaskDefinitionandLoadBalancerInfo) and aHookslist (CodeDeploy for ECS: §8).
Traps
- Trap: "Ship
appspec.jsonfor the EC2 fleet." → Reality: EC2/on-premises AppSpec files are YAML (appspec.ymlat the bundle root); JSON is for Lambda and ECS. - Trap: "Fix the failing
ApplicationStopscript in the new revision." → Reality: that event runs the previous revision's script; redeploy withignoreApplicationStopFailures. - Trap: "Run the database migration in the
Installhook." → Reality:Installis reserved; useBeforeInstallorAfterInstall. - Trap: "A validation Lambda that simply returns signals success." → Reality: it must call
PutLifecycleEventHookExecutionStatus, or the deployment fails after an hour. - Trap: "
ValidateServiceexists for Lambda deployments." → Reality: Lambda has onlyBeforeAllowTrafficandAfterAllowTraffic;AfterAllowTestTrafficis ECS-only. - Trap: "Leftover files are overwritten by default." → Reality: the default
DISALLOWfails the deployment.
Practice questions
-
Every deployment to an EC2 fleet fails during
ApplicationStopbecause the stop script of the currently installed revision calls a file that an operator deleted. The new revision contains a corrected script. How can the developer get the new revision deployed fastest?- A. Add the corrected script to the new revision's
ApplicationStophook and deploy again. - B. Create a new deployment with
--ignore-application-stop-failures. - C. Move the stop logic into the
Installevent of the new revision. - D. Raise the
ApplicationStophook timeout to 3,600 seconds.
- A. Add the corrected script to the new revision's
-
A team deploys a Lambda function with CodeDeploy canary traffic shifting. Integration tests must run against the new version before any production traffic reaches it, and a failed test must stop the deployment. Which TWO actions meet these requirements? (Select TWO.)
- A. Add a
BeforeAllowTraffichook that names a test function in the AppSpec file. - B. Have the test function call
PutLifecycleEventHookExecutionStatuswithFailedwhen a test fails. - C. Add a
ValidateServicehook that runs the integration tests. - D. Add an
AfterAllowTestTraffichook and a test listener to the deployment group. - E. Have the test function raise an exception so that CodeDeploy reads the error and stops.
- A. Add a
Answers
- B.
ApplicationStopruns the script of the last successful revision, so a new script can't help; ignoringApplicationStopfailures lets the deployment continue and install the fixed revision. A doesn't change which script runs; C uses a reserved event; D doesn't bring back a missing file. - A, B.
BeforeAllowTrafficruns before the first traffic shift, and the hook must reportFailedthrough the API to stop the deployment. C is an EC2/on-premises event; D exists only for ECS; E isn't a reporting mechanism, so the deployment would wait for the API call until it times out.
8. CodeDeploy for Lambda and ECS
Concept
- For Lambda and ECS, CodeDeploy never updates in place: it shifts traffic from the old version to the new one and can shift it back. Lambda shifting happens on an alias (weights between two published versions); ECS shifting happens on the load balancer listener (from the original task set's target group to the replacement task set's target group).
- The deployment configuration sets the shape of the shift: canary (a slice first, the rest after one wait), linear (equal slices at fixed intervals) or all at once.
Exam facts
- Lambda predefined configurations:
CodeDeployDefault.LambdaCanary10Percent5Minutes,…10Minutes,…15Minutes,…30Minutes;CodeDeployDefault.LambdaLinear10PercentEvery1Minute,…Every2Minutes,…Every3Minutes,…Every10Minutes;CodeDeployDefault.LambdaAllAtOnce. - ⚠️ Changed: the ECS predefined configurations are
CodeDeployDefault.ECSLinear10PercentEvery1Minutes,CodeDeployDefault.ECSLinear10PercentEvery3Minutes,CodeDeployDefault.ECSCanary10Percent5Minutes,CodeDeployDefault.ECSCanary10Percent15MinutesandCodeDeployDefault.ECSAllAtOnce. Older material may listECSLinear10PercentEvery10MinutesandECSCanary10Percent30Minutes, which exist only if you create them as custom configurations. - Custom Lambda or ECS configurations:
TimeBasedCanary(canaryPercentage,canaryIntervalin minutes) orTimeBasedLinear(linearPercentage,linearInterval); step 1–99 %. - Lambda limits: at most 2,880 minutes between the first and the last traffic shift; a Lambda deployment runs at most 50 hours (48 hours of shifting plus one hour per hook).
- Lambda prerequisites: the alias exists and points at a published version, and the new version is published. Weighted aliases: see
notes/lambda-guide.md; SAM'sAutoPublishAliasandDeploymentPreferencecreate all of this for you (seenotes/sam-guide.md). - ECS prerequisites: the service's
deploymentControllertype isCODE_DEPLOY; ⚠️ Changed: an Application Load Balancer or a Network Load Balancer (ALB recommended; with an NLB onlyCodeDeployDefault.ECSAllAtOnceis supported). Older material may say an ALB is required. Plus one production listener, an optional test listener, two target groups, and one deployment group per ECS service. - ECS flow: replacement task set created (
Install) → test listener traffic (AllowTestTraffic) → production traffic (AllowTraffic) → original task set removed afterterminationWaitTimeInMinutes(up to 2,880 minutes). A rollback reroutes traffic back to the original task set. - ⚠️ Changed: Amazon ECS also runs blue/green deployments (since 2025-07-17) and linear and canary deployments (since 2025-10-30) itself, without CodeDeploy (
deploymentControllerECS,strategyBLUE_GREEN,LINEARorCANARY, a bake time before the old revision is removed). Older material may say CodeDeploy is the only way to run blue/green on ECS. Supported traffic routes and details: seenotes/containers-guide.md. - Moving between the two: CodeDeploy hooks are Lambda functions named in each deployment's AppSpec and must call
PutLifecycleEventHookExecutionStatuswithin an hour; ECS-native lifecycle hooks (Lambda functions or pause points resumed withContinueServiceDeployment) are part of the service's deployment configuration. - ECS blue/green managed through CloudFormation can't use custom deployment configurations (see
notes/cloudformation-guide.md). - CodePipeline's Lambda deploy action (V2 pipelines only) also shifts alias traffic (
DeployStrategysuch asCanary10Percent5MinutesorLinear10PercentEvery1Minute, defaultAllAtOnce; at most 2 days; up to 10 alarms) without a CodeDeploy application (§10). - Service role managed policies:
AWSCodeDeployRoleForLambda(or…Limited) andAWSCodeDeployRoleForECS(or…Limited).
Developer angle
# Custom canary: 20 % first, the rest after 15 minutes
aws deploy create-deployment-config --deployment-config-name Canary20Percent15Minutes --compute-platform Lambda \
--traffic-routing-config 'type=TimeBasedCanary,timeBasedCanary={canaryPercentage=20,canaryInterval=15}'
# ECS blue/green deployment group
aws deploy create-deployment-group --application-name orders-ecs --deployment-group-name orders-web-bg \
--service-role-arn arn:aws:iam::111122223333:role/CodeDeployECSRole \
--deployment-config-name CodeDeployDefault.ECSCanary10Percent5Minutes \
--deployment-style deploymentType=BLUE_GREEN,deploymentOption=WITH_TRAFFIC_CONTROL \
--ecs-services clusterName=orders,serviceName=orders-web \
--load-balancer-info file://lb-info.json --blue-green-deployment-configuration file://bg-config.json \
--auto-rollback-configuration '{"enabled":true,"events":["DEPLOYMENT_FAILURE","DEPLOYMENT_STOP_ON_ALARM"]}'
lb-info.jsonholds onetargetGroupPairInfoListentry: the twotargetGroups, theprodTrafficRoutelistener ARN and the optionaltestTrafficRoutelistener ARN (one listener per route).bg-config.jsonsetsterminateBlueInstancesOnDeploymentSuccess(TERMINATEafterterminationWaitTimeInMinutes, orKEEP_ALIVE) anddeploymentReadyOption.
Traps
- Trap: "Pick
CodeDeployDefault.ECSCanary10Percent30Minutes." → Reality: it isn't predefined; create a customTimeBasedCanary. - Trap: "CodeDeploy canary shifting works behind the existing Network Load Balancer." → Reality: with an NLB CodeDeploy supports only
ECSAllAtOnce; put the service behind an ALB. - Trap: "Run an in-place deployment of the Lambda function." → Reality: Lambda and ECS deployments always shift traffic.
- Trap: "Shift traffic from
$LATEST." → Reality: CodeDeploy moves an alias between published version numbers. - Trap: "Keep the ECS service on the
ECSdeployment controller and add a CodeDeploy group." → Reality: CodeDeploy needsCODE_DEPLOY; ECS-native blue/green usesECS. - Trap: "Linear 10 % every 10 minutes finishes in 10 minutes." → Reality: it needs nine 10-minute waits (about 90 minutes);
LambdaCanary10Percent10Minutesfinishes after a single 10-minute wait.
Practice questions
-
An ECS service on Fargate sits behind a Network Load Balancer. The team wants CodeDeploy to send 10 % of traffic to a new task set, wait 15 minutes, and then shift the rest. What should the developer do?
- A. Use
CodeDeployDefault.ECSCanary10Percent15Minuteswith the existing Network Load Balancer. - B. Put the service behind an Application Load Balancer with two target groups and use
CodeDeployDefault.ECSCanary10Percent15Minutes. - C. Change the deployment group to an in-place deployment with
CodeDeployDefault.HalfAtATime. - D. Set the service's deployment controller to
ECSand keep using the CodeDeploy deployment group.
- A. Use
-
A Lambda function is invoked through the alias
live. Each release must send 10 % of traffic to the new version for 10 minutes before the rest moves, and all traffic must return to the old version automatically if an error-rate alarm fires. Which TWO settings meet these requirements? (Select TWO.)- A. The deployment configuration
CodeDeployDefault.LambdaCanary10Percent10Minutes. - B. The alarm added to the deployment group, with automatic rollback when an alarm threshold is met.
- C. The deployment configuration
CodeDeployDefault.LambdaLinear10PercentEvery10Minutes. - D. The alias pointed at
$LATESTwith a second version weighted at 10 %. - E.
ignorePollAlarmFailureset totruein the deployment group's alarm configuration.
- A. The deployment configuration
Answers
- B. CodeDeploy supports canary shifting for ECS only with an Application Load Balancer; behind a Network Load Balancer only
ECSAllAtOnceworks. A isn't supported with an NLB; C is impossible for ECS; D breaks the CodeDeploy integration, which needs theCODE_DEPLOYcontroller. - A, B. The canary configuration matches the 10 %-then-the-rest shape, and alarm-based rollback (
DEPLOYMENT_STOP_ON_ALARM) moves traffic back. C takes about 90 minutes in ten steps; D can't work because CodeDeploy shifts between published versions; E lets deployments continue when alarm states can't be read, the opposite of what is needed.
9. CodeDeploy rollbacks and troubleshooting
Concept
- A CodeDeploy rollback is simply another deployment: it redeploys the most recent revision that succeeded and gets a fresh deployment ID. How fast it is depends on the platform: Lambda and ECS move traffic back, EC2 blue/green reroutes to the original instances if they still exist, EC2 in-place reinstalls the older files.
- Most failed deployments come from a short list: the agent, one of the two IAM roles, the bundle and its AppSpec, a hook script, or the health constraints of the deployment configuration.
Exam facts
- Automatic rollback events:
DEPLOYMENT_FAILURE,DEPLOYMENT_STOP_ON_ALARM,DEPLOYMENT_STOP_ON_REQUEST; set on the deployment group and overridable (or switched off) for one deployment. A manual rollback is a deployment of an earlier revision. - Alarms: the API reference and user guide allow 10 CloudWatch alarms per deployment group (
AlarmsLimitExceededException), ⚠️ unverified: the quotas page lists 50 (adjustable), so don't rely on the exact number. The service role must be able to read the alarms (AWSCodeDeployRolecan). When an alarm entersALARMthe deployment stops (statusStopped), and onlyDEPLOYMENT_STOP_ON_ALARMin the rollback settings reverts it.ignorePollAlarmFailure(defaultfalse) decides whether a deployment continues when alarm states can't be read.overrideAlarmConfigurationonCreateDeploymentneeds theUpdateDeploymentGrouppermission. - A redeploy on EC2 first removes the files listed in the deployment group's cleanup file (installed by the last successful deployment); files your scripts created stay, and CodeDeploy doesn't undo script side effects.
- Notifications: up to 10 SNS triggers per deployment group (deployment and instance events, including automatic rollbacks), EventBridge events and notification rules.
- Error codes to recognise:
| Code | Meaning |
|---|---|
HEALTH_CONSTRAINTS |
Too many instances failed to stay above the minimum healthy hosts; this is the code an EC2/on-premises deployment gets when hook scripts fail on too many instances (each failed instance's lifecycle event shows a script error code such as ScriptFailed, ScriptTimedOut or ScriptMissing) |
HEALTH_CONSTRAINTS_INVALID |
The configuration can never be met (for example minimum healthy hosts equals the fleet size) |
IAM_ROLE_MISSING / IAM_ROLE_PERMISSIONS |
The service role can't be accessed or lacks permissions |
NO_INSTANCES |
No instance matches the tags or Auto Scaling groups |
AGENT_ISSUE |
A problem with the agent: not installed, not running or unable to reach CodeDeploy |
TIMEOUT |
The deployment ran out of time |
ALARM_ACTIVE / MANUAL_STOP |
Stopped by an alarm or by a person |
HOOK_EXECUTION_FAILURE |
A lifecycle hook failed (⚠️ unverified: the API lists the code without a description, and the CodeDeploy User Guide doesn't say which platforms report it; a failing EC2 hook script ends in HEALTH_CONSTRAINTS) |
REVISION_MISSING |
The revision was deleted before the deployment started |
- Timing rules: a lifecycle event fails after 3,600 seconds; a deployment fails if a lifecycle event doesn't start within 5 minutes (usually the agent isn't running or can't reach CodeDeploy).
- Symptoms and causes:
DownloadBundlefails with access denied → the instance profile lacks S3 read; the AppSpec file isn't found →appspec.ymlisn't at the bundle root; a script exits non-zero → the deployment to that instance fails (ScriptFailedin its lifecycle event, thenHEALTH_CONSTRAINTSfor the deployment once too many instances fail), so readscripts.login the deployment's folder;ApplicationStopfails → the old revision's script (useignoreApplicationStopFailures); deployments hang for about an hour → several deployment groups share one Auto Scaling group.
Developer angle
# Why did it fail?
aws deploy get-deployment --deployment-id d-ABCDEFGH1 \
--query 'deploymentInfo.[status,errorInformation.code,errorInformation.message,rollbackInfo]'
aws deploy list-deployment-targets --deployment-id d-ABCDEFGH1 --target-filters '{"TargetStatus":["Failed"]}'
# Alarms plus automatic rollback on the deployment group
aws deploy update-deployment-group --application-name orders-app --current-deployment-group-name orders-prod \
--alarm-configuration '{"enabled":true,"ignorePollAlarmFailure":false,"alarms":[{"name":"orders-5xx-high"},{"name":"orders-p99-latency"}]}' \
--auto-rollback-configuration '{"enabled":true,"events":["DEPLOYMENT_FAILURE","DEPLOYMENT_STOP_ON_ALARM"]}'
# Stop a bad deployment and roll back now (a manual rollback is a create-deployment of the old bundle)
aws deploy stop-deployment --deployment-id d-ABCDEFGH1 --auto-rollback-enabled
Traps
- Trap: "A rollback reuses the old deployment ID." → Reality: it is a new deployment with a new ID.
- Trap: "A rollback undoes everything the failed version changed." → Reality: it removes CodeDeploy-installed files and redeploys; script side effects (created files, database changes) remain.
- Trap: "An alarm that stops a deployment also rolls it back." → Reality: only with
DEPLOYMENT_STOP_ON_ALARMin the rollback configuration. - Trap: "Blue/green rollback is always instant." → Reality: only while the original instances still exist; after they're terminated, CodeDeploy must redeploy.
- Trap: "
HEALTH_CONSTRAINTS_INVALIDmeans instances are unhealthy." → Reality: the deployment can't start because the configuration can't be met; lower the minimum healthy hosts or add instances. - Trap: "Hook output shows up in CloudWatch Logs by default." → Reality: it is in the agent's
scripts.logon the instance unless you ship logs yourself.
Practice questions
-
A deployment group contains four instances. A deployment that uses a custom configuration requiring four healthy hosts fails immediately with
HEALTH_CONSTRAINTS_INVALID. What should the developer change?- A. Lower the configuration's minimum healthy hosts below the fleet size, for example
HOST_COUNT3. - B. Add
s3:Get*ands3:List*on the revision bucket to the instance profile. - C. Raise the
ValidateServicehook timeout to 3,600 seconds. - D. Enable automatic rollback on
DEPLOYMENT_FAILUREfor the deployment group.
- A. Lower the configuration's minimum healthy hosts below the fleet size, for example
-
A team wants any EC2 deployment to stop and revert automatically when the p99 latency alarm fires, and wants the on-call channel told when an automatic rollback happens. Which TWO steps meet these requirements? (Select TWO.)
- A. Add the alarm to the deployment group and enable rollback when alarm thresholds are met.
- B. Create a deployment group trigger that publishes rollback events to the on-call SNS topic.
- C. Set
ignorePollAlarmFailuretotrueso that alarm checks never block a deployment. - D. Add a termination lifecycle hook to the Auto Scaling group.
- E. Create a CloudTrail trail and search it for
CreateDeploymentcalls.
Answers
- A.
HEALTH_CONSTRAINTS_INVALIDmeans the configuration can never be satisfied: requiring all four of four hosts to stay healthy leaves none to update. B fixes download errors; C changes hook timing; D doesn't make the configuration valid. - A, B. Alarm-based rollback stops and reverts the deployment, and a deployment group trigger (SNS) reports rollbacks. C weakens the alarm check; D concerns scale-in; E is an audit trail, not a notification.
10. CodePipeline stages actions and artifacts
Concept
- A pipeline is an ordered list of stages; each stage holds actions (source, build, test, deploy, approval, invoke, compute). Actions in a stage with the same
runOrderrun in parallel; a higherrunOrderwaits for the lower ones. A stage works on one execution at a time (except in PARALLEL mode, §11). - Actions hand files to each other as artifacts: an action's output artifact is a ZIP (or a Git reference) stored in the pipeline's artifact store, an S3 bucket in the pipeline's Region, encrypted with KMS.
- The pipeline acts through its service role; an action can instead use a role in another account (
roleArn) for cross-account work.
Exam facts
- Structure rules: 2 to 50 stages; the first stage holds only source actions, and only the first stage may hold them; 1 to 50 actions per stage;
runOrder1–999; up to 1,000 actions per pipeline; 1,000 pipelines per Region; execution history kept 12 months. - ⚠️ Changed: providers by category — Source: CodeCommit, S3 (versioned bucket, single ZIP), ECR,
CodeStarSourceConnection(Bitbucket Cloud, GitHub, GitHub Enterprise Server, GitLab.com, GitLab self-managed); Build and test: CodeBuild,ECRBuildAndPublish, Jenkins, Device Farm, partner tools; Deploy: CodeDeploy,CodeDeployToECS(blue/green), ECS (rolling), EKS, EC2, Lambda (V2), Elastic Beanstalk, CloudFormation and StackSets, S3, AppConfig, Service Catalog; Approval: Manual; Invoke: Lambda, Step Functions, Inspector scan, another pipeline; Compute: Commands (V2). Older material may list a much shorter set and the GitHub (via OAuth app) action, which AWS no longer recommends. - Artifact size limits: S3 source 7 GB; CodeCommit or GitHub source 1 GB; Elastic Beanstalk deploy 512 MB; CloudFormation input 256 MB;
CodeDeployToECSinput 3 MB;imagedefinitions.json100 KB. - Default action timeouts: CodeBuild build 36 hours (test actions 8 hours), CodeDeploy 5 days, CloudFormation 3 days, Step Functions 7 days, Lambda invoke 24 hours (the function must answer within each 20-minute window), S3 deploy 90 minutes, Commands 55 minutes, manual approval 7 days (§12), most others 1 hour.
- Artifact encryption: the console creates
codepipeline-<region>-<number>; without a customer managed key the AWS managed S3 key is used. Cross-account actions need a customer managed KMS key whose key policy grants the other account, a bucket policy for that account, and a role in that account that the pipeline's service role assumes (roleArnon the action); refer to the key by its key ARN: aliases are recognized only in the account that owns the key, and a bare key ID is looked up in the other account, because the action runs with that account's role. An artifact can't travel between two accounts when neither is the pipeline's account, and Jenkins build actions can't be cross-account. - Cross-Region actions:
artifactStores(one bucket and key per Region where actions run) replacesartifactStore; CodePipeline copies the action's input artifacts; not allowed for source, third-party or custom actions. - ⚠️ Changed: change detection is event-based — EventBridge rules for CodeCommit, S3 and ECR (the console default) and connection-managed webhooks for GitHub, Bitbucket and GitLab; polling is legacy (at most 300 polling pipelines per Region, fixed) and is switched off for pipelines with no execution in 30 days. Older material may describe pipelines that poll their sources. When
PollForSourceChangesis missing from a CLI or CloudFormation definition it defaults to polling, so set it tofalsenext to an EventBridge rule or every change runs twice. - When a pipeline has several source actions, all of them run again even if only one changed.
- Variables: actions with a
namespacepublish output variables (#{SourceVariables.CommitId};#{BuildVariables.IMAGE_TAG}from CodeBuildexported-variables);#{codepipeline.PipelineExecutionId}is always available; pipeline-level variables (#{variables.name}) need V2. - Lambda invoke action: the function reads the job ID from
event["CodePipeline.job"]["id"]and must callPutJobSuccessResultorPutJobFailureResult, or the action hangs until it times out; the event carries temporary artifact credentials (artifactCredentials), so never log it. - Deploy actions for other services: Elastic Beanstalk (see
notes/beanstalk-guide.md), CloudFormation and change sets (seenotes/cloudformation-guide.md), ECS rolling and EKS (seenotes/containers-guide.md).
Developer angle
Skeleton of a three-stage V2 pipeline:
{ "pipeline": {
"name": "orders-pipeline", "pipelineType": "V2",
"roleArn": "arn:aws:iam::111122223333:role/orders-pipeline-role",
"artifactStore": { "type": "S3", "location": "codepipeline-eu-west-1-orders" },
"stages": [
{ "name": "Source", "actions": [{ "name": "App", "namespace": "SourceVariables",
"actionTypeId": { "category": "Source", "owner": "AWS", "provider": "CodeStarSourceConnection", "version": "1" },
"configuration": { "ConnectionArn": "arn:aws:codeconnections:eu-west-1:111122223333:connection/0a1b2c3d-EXAMPLE",
"FullRepositoryId": "acme/orders", "BranchName": "main" },
"outputArtifacts": [{ "name": "SourceOutput" }] }] },
{ "name": "Build", "actions": [{ "name": "TestAndPackage", "namespace": "BuildVariables",
"actionTypeId": { "category": "Build", "owner": "AWS", "provider": "CodeBuild", "version": "1" },
"configuration": { "ProjectName": "orders-build" },
"inputArtifacts": [{ "name": "SourceOutput" }], "outputArtifacts": [{ "name": "BuildOutput" }] }] },
{ "name": "Deploy", "actions": [{ "name": "ToProd",
"actionTypeId": { "category": "Deploy", "owner": "AWS", "provider": "CodeDeploy", "version": "1" },
"configuration": { "ApplicationName": "orders-app", "DeploymentGroupName": "orders-prod" },
"inputArtifacts": [{ "name": "BuildOutput" }] }] } ] } }
A Lambda invoke action that reports its result:
import boto3
codepipeline = boto3.client("codepipeline")
def handler(event, context):
job_id = event["CodePipeline.job"]["id"]
try:
# run the smoke tests here; raise on failure
codepipeline.put_job_success_result(jobId=job_id)
except Exception as exc:
codepipeline.put_job_failure_result(
jobId=job_id, failureDetails={"type": "JobFailed", "message": str(exc)[:500]})
- Edit with
aws codepipeline get-pipeline→ change the JSON →update-pipeline --cli-input-json, after deleting themetadatablock thatget-pipelinereturns.
Traps
- Trap: "Use an S3 bucket without versioning as the source." → Reality: the S3 source action needs a versioned bucket.
- Trap: "Add an EventBridge rule and leave the CLI-created source action as it is." → Reality:
PollForSourceChangesdefaults to polling; set it tofalse, or every change starts two executions. - Trap: "Cross-account deployment works with the default artifact encryption." → Reality: the other account can't use the AWS managed key; use a customer managed key, a bucket policy and a cross-account role.
- Trap: "Add a deploy action in us-east-1 to a pipeline in eu-west-1 without other changes." → Reality: the pipeline needs an artifact bucket (and key) in us-east-1 through
artifactStores. - Trap: "The Lambda invoke function just returns a value." → Reality: it must call
PutJobSuccessResultorPutJobFailureResult; and logging its event leaks temporary credentials. - Trap: "Pass the full-clone Git reference to CodeDeploy." → Reality: a
CODEBUILD_CLONE_REFartifact can only be used by CodeBuild (§13).
Practice questions
-
A pipeline in account A deploys with CodeDeploy to an application in account B through a cross-account role. The deploy action fails because account B can't read the input artifact. The artifact bucket uses the default encryption that the console set up. What must the developer do?
- A. Encrypt the artifact store with a customer managed KMS key whose key policy grants account B, and allow account B in the bucket policy.
- B. Make the artifact bucket publicly readable while deployments run.
- C. Recreate the pipeline as the V2 type so that cross-account actions are supported.
- D. Replace the action's
roleArnwith the CodeDeploy service role of account A.
-
A pipeline with an S3 source was created with the AWS CLI. Executions start only after a delay, and the account is close to its limit of polling pipelines. Which TWO changes implement the recommended change detection? (Select TWO.)
- A. Create an EventBridge rule for object changes in the source bucket (through S3 event notifications or a CloudTrail trail) that targets the pipeline.
- B. Set
PollForSourceChangestofalsein the S3 source action. - C. Suspend versioning on the source bucket so that fewer events are generated.
- D. Replace the S3 source action with a
CodeStarSourceConnectionaction that points at the bucket. - E. Request an increase of the polling pipelines quota.
Answers
- A. Account B can't use account A's AWS managed key, so cross-account pipelines need a customer managed key shared through its key policy, plus bucket access. B is insecure; C changes nothing because V1 pipelines support cross-account actions too; D removes the role that account B trusts.
- A, B. An EventBridge rule starts the pipeline as soon as the object changes, and turning polling off avoids duplicate runs. C breaks the source action, which needs versioning; D is for Git providers, not buckets; E is impossible because the polling quota is fixed at 300 per Region.
11. CodePipeline V2 triggers variables and execution modes
Concept
- CodePipeline has two pipeline types. V2 keeps the V1 structure and adds release-safety features (triggers with Git filters, queued or parallel runs, variables, stage conditions, rollbacks, retries, the Commands action) and is billed by action minutes instead of per pipeline.
- Execution modes decide what happens when changes arrive faster than the pipeline can finish them.
Exam facts
- ⚠️ Changed: V2 costs $0.002 per action execution minute (rounded up; manual approvals and custom actions are free; 100 free minutes per month per account); V1 costs $1.00 per active pipeline per month (active = older than 30 days with at least one code change that month, so a new pipeline is free for its first 30 days; one free active V1 pipeline per month). Older material may say every pipeline costs $1 per month.
- V2-only features: trigger filters, pipeline-level variables, source revision overrides, QUEUED and PARALLEL modes, stage conditions, stage rollback, automatic stage retry on failure, the Commands action and the Lambda deploy action.
- Triggers (only for
CodeStarSourceConnectionsources such as GitHub, Bitbucket and GitLab):pushfilters on branches, file paths or Git tags;pullRequestfilters on events (OPEN,UPDATED,CLOSED), branches and file paths; glob patterns; excludes win over includes; one trigger per source action; up to 50 triggers per pipeline, 3 filters per event type and 8 include plus 8 exclude patterns per filter. With branch filters, the action'sBranchNameis used only for manual starts. CodeCommit and S3 sources start through EventBridge instead. - Execution modes:
SUPERSEDED(default; a stage holds one execution, and a newer execution waiting between stages replaces an older waiting one),QUEUED(one by one in arrival order; nothing is skipped),PARALLEL(independent runs, for example one per feature branch; no stage rollback). QUEUED and PARALLEL allow up to 50 concurrent executions per pipeline. - Pipeline-level variables: up to 50 per pipeline with default values, referenced as
#{variables.<name>}, overridden withstart-pipeline-execution --variables. - Source revision overrides at start:
COMMIT_ID,IMAGE_DIGEST,S3_OBJECT_VERSION_ID,S3_OBJECT_KEY(the last needsAllowOverrideForS3ObjectKey). - Stage conditions with rules (
CloudWatchAlarm,CodeBuild,Commands,DeploymentWindow,LambdaInvoke,VariableCheck; a condition is met only when all its rules succeed): entry conditions (beforeEntry) with resultFAILorSKIP(SKIPworks only withLambdaInvokeorVariableCheckrules); on failure conditions withROLLBACK; on success conditions withROLLBACKorFAIL. Most conditions can be overridden while running;SKIPcan't. - Stage rollback (manual or automatic): runs a new execution of the stage with the source revisions and variables of an earlier successful execution; not for the source stage, only back to executions started with the current pipeline structure version, never to a rollback execution, and not in PARALLEL mode.
- Retry:
retry-stage-executionwithFAILED_ACTIONSorALL_ACTIONS, or automatic retry on stage failure (V2, one attempt, not combined with on-failure conditions); a failed execution that another execution superseded can't be retried. - Commands action (category Compute): single-line shell commands on CodePipeline-managed CodeBuild compute without a CodeBuild project; 55-minute timeout; billed as CodeBuild and counted against CodeBuild concurrency quotas; supports
SECRETS_MANAGERenvironment variables; logs in/aws/codepipeline/<pipeline>. - Stopping an execution: stop and wait (in-progress actions finish; recommended) or stop and abandon (CodePipeline abandons the actions, but the target service, for example a CloudFormation stack update, may keep going).
Developer angle
Trigger block that starts the pipeline for release tags, for changes to one service folder on main, and for pull requests into main:
{ "triggers": [{
"providerType": "CodeStarSourceConnection",
"gitConfiguration": {
"sourceActionName": "App",
"push": [
{ "tags": { "includes": ["release-*"] } },
{ "branches": { "includes": ["main"] },
"filePaths": { "includes": ["services/orders/**"], "excludes": ["**/*.md"] } } ],
"pullRequest": [ { "events": ["OPEN", "UPDATED"], "branches": { "includes": ["main"] } } ] } }] }
# executionMode and triggers are fields of the V2 pipeline JSON (apply with update-pipeline)
# Start with a variable value and a pinned commit
aws codepipeline start-pipeline-execution --name orders-pipeline --variables name=TARGET_ENV,value=staging \
--source-revisions actionName=App,revisionType=COMMIT_ID,revisionValue=8cf40f2EXAMPLE
# Retry only the failed actions, or roll the stage back to an earlier successful execution
aws codepipeline retry-stage-execution --pipeline-name orders-pipeline --stage-name Deploy \
--pipeline-execution-id 3137f7cb-7cf7-4a1b-9c2d-0123456789ab --retry-mode FAILED_ACTIONS
aws codepipeline rollback-stage --pipeline-name orders-pipeline --stage-name Deploy \
--target-pipeline-execution-id 9f8e7d6c-5b4a-4321-8fed-0123456789ab
Traps
- Trap: "Add a Git tag trigger to the CodeCommit source action." → Reality: trigger filters work only with connection sources; CodeCommit pipelines start from EventBridge.
- Trap: "In SUPERSEDED mode every waiting change eventually runs." → Reality: a newer waiting execution replaces older ones between stages; use QUEUED to run every change.
- Trap: "Use PARALLEL mode for production and rely on stage rollback." → Reality: PARALLEL mode has no stage rollback; it suits isolated feature-branch environments.
- Trap: "Roll back the Source stage." → Reality: source stages can't be rolled back.
- Trap: "V2 always costs more than V1." → Reality: V2 charges only action minutes (approvals free, 100 free minutes), so short or rarely used pipelines can cost less.
- Trap: "Stop and abandon cancels the running CloudFormation update." → Reality: the action is abandoned in CodePipeline, but the stack operation may continue.
Practice questions
-
A team's pipeline deploys every merge to
main. During busy hours some merges are never deployed on their own, because a later merge overtakes them while they wait for the Deploy stage. Compliance now requires every merge to be deployed, in order. What should the developer change?- A. Set the pipeline's execution mode to
QUEUED(V2 pipeline type). - B. Set the pipeline's execution mode to
PARALLEL(V2 pipeline type). - C. Disable the inbound transition of the Deploy stage during busy hours.
- D. Add a manual approval action before the Deploy stage.
- A. Set the pipeline's execution mode to
-
A V2 pipeline with a GitHub source through CodeConnections must start only when a tag matching
v*is pushed, and the Production stage must be skipped automatically unless the pipeline variableDEPLOY_PRODequalsyes. Which TWO configurations meet these requirements? (Select TWO.)- A. A trigger with a
pushfilter whosetagsincludescontainsv*. - B. An entry condition on the Production stage with a
VariableCheckrule and the resultSKIP. - C. An EventBridge rule on
aws.codecommittag events that targets the pipeline. - D. An on-success condition on the Build stage with the result
ROLLBACK. - E. A
BranchNamevalue ofv*in the source action configuration.
- A. A trigger with a
Answers
- A. QUEUED mode processes executions one by one in arrival order without superseding them. B runs executions independently and out of order; C holds executions back, but they can still be superseded; D adds a manual gate and doesn't stop supersession.
- A, B. A tag filter on a connection trigger starts the pipeline only for matching tags, and an entry condition with
VariableCheckandSKIPskips the stage. C applies to CodeCommit, not GitHub; D rolls a stage back instead of skipping one; E takes a single branch name, not a tag pattern.
12. Manual approvals and pipeline monitoring
Concept
- A manual approval action pauses an execution until someone with permission approves or rejects it: code review sign-off, manual QA or change management before production.
- Monitoring answers two questions: "tell me when something happens" (EventBridge, notification rules, SNS) and "what failed and what can I do about it" (execution history, retry, rollback, stop, transitions, CloudTrail).
Exam facts
- Approval options, all optional: an SNS topic in the pipeline's Region (
NotificationArn), a URL to review (ExternalEntityLink), comments for the approver (CustomData). The pipeline's service role needs permission to publish to the topic. - Approving or rejecting needs
codepipeline:PutApprovalResultonarn:aws:codepipeline:<region>:<account>:<pipeline>/<stage>/<action>, plusGetPipeline,GetPipelineStateandGetPipelineExecutionto see it (ListPipelinesonly for the console list); AWS managed policyAWSCodePipelineApproverAccess. - ⚠️ Changed: an unanswered approval fails after the account default of 7 days, and the per-action
timeoutInMinutessetting (approval actions only) changes that window to anything from 5 to 86,400 minutes (60 days). Older material may say the 7-day timeout is fixed. - A rejected or timed-out approval counts as a failed action; the stage stays locked while the approval waits; approvals are free under V2 pricing.
- EventBridge events from
aws.codepipelinewith the detail-typesCodePipeline Pipeline Execution State Change,CodePipeline Stage Execution State ChangeandCodePipeline Action Execution State Change; pipeline statesSTARTED,SUCCEEDED,FAILED,CANCELED,SUPERSEDED,STOPPING,STOPPED,RESUMED; action states includeABANDONED; filter ondetail.stateanddetail.type.category(for example failedApprovalorDeployactions). Delivery is at least once. - Notification rules (Developer Tools console) send the same events to SNS or Amazon Q Developer in chat applications (Slack, Microsoft Teams) without writing event patterns.
- CloudTrail records CodePipeline API calls: who approved, who started, stopped or retried an execution.
- Disabling a stage's inbound transition holds executions in front of it (they can still be superseded); enabling it again lets the latest one in.
- Troubleshooting checklist: permission errors in an action → the pipeline's service role (or the action's cross-account role); a connection source fails → missing
codeconnections:UseConnectionorcodestar-connections:UseConnection(§13); CodeBuild fails right after a full-clone source → the CodeBuild role lacks connection orcodecommit:GitPullpermission; a cross-account action can't read artifacts → the KMS key policy or bucket policy (§10).
Developer angle
# Find the token of the pending approval, then approve it
aws codepipeline get-pipeline-state --name orders-pipeline \
--query 'stageStates[?stageName==`Approve`].actionStates[0].latestExecution.token' --output text
aws codepipeline put-approval-result --pipeline-name orders-pipeline --stage-name Approve --action-name ProdGate \
--result summary="QA signed off",status=Approved --token 1a2c3b4d-EXAMPLE
# EventBridge rule: alert on failed deploy or approval actions
aws events put-rule --name orders-pipeline-failures --event-pattern '{
"source": ["aws.codepipeline"], "detail-type": ["CodePipeline Action Execution State Change"],
"detail": { "pipeline": ["orders-pipeline"], "state": ["FAILED"], "type": { "category": ["Deploy", "Approval"] } } }'
aws events put-targets --rule orders-pipeline-failures --targets Id=1,Arn=arn:aws:sns:eu-west-1:111122223333:orders-oncall
Approval action with a two-day window (the approver's least-privilege policy is in Exam facts and in practice question 1):
{ "name": "ProdGate", "runOrder": 1, "timeoutInMinutes": 2880,
"actionTypeId": { "category": "Approval", "owner": "AWS", "provider": "Manual", "version": "1" },
"configuration": { "NotificationArn": "arn:aws:sns:eu-west-1:111122223333:orders-approvals",
"ExternalEntityLink": "https://staging.orders.example.com",
"CustomData": "Check the checkout flow before approving." } }
Traps
- Trap: "Give approvers
AWSCodePipeline_FullAccessso they can approve." → Reality:codepipeline:PutApprovalResulton the approval action's ARN (orAWSCodePipelineApproverAccess) is enough. - Trap: "Approvals wait forever." → Reality: the default is 7 days, then the action fails; set
timeoutInMinutes(5 minutes to 60 days) for another window. - Trap: "Send approval notifications to an SNS topic in another Region." → Reality: the topic must be in the pipeline's Region.
- Trap: "CloudTrail is how you alert on failed stages." → Reality: use EventBridge rules or notification rules; CloudTrail is the audit record of API calls.
- Trap: "A disabled transition protects waiting executions from being skipped." → Reality: waiting executions can still be superseded.
Practice questions
-
A release manager must be able to approve or reject only the
ProdGateapproval action in theorders-pipelinepipeline, and nothing else. Which policy grants the least privilege?- A.
codepipeline:*onarn:aws:codepipeline:eu-west-1:111122223333:orders-pipeline. - B.
codepipeline:PutApprovalResultonarn:aws:codepipeline:eu-west-1:111122223333:orders-pipeline/Approve/ProdGate, plus read access to that pipeline's state. - C. The
AWSCodePipeline_FullAccessmanaged policy. - D.
codepipeline:UpdatePipelineon the pipeline, so that the manager can remove the approval action once it is approved.
- A.
-
A team wants an alert in its on-call SNS topic whenever a deploy action or an approval fails in any of its pipelines, without polling and with the least operational overhead. Which TWO steps meet this requirement? (Select TWO.)
- A. Create an EventBridge rule with source
aws.codepipeline, detail-typeCodePipeline Action Execution State Change, stateFAILEDand categoryDeployorApproval. - B. Add the on-call SNS topic as the rule's target, with permission for EventBridge to publish to it.
- C. Create a CloudTrail trail and an Athena query that searches for
PutApprovalResultcalls every hour. - D. Add a Lambda invoke action at the end of every pipeline that checks the earlier stages.
- E. Raise each approval action's
timeoutInMinutesso that approvals never fail.
- A. Create an EventBridge rule with source
Answers
- B.
PutApprovalResultscoped to the single approval action's ARN, plus read access to view it, is the least privilege. A and C allow every pipeline operation; D lets the manager change the pipeline instead of approving it. - A, B. An EventBridge rule on action state changes, filtered by state and category, with SNS as the target alerts in near real time with no code. C is delayed and only sees API calls; D never runs after a failure because the pipeline stops before it; E hides failures instead of reporting them.
13. Connections to GitHub Bitbucket and GitLab
Concept
- AWS CodeConnections (formerly AWS CodeStar Connections) stores an authorized link between your AWS account and a third-party Git provider. CodePipeline, CodeBuild, CloudFormation Git sync and other services use the connection's ARN instead of personal tokens kept in secrets or parameters.
- A connection is created in AWS and then completed through a browser handshake that installs the provider's AWS Connector app; until then it stays
PENDING. Self-managed providers (GitHub Enterprise Server, GitLab self-managed) also need a host resource.
Exam facts
- ⚠️ Changed: renamed AWS CodeConnections on 2024-03-29, with the
codeconnectionsAPI, CLI and IAM prefix (API version 2023-12-01); resources created under thecodestar-connectionsprefix are still supported, new resources getcodeconnectionsARNs (the console has done so since 2024-07-01), and the prefix in a policy's resource ARN must match the connection's. Older material may say AWS CodeStar Connections andcodestar-connectionsonly. - Provider types:
Bitbucket(Bitbucket Cloud only, not Bitbucket Server),GitHub(GitHub and GitHub Enterprise Cloud),GitHubEnterpriseServer,GitLab(GitLab.com),GitLabSelfManaged, andAzureDevOps(added 2025-08-05; ⚠️ unverified for CodePipeline, whose connection source action documents only the other five). - A connection created with the CLI, an SDK or CloudFormation stays
PENDINGuntil someone completes the handshake in the console; a pipeline that uses a pending connection is never triggered. - Creating a GitHub connection for a repository in an organization requires the organization owner; GitLab needs the Owner role on the repository. One connection covers every repository the installed app can reach for that provider account.
- ⚠️ Changed: the CodePipeline source action keeps the provider name
CodeStarSourceConnection(category Source, owner AWS, version 1;ConnectionArn,FullRepositoryIdsuch asacme/ordersin exact case,BranchName, optionalOutputArtifactFormatandDetectChanges, defaulttrue), and the pipeline's service role needs bothcodeconnections:UseConnectionandcodestar-connections:UseConnectionon the connection. Older material may show onlycodestar-connections:UseConnection. OutputArtifactFormat:CODE_ZIP(default; a ZIP of the commit without Git history) orCODEBUILD_CLONE_REF(full clone: a reference that only a downstream CodeBuild action can use; the CodeBuild service role then needs permission to use the connection).- Output variables:
CommitId,BranchName,CommitMessage,AuthorDate,ConnectionArn,FullRepositoryName. - IAM:
PassConnectionto put a connection ARN into a pipeline definition, granted under both prefixes: the connections guide namescodeconnections:PassConnection, while CodePipeline'sCreatePipelineandUpdatePipelineare authorized withcodestar-connections:PassConnection(condition keyscodeconnections:PassedToServiceandcodestar-connections:PassedToService, for examplecodepipeline.amazonaws.com);codeconnections:UseConnectionfor the service that uses it (condition keys such ascodeconnections:FullRepositoryId,codeconnections:BranchName,codeconnections:ProviderAction,codeconnections:ProviderPermissionsRequired);CreateConnectionsupportscodeconnections:ProviderType. - Connections can be shared with other accounts through AWS RAM (since 2025-03-06).
- The connection source action is missing from about a dozen Regions (for example Asia Pacific (Hong Kong), Middle East (Bahrain), Africa (Cape Town) and AWS GovCloud (US-West)); Europe (Milan) needs a Region-specific app.
- The GitHub (via OAuth app) source action (owner
ThirdParty, providerGitHub, version 1, withOAuthTokenand a webhook) still works in existing pipelines but isn't recommended; move to the GitHub (via GitHub App) connection action. - CodeBuild sources and webhooks for GitHub, GitLab and Bitbucket can authenticate through a connection (
authtypeCODECONNECTIONS) instead of stored tokens.
Developer angle
aws codeconnections create-connection --provider-type GitHub --connection-name acme-github
# returns ConnectionArn; the status stays PENDING until the console handshake is done
aws codeconnections get-connection \
--connection-arn arn:aws:codeconnections:eu-west-1:111122223333:connection/0a1b2c3d-EXAMPLE \
--query Connection.ConnectionStatus
Statement for the pipeline's service role (both prefixes, as AWS requires):
{ "Effect": "Allow",
"Action": ["codeconnections:UseConnection", "codestar-connections:UseConnection"],
"Resource": "arn:aws:codeconnections:eu-west-1:111122223333:connection/0a1b2c3d-EXAMPLE" }
- People who create or edit pipelines need
PassConnectionon the connection under both prefixes (codeconnections:PassConnectionandcodestar-connections:PassConnection), ideally each limited with itsPassedToServicecondition key =codepipeline.amazonaws.com. - In CloudFormation the resource type is still
AWS::CodeStarConnections::Connection; itsConnectionStatusstarts asPENDING(pipeline templates: seenotes/cloudformation-guide.md).
Traps
- Trap: "The pipeline that CloudFormation created with a new connection runs immediately." → Reality: the connection is
PENDINGuntil the console handshake; nothing triggers. - Trap: "Grant only
codestar-connections:UseConnectionto the service role." → Reality: grant both prefixes; calls can be authorized under either one. - Trap: "Store a GitHub personal access token in Secrets Manager for the source action." → Reality: that's the legacy OAuth approach; connections need no stored token.
- Trap: "Use full clone so that the CodeDeploy action gets the Git history." → Reality: only CodeBuild can consume a
CODEBUILD_CLONE_REFartifact. - Trap: "Create one connection per repository." → Reality: one connection per provider account covers its repositories.
- Trap: "Connect the pipeline to an on-premises Bitbucket Server." → Reality: the Bitbucket provider supports Bitbucket Cloud only.
Practice questions
-
A developer creates a connection with
aws codeconnections create-connection --provider-type GitHuband references its ARN in a new pipeline deployed by CloudFormation. Pushes to the repository never start the pipeline. What should the developer do?- A. Add
codestar-connections:UseConnectionto the developer's own IAM permissions. - B. Complete the pending connection's handshake in the Developer Tools console so that the AWS Connector app gets installed.
- C. Create a GitHub webhook that calls the pipeline's ARN directly.
- D. Set
PollForSourceChangestotruein the source action.
- A. Add
-
A V2 pipeline uses a GitHub source through a connection with
OutputArtifactFormatset toCODEBUILD_CLONE_REF, because the build needs Git history. The source action succeeds, but the CodeBuild action fails while cloning. Which TWO statements are correct? (Select TWO.)- A. The CodeBuild project's service role needs permission to use the connection.
- B. Only CodeBuild actions can consume this artifact; a deploy action can't use it directly.
- C. The pipeline must be switched to the V1 type to support full clones.
- D. The artifact store must be encrypted with a customer managed key for full clones.
- E. The connection must be recreated under the
codestar-connectionsprefix.
Answers
- B. Connections created with the CLI or CloudFormation stay
PENDINGuntil the browser handshake installs the provider app. A changes the developer's permissions, not the connection's state; C isn't how connection sources work (the connection manages the webhook); D isn't a setting of connection sources and wouldn't complete the connection. - A, B. A full-clone artifact is a Git reference that CodeBuild resolves with its own role, so that role needs permission to use the connection, and no other action type can consume it. C, D and E aren't requirements for full clones.
14. CodeArtifact
Concept
- CodeArtifact is a managed package repository: build tools and developers fetch dependencies from it and publish internal packages to it, instead of calling public registries directly or running their own artifact server.
- A domain holds the packages (each asset stored once, encrypted with one KMS key) and carries organization-wide policy; repositories in the domain are what clients talk to; an upstream relationship makes one repository's packages visible through another; an external connection lets one repository fetch from a public registry on demand.
Exam facts
- ⚠️ Changed: package formats are Cargo, generic, Maven, npm, NuGet, PyPI, Ruby and Swift;
aws codeartifact loginconfiguresdotnet,npm,nuget,pip,swiftandtwine(Maven, Gradle and other tools useget-authorization-token). Older material may list only Maven, Gradle, npm, yarn, twine, pip and NuGet. - Repositories are polyglot; there is no limit on the number or total size of packages; packages can't be made public.
- Upstreams: up to 10 direct upstream repositories per repository; up to 25 repositories searched when a package is resolved.
- External connections: one per repository (
public:npmjs,public:pypi,public:maven-central,public:nuget-org,public:ruby-gems-org,public:crates-io, and Maven repositories for Google Android, Gradle plugins, CommonsWare and Clojars). Recommended layout: one repository per public registry in the domain (the console createsnpm-store,pypi-storeand similar), used as an upstream by the team repositories, so each public package is fetched once. - Package groups apply origin controls (block or allow publishing and upstream ingestion) to packages that match a pattern, guarding against dependency substitution attacks.
- Tokens:
GetAuthorizationTokenreturns a token valid 12 hours by default, configurable from 15 minutes to 12 hours (--duration-seconds900–43,200);0while assuming a role makes it expire with the role session; otherwise its lifetime is independent of the role session. Calling it needs bothcodeartifact:GetAuthorizationTokenandsts:GetServiceBearerToken; the root user can't call it. To revoke tokens, deny the principal in IAM. - Resource policies: optional domain and repository policies in a single account; for cross-account access the other account needs both a resource policy that allows it and its own identity policy.
codeartifact:ReadFromRepositoryapplies to the whole repository — read access can't be limited to some packages.codeartifact:PublishPackageVersionis granted on package ARNs (arn:aws:codeartifact:<region>:<account>:package/<domain>/<repo>/<format>/<namespace>/<name>); Maven publishing also needsPutPackageMetadata, NuGet publishingReadFromRepository. Cross-account readers getGetAuthorizationTokenthrough the domain policy. - Private builds (for example CodeBuild in a VPC without internet access) need the interface endpoints
com.amazonaws.<region>.codeartifact.apiandcom.amazonaws.<region>.codeartifact.repositories(private DNS on the latter) plus the S3 gateway endpoint for package assets (not needed for PyPI or Swift; network details: seenotes/vpc-guide.md). - Package version changes reach EventBridge (source
aws.codeartifact); a rule on them can start the pipeline of every application that consumes a patched library. - Quotas: 10 domains per account and 1,000 repositories per domain (adjustable); 5 GB per asset (adjustable); 40
GetAuthorizationTokenrequests per second.
Developer angle
# Developer laptop: point npm at the team repository for 1 hour
aws codeartifact login --tool npm --domain acme --domain-owner 111122223333 --repository team-js --duration-seconds 3600
# Tools without login support (Maven, Gradle): export the token
export CODEARTIFACT_AUTH_TOKEN=$(aws codeartifact get-authorization-token \
--domain acme --domain-owner 111122223333 --query authorizationToken --output text)
# Domain layout: a store repository with the public connection, used as an upstream
aws codeartifact create-repository --domain acme --repository npm-store
aws codeartifact associate-external-connection --domain acme --repository npm-store --external-connection public:npmjs
aws codeartifact update-repository --domain acme --repository team-js --upstreams repositoryName=npm-store
- In a buildspec, run
aws codeartifact login --tool pip …in theinstallphase beforepip install; the CodeBuild service role then needs the same two token permissions.
Repository policy that lets another account read (it also needs a domain policy granting codeartifact:GetAuthorizationToken):
{ "Version": "2012-10-17",
"Statement": [{ "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::444455556666:root" },
"Action": ["codeartifact:DescribePackageVersion", "codeartifact:DescribeRepository",
"codeartifact:GetRepositoryEndpoint", "codeartifact:ListPackages",
"codeartifact:ListPackageVersions", "codeartifact:ReadFromRepository"],
"Resource": "*" }] }
Traps
- Trap: "Grant
codeartifact:GetAuthorizationTokenand the build can log in." → Reality:sts:GetServiceBearerTokenis required too. - Trap: "The token expires with the assumed role's 15-minute session." → Reality: it lasts 12 hours by default unless you pass
--duration-seconds 0. - Trap: "Give the partner read access to a single package." → Reality: read permission is granted per repository, never per package; put the shared packages in a repository of their own.
- Trap: "Add npmjs and PyPI external connections to the same repository." → Reality: one external connection per repository; use store repositories as upstreams.
- Trap: "One VPC endpoint is enough for CodeArtifact." → Reality: you need the
apiandrepositoriesendpoints plus S3 (S3 isn't needed for PyPI or Swift packages). - Trap: "Publish the SDK to the public through CodeArtifact." → Reality: CodeArtifact packages can't be made public.
Practice questions
-
A CodeBuild project's role has
codeartifact:GetAuthorizationTokenandcodeartifact:ReadFromRepositoryon the team's domain and repository, butaws codeartifact loginfails with an access-denied error in theinstallphase. What is missing?- A.
sts:GetServiceBearerTokenin the service role's identity policy. - B.
codeartifact:PublishPackageVersionon the repository's packages. - C. An external connection from the repository to
public:pypi. - D. A
--duration-seconds 0argument on thelogincommand.
- A.
-
A company wants every team repository in its CodeArtifact domain to resolve public npm and PyPI packages, to fetch each public package from the internet only once for the whole domain, and to keep each team's own packages separate. Which TWO actions meet these requirements? (Select TWO.)
- A. Create one repository with an external connection to
public:npmjsand another with an external connection topublic:pypi. - B. Add those two repositories as upstream repositories of each team repository.
- C. Add both external connections to every team repository.
- D. Create a separate domain for each team, each with its own external connections.
- E. Grant each team
codeartifact:ReadFromRepositoryon only the public packages it needs.
- A. Create one repository with an external connection to
Answers
- A. Getting a CodeArtifact token requires both
codeartifact:GetAuthorizationTokenandsts:GetServiceBearerToken. B is for publishing; C changes where packages come from, not authentication; D only changes the token lifetime. - A, B. One store repository per public registry, used as an upstream by the team repositories, caches each public package once for the domain while team packages stay in their own repositories. C fails because a repository can have only one external connection (and it would cache per repository); D duplicates storage across domains; E is impossible because read access can't be limited to some packages.
Quick decision rules
Toolchain and CodeCommit (§1–§2)
- If you see "set up a CI/CD project from a template with CodeStar", think CodeStar is shut down: build the pipeline directly or as infrastructure as code.
- If you see "find the most CPU-expensive methods in a running application", think CodeGuru Profiler.
- If you see federated, SSO or role-based developers cloning CodeCommit, think git-remote-codecommit (
codecommit::URLs). - If you see "block pushes to main but allow pull requests", think an IAM
Denywithcodecommit:Referencesplus theNullcondition. - If you see another account needing CodeCommit access, think a role in the repository account and
sts:AssumeRole, never shared keys. - If you see "notify or start something on every push", think CodeCommit triggers (SNS or Lambda in the same Region) or EventBridge.
- If you see builds stuck in
QUEUEDwith "Cannot have more than X active builds", think a Service Quotas increase for that compute type. - If you see "build a Docker image in CodeBuild", think EC2 compute with
privilegedMode: true, never Lambda compute. - If you see the fastest start-up for short builds that need no Docker, think Lambda compute.
- If you see a buildspec in a subfolder or under another name, think the project's
buildspecsetting or--buildspec-override. - If you see a secret needed during a build, think
env/secrets-managerorenv/parameter-storeplus the matching read permission on the service role. - If you see dependencies downloaded on every build across hosts, think S3 cache; frequent builds with big images, think local Docker layer cache.
- If you see "alert on every failed build", think an EventBridge rule on
CodeBuild Build State ChangewithFAILED; "alert when failures pass a threshold", think a CloudWatch alarm onFailedBuilds. - If you see test results needed in the console, think the
reportssection (JUnit XML by default). - If you see a value needed by a later pipeline action, think
exported-variablesand#{Namespace.VAR}.
- If you see "at least N instances must stay in service", think a custom configuration with minimum healthy hosts.
- If you see on-premises servers, think in-place only, the agent, and registration with an IAM session ARN.
- If you see
DownloadBundleaccess denied, think the instance profile's S3 permissions. - If you see
IAM_ROLE_PERMISSIONSwhile copying an Auto Scaling group with a launch template, thinkec2:RunInstances,ec2:CreateTagsandiam:PassRoleon the service role. - If you see
ApplicationStopfailing because of an old script, think--ignore-application-stop-failures. - If you see "test the new Lambda version before traffic moves", think a
BeforeAllowTraffichook that callsPutLifecycleEventHookExecutionStatus. - If you see ECS testing on a separate port before production, think a test listener and
AfterAllowTestTraffic. - If you see CodeDeploy canary or linear shifting for ECS behind an NLB, think an ALB instead (with an NLB only
ECSAllAtOnceworks). - If you see "roll back automatically when an alarm fires", think deployment group alarms plus
DEPLOYMENT_STOP_ON_ALARM. - If you see
HEALTH_CONSTRAINTS_INVALID, think a minimum-healthy-hosts value that can never be met.
CodePipeline and connections (§10–§13)
- If you see a cross-account deploy that can't read artifacts, think a customer managed KMS key, a bucket policy and a cross-account
roleArn. - If you see a cross-Region action, think
artifactStoreswith a bucket per Region. - If you see duplicate executions after adding an EventBridge rule, think
PollForSourceChanges: false. - If you see "start only for Git tags, branches or file paths", think V2 triggers on a connection source.
- If you see "every change must deploy, in order", think QUEUED mode; independent feature-branch runs, think PARALLEL.
- If you see "skip a stage unless a variable is set", think an entry condition with
VariableCheckandSKIP. - If you see the minimal approver permission, think
codepipeline:PutApprovalResulton the approval action's ARN. - If you see alerts on failed stages or actions, think EventBridge rules on
aws.codepipelinestate-change events. - If you see a new connection that never triggers, think a
PENDINGconnection: finish the handshake in the console. - If you see a CodeBuild action that needs Git history, think
CODEBUILD_CLONE_REF(full clone) plus connection permission on the CodeBuild role.
CodeArtifact (§14)
- If you see
codeartifact loginaccess denied, thinksts:GetServiceBearerToken. - If you see public packages that should be fetched once for the whole organization, think store repositories with external connections used as upstreams.
- If you see CodeBuild in a private subnet failing to reach CodeArtifact, think the
apiandrepositoriesinterface endpoints plus S3 (except for PyPI and Swift).
Changed vs older material
Learn the Current column; older practice material may still show the Older material may say value. After your confirmation, these rows are kept with their verification dates in notes/current-facts.md. Verified unchanged: CodeGuru Profiler is still active (all JVM languages, Python 3.6+) and is on none of the AWS lifecycle maintenance, sunset or shutdown lists.
| Topic | Older material may say | Current (verified 2026-10-12) | Source |
|---|---|---|---|
| §1 · CodeStar | A current service for project templates and dashboards | Full shutdown, end of support 2024-07-25; repositories and pipelines it created keep working | AWS docs |
| §1 · Cloud9 | A browser IDE available to any account | Closed to new customers since 2024-07-25 (maintenance); IDE Toolkits or CloudShell instead | AWS docs |
| §1 · CodeCatalyst | Open to new customers as the CodeStar successor | Closed to new customers since 2025-11-07; existing customers can't create new spaces | AWS docs |
| §1 · CodeGuru Reviewer | ML code reviews available for any repository | Maintenance: no new repository associations since 2025-11-07; Amazon Q Developer code reviews or Amazon Inspector code security instead | AWS docs |
| §1 · Notification rule chat targets | AWS Chatbot clients | Amazon Q Developer in chat applications (renamed 2025-02-19); APIs, IAM permissions and console URLs unchanged | AWS docs |
| §1, §13 · Connections service name | AWS CodeStar Connections (codestar-connections) |
AWS CodeConnections since 2024-03-29 (codeconnections); old-prefix resources still supported; the console has created codeconnections ARNs since 2024-07-01 |
AWS docs |
| §2 · CodeCommit availability | Closed to new customers since 2024-07-25 | Generally available and open to new customers again since 2025-11-24 | AWS blog |
| §2 · CodeCommit with temporary credentials | HTTPS users pick Git credentials or the AWS CLI credential helper | git-remote-codecommit is the recommended method for federated, SSO and role-based access | AWS docs |
| §3 · CodeBuild sources | CodeCommit, S3, Bitbucket, GitHub | Also GitHub Enterprise Server, GitLab, GitLab self-managed, CodePipeline and no source | AWS docs |
| §3 · CodeBuild build queue | No build queue | Builds wait in QUEUED at the per-compute-type concurrency quota; queued timeout 5–480 minutes |
AWS docs |
| §3 · CodeBuild billing | Charged per minute | On-demand EC2 per minute (rounded up); Lambda compute per second; reserved capacity per minute with a 60-minute minimum | AWS pricing |
| §3 · CodeBuild maximum build timeout | 8 hours | 36 hours (2,160 minutes) since 2024-05-01; default 60 minutes | AWS docs |
| §6 · CodeDeploy agent runtime | The agent requires Ruby | Agent 2.x (2026-07-15) is a Rust binary without Ruby; opt-in through AWSCodeDeployAgentV2; 1.8.x is the minimum supported |
AWS docs |
| §8 · ECS predefined deployment configurations | ECSLinear10PercentEvery3Minutes, ECSLinear10PercentEvery10Minutes, ECSCanary10Percent5Minutes, ECSCanary10Percent30Minutes |
ECSLinear10PercentEvery1Minutes, ECSLinear10PercentEvery3Minutes, ECSCanary10Percent5Minutes, ECSCanary10Percent15Minutes, ECSAllAtOnce |
AWS docs |
| §8 · Load balancer for CodeDeploy ECS deployments | An Application Load Balancer is required | ALB or NLB (ALB recommended; with an NLB only ECSAllAtOnce) |
AWS docs |
| §8 · Blue/green on ECS | Only possible through CodeDeploy | ECS built-in blue/green since 2025-07-17 and linear/canary since 2025-10-30 (deploymentController ECS) |
What's New |
| §10 · CodePipeline action providers | Sources CodeCommit, ECR, S3, Bitbucket, GitHub; a short deploy list | Connection sources for Bitbucket Cloud, GitHub, GitHub Enterprise Server, GitLab.com, GitLab self-managed; GitHub OAuth action not recommended; EC2, EKS and Lambda deploy actions; Commands | AWS docs |
| §10 · Source change detection | Pipelines poll their sources | Event-based (EventBridge, connections); polling switched off after 30 days without executions; at most 300 polling pipelines per Region | AWS docs |
| §11 · CodePipeline pricing | $1 per active pipeline per month | V1 $1.00 per active pipeline per month; V2 $0.002 per action execution minute with 100 free minutes per month | AWS pricing |
| §12 · Manual approval timeout | Fixed at 7 days | Account default 7 days; per-action timeoutInMinutes 5–86,400 (60 days) |
AWS docs |
| §13 · Connections source action permission | codestar-connections:UseConnection |
Both codeconnections:UseConnection and codestar-connections:UseConnection |
AWS docs |
| §14 · CodeArtifact formats | Maven, Gradle, npm, yarn, twine, pip, NuGet | Cargo, generic, Maven, npm, NuGet, PyPI, Ruby and Swift packages | AWS docs |