AWS CodeBuild, CodePipeline and CodeDeploy
Build a .NET 10 image in CodeBuild with a buildspec, orchestrate it with a CodePipeline V2 pipeline that has a manual approval, understand where CodeDeploy fits, and decide when AWS-native tooling beats GitHub Actions.
Assumes: .NET 10 LTS · AWS CodeBuild · AWS CodePipeline V2 · AWS CodeDeploy · Amazon.CDK.Lib 2.277.0 · Terraform AWS provider v6 · AWS CLI v2 · Region us-east-1. Verified against official sources on 2026-11-18.
Learning objectives
By the end of this lesson you can:
- Read and write a CodeBuild
buildspec.yml: phases, environment variables, reports, artefacts and cache. - Explain what CodePipeline adds over CodeBuild alone: stages, actions, artefact hand-off, approvals and execution modes.
- Describe the differences between CodePipeline V1 and V2 pipelines, including how V2 is billed.
- Connect a GitHub repository to a pipeline with AWS CodeConnections instead of a stored token.
- Explain where AWS CodeDeploy fits for ECS, Lambda and EC2, and what an AppSpec file does.
- Define the same pipeline in CDK (C#) or Terraform, with a least-privilege service role per component.
- Decide, with reasons a risk committee would accept, between GitHub Actions and the AWS-native toolchain.
Prerequisites
- CI/CD concepts on AWS
- GitHub Actions with OIDC, so you can compare the two trust models
- Module 3: .NET on AWS — containers, ECR and ECS on Fargate
- Tools: AWS CLI v2 with the
learn-sandboxprofile, Docker, a GitHub repository you own
Why this matters in banking
Some banks cannot, or will not, run production deployments from a third-party SaaS. The risk team's reasons are reasonable: the build service becomes a critical supplier, the runner executes code on infrastructure the bank does not control, and an outage at the vendor stops releases. Those banks often keep source in GitHub (developers expect it) but run build and deploy inside their own AWS accounts with CodeBuild and CodePipeline, where service roles, VPC access, CloudTrail and KMS encryption are the same controls the rest of the estate uses.
Other banks go the opposite way: GitHub Actions for everything, because the pipeline is the same on laptops, branches and releases. Neither choice is wrong. What matters is that you can explain both, because a DevOps engineer at a bank is asked to defend the choice, and because the DOP-C02 and DVA-C03 exams test the AWS-native services directly.
The idea in plain language
Three services, three jobs:
| Service | Job in one sentence | .NET analogy |
|---|---|---|
| CodeBuild | Runs a build in a fresh container and then throws the container away | One Azure Pipelines agent job, with the agent also created and deleted for you |
| CodePipeline | Chains actions (source, build, test, approve, deploy) in stages and passes artefacts between them | The stage and gate structure of an Azure Pipelines multi-stage YAML or a classic release pipeline |
| CodeDeploy | Rolls a new version out onto compute (EC2, on-premises, ECS, Lambda) in a controlled way, with hooks and rollback | The deployment step of a release pipeline, plus the slot-swap logic of App Service |
Analogy: a branch's morning cash run. CodeBuild is the clerk who counts and seals one bag, then goes home. CodePipeline is the supervisor's checklist: bag sealed, second signature obtained, van dispatched. CodeDeploy is the driver who delivers to each branch in order and turns back if the first branch reports a problem.
You do not need all three. A common modern setup uses CodePipeline and CodeBuild, with ECS or CloudFormation doing the rollout itself, and keeps CodeDeploy only for Lambda traffic shifting or EC2 fleets.
What problem the AWS services solve
| Service | What it gives you | Limits and sharp edges |
|---|---|---|
| CodeBuild | Managed build containers; per-build isolation; IAM service role per project; logs in CloudWatch; test and coverage reports; VPC access to private resources; no servers to patch | You pay per build minute; the build image is yours to keep patched; privileged mode is required for Docker builds, which weakens isolation, so scope those projects tightly |
| CodePipeline | Visual and auditable stage history; approvals; cross-account deploy; triggers from GitHub, S3, ECR and more; integrates with CloudFormation, ECS, CodeDeploy, Lambda | Less flexible than a general workflow engine; YAML is not the authoring format (the definition is JSON/IaC); no matrix builds or marketplace of reusable steps |
| CodeDeploy | Deployment groups, traffic shifting configurations, lifecycle hooks, alarm-based rollback for ECS blue/green and Lambda | Another service and another IAM role to understand; the EC2/on-premises mode needs an agent on every instance |
An honest comparison with GitHub Actions: Actions has a larger ecosystem, matrix builds, and the same workflow on pull requests and releases; the AWS-native tools have tighter AWS integration, no third-party runners, and AWS-managed audit trails. The trade-off is covered in the decision section below.
Microsoft / Azure comparison
| You know (Microsoft/Azure) | AWS equivalent | What's different |
|---|---|---|
Azure Pipelines YAML steps: | CodeBuild buildspec.yml phases: | The buildspec describes one build, not the whole pipeline. Stages and approvals live in CodePipeline |
| Microsoft-hosted agent pool | CodeBuild compute (managed image) | A new container per build; you pick the image and size, and pay per minute |
| Self-hosted agent in a VNet | CodeBuild project with VPC configuration | No agent software to maintain; the project's network interface sits in your subnets |
| Multi-stage pipeline with environments and approvals | CodePipeline stages with a manual approval action | Approval is an action, and it records approver, comment and time |
| Release pipeline with deployment groups | CodeDeploy application and deployment group | CodeDeploy owns traffic shifting and rollback logic |
Pipeline artifacts / PublishPipelineArtifact | S3 artefact store encrypted with KMS | Artefact hand-off goes through an S3 bucket the pipeline owns |
| Service connection | CodeConnections connection (GitHub, GitLab, Bitbucket) | The connection is a first-class AWS resource you authorise once in the console |
| Test results tab (VSTest, JUnit publish) | CodeBuild report groups | JUnit XML, Cucumber and others; keep history per group |
| Azure DevOps Server (on-premises) | There is no direct equivalent; run CodeBuild in a VPC | Build workers run in AWS, not in the datacentre |
Source control note: CodeCommit versus GitHub
CodeCommit stopped accepting new customers in July 2024, and this curriculum's module overview records that AWS announced it back to general availability on 24 November 2025 ⚠ VERIFY on the AWS service page before relying on either state. Treat that as a reason to be cautious rather than a recommendation: many AWS pages still carry the older notice, and a bank that chose CodeCommit once may have to defend that choice in a vendor-risk review. This lesson uses GitHub as the source and CodeConnections to connect it. The same pipeline works unchanged with a CodeCommit source if your organisation already uses it.
Architecture
Security-boundary view
CodeBuild, CodePipeline and the deploy actions each assume a different role. That is the equivalent of the separate OIDC roles in the GitHub design. If you give the build role deploy permissions "to keep it simple", a malicious pull request that changes the buildspec can deploy.
CodeBuild in depth
The buildspec
A buildspec is YAML at the repository root (default name buildspec.yml). Its top-level keys:
| Key | Purpose |
|---|---|
version | Always 0.2 for new files |
env | variables (plain text), parameter-store, secrets-manager, exported-variables (values to hand to later pipeline actions), shell |
phases | install, pre_build, build, post_build, each with commands; finally blocks run even on failure |
reports | Test reports: JUnit XML and similar, grouped for history |
artifacts | Files to upload as the build output |
cache | Paths to cache between builds (for example the NuGet package folder) |
Behaviour to remember: a failing command stops the phase and fails the build, and cleanup that must always run belongs in a finally block of the phase ⚠ VERIFY whether post_build still runs after a failed build phase for your buildspec version, because that decides whether a push step can run after failed tests. In version 0.2 every command of a build runs in the same shell instance, so variables set in one commands entry are visible in later ones; that is why the lab sets COMMIT in pre_build and uses it in build ⚠ VERIFY for your env.shell setting. The lab avoids the question by gating the push with set -euo pipefail and by ordering tests before any push.
The lab's buildspec.yml, annotated:
version: 0.2
env:
shell: bash
variables:
DOTNET_IMAGE: "mcr.microsoft.com/dotnet/sdk:10.0"
exported-variables:
- IMAGE_URI # handed to later pipeline actions as a variable
phases:
pre_build:
commands:
- set -euo pipefail
- COMMIT="${CODEBUILD_RESOLVED_SOURCE_VERSION}"
# Log in to ECR with the build role's temporary credentials (no stored keys).
- aws ecr get-login-password --region "$AWS_REGION" | docker login --username AWS --password-stdin "$ECR_REGISTRY"
build:
commands:
# Run restore, build and test inside the official SDK container, exactly as on a laptop.
- >
docker run --rm -v "$PWD:/src" -w /src -e CI=true "$DOTNET_IMAGE"
sh -c "dotnet test --solution DeliveryPipeline.slnx -c Release --report-junit --results-directory /src/artifacts/test-results"
- docker build --build-arg VERSION="$APP_VERSION" --build-arg GIT_SHA="$COMMIT" -t "$ECR_REGISTRY/$ECR_REPOSITORY:$GIT_TAG" .
post_build:
commands:
- docker push "$ECR_REGISTRY/$ECR_REPOSITORY:$GIT_TAG"
- DIGEST=$(aws ecr describe-images --repository-name "$ECR_REPOSITORY" --image-ids imageTag="$GIT_TAG" --query 'imageDetails[0].imageDigest' --output text)
- export IMAGE_URI="$ECR_REGISTRY/$ECR_REPOSITORY@$DIGEST"
# imagedefinitions.json is what the CodePipeline "Amazon ECS" deploy action reads.
- printf '[{"name":"accounts-api","imageUri":"%s"}]' "$IMAGE_URI" > imagedefinitions.json
reports:
unit-and-integration-tests:
files: ["**/*.xml"]
base-directory: artifacts/test-results
file-format: JUNITXML
artifacts:
files:
- imagedefinitions.json
- deploy/ecs/taskdef.json
cache:
paths:
- "/root/.nuget/packages/**/*"Notes on the choices:
- Tests run inside the .NET 10 SDK container, not on the CodeBuild image. That makes the result the same as a laptop and avoids depending on which .NET versions the managed image ships.
CODEBUILD_RESOLVED_SOURCE_VERSIONis the exact commit CodeBuild built. Use it, not the branch name, to stamp the image: the evidence must say which commit produced which bytes.- The image reference uses the digest. The pipeline then deploys by digest, so a later push cannot change what runs.
imagedefinitions.jsonis the contract between CodeBuild and the ECS deploy action: a list of container name and image URI pairs.- The NuGet cache cuts restore time; the cache is a convenience. A cache that is poisoned (for example by a malicious package version) persists across builds, so the lab's
NuGet Auditsetting still fails the build on known high and critical advisories.
Build environment and privileged mode
Docker builds in CodeBuild need privileged mode on the project. Privileged mode allows the build container to start a Docker daemon, which gives the build more power over its host. Mitigations: dedicated project for image builds, no deploy permissions on its role, no secrets other than what it needs, and a trusted base image. If your policy forbids privileged mode, use a daemonless builder; check the options for your image and organisation ⚠ VERIFY.
Reports
A CodeBuild report group stores test results over time. Point it at the JUnit XML that dotnet test --report-junit writes. The console shows pass rate and failures per build, and the reports can be exported to an S3 bucket as evidence ⚠ VERIFY export options. The release management lesson shows how to put these in the evidence pack.
CodePipeline in depth
V1 and V2 pipelines
AWS documents two pipeline types. The differences that matter for a bank:
| Feature | V1 | V2 |
|---|---|---|
| Execution modes | Superseded only | Superseded, queued and parallel |
| Pipeline-level variables | No | Yes |
| Triggers with filters on Git tags, pull requests, branches and file paths | No | Yes |
| Stage conditions (entry, on-success, on-failure) and automatic rollback of stages | No | Yes |
| Automatic retry on stage failure | No | Yes |
Source revision overrides, Commands action | No | Yes |
| Billing | About 1 US dollar per active pipeline per month; the first 30 days of a new pipeline are free; one free active V1 pipeline per month | 0.002 US dollars per action execution minute, rounded up to the next minute; 100 free minutes per month shared across the account; manual approval and custom actions are not charged |
Superseded mode means a newer execution can take over a stage while an older one is waiting, and the older one is dropped. For a bank that wants every release candidate to pass through approval in order, queued mode (V2) keeps executions in sequence instead of discarding them ⚠ VERIFY the exact semantics of the queued mode and the rule for stage locks in the documentation before you rely on it for audit purposes. Prices are the published figures at the time of writing; confirm them on the pricing page ⚠ VERIFY, and use V2 unless you have a reason not to.
Stages, actions and artefacts
A pipeline is a list of stages; a stage is a list of actions; an action has a category and a provider:
| Category | Providers you will use |
|---|---|
| Source | CodeConnections (GitHub, GitLab, Bitbucket), CodeCommit, S3, ECR |
| Build | CodeBuild |
| Test | CodeBuild, third-party |
| Approval | Manual approval |
| Deploy | Amazon ECS, CodeDeploy, CloudFormation, Lambda, S3, and others |
| Invoke | Lambda, Step Functions |
Actions pass artefacts through the pipeline's S3 artefact bucket. Each action declares input and output artefacts by name. Encrypt the bucket with a customer managed KMS key so you control who can read pipeline outputs, and give the key policy to the pipeline, build and deploy roles only.
CodeConnections for GitHub
A connection is an AWS resource that lets CodePipeline read a GitHub repository through the AWS Connector for GitHub app, authorised once by a GitHub organisation owner. The pipeline never holds a personal access token. A few things to know:
- The connection starts in a
PENDINGstate when created by CLI, CDK or Terraform; someone must complete the handshake in the console before it works ⚠ VERIFY. - The service and API are called AWS CodeConnections; older names (CodeStar Connections) still appear in IAM actions and in some SDK and Terraform resource names, so search for both ⚠ VERIFY.
- The connection should be owned by the platform team and used by many pipelines; the pipeline role needs
codeconnections:UseConnectionon that one connection ARN (or the oldercodestar-connections:UseConnection) ⚠ VERIFY which prefix your account evaluates.
Manual approval
The approval action pauses the pipeline, can publish to an SNS topic, and records the approver's identity, comment and time in the execution history. To keep segregation of duties, give the right to approve (codepipeline:PutApprovalResult) to an approver group in IAM, and do not give that permission to the person or role that starts the pipeline.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ApproveProdStageOnly",
"Effect": "Allow",
"Action": "codepipeline:PutApprovalResult",
"Resource": "arn:aws:codepipeline:us-east-1:111122223333:hl-m09-accounts-api/Approve/ApproveProd"
},
{
"Sid": "ReadPipelineState",
"Effect": "Allow",
"Action": ["codepipeline:GetPipelineState", "codepipeline:GetPipelineExecution"],
"Resource": "arn:aws:codepipeline:us-east-1:111122223333:hl-m09-accounts-api"
}
]
}The resource format for approval actions is pipeline/stage/action ⚠ VERIFY against the IAM action table in the service authorisation reference.
CodeDeploy in depth
CodeDeploy deploys to four platforms:
| Compute platform | What CodeDeploy does | Rollback mechanism |
|---|---|---|
| EC2 / on-premises | An agent on each instance downloads a revision and runs scripts at lifecycle hooks; in-place or blue/green with a load balancer | Redeploy the last good revision; optional alarm trigger |
| Amazon ECS | Creates a replacement task set behind a second target group and shifts load balancer traffic (all at once, linear or canary) | Traffic shifts back to the original task set |
| AWS Lambda | Shifts an alias between two function versions (all at once, linear or canary), with BeforeAllowTraffic and AfterAllowTraffic hook functions | Alias points back to the old version |
| Amazon ECS native (no CodeDeploy) | ECS does blue/green, linear and canary itself in the service configuration | ECS shifts traffic back on alarm |
The last row matters. ECS now offers built-in BLUE_GREEN, LINEAR and CANARY strategies in the service's deployment configuration, with CloudWatch alarm rollback and lifecycle hooks; the lab's deploy/ecs/service-deployment.json uses it. That removes the need for a CodeDeploy application for many ECS services. CodeDeploy remains relevant for Lambda traffic shifting, for EC2 and for existing ECS services that already use it. The ECS deployment strategies lesson compares the two for ECS, and Lambda deployments goes deep on the Lambda case.
The AppSpec file
The AppSpec file tells CodeDeploy what to deploy. For Lambda (the lab file deploy/lambda/appspec.yml):
version: 0.0
Resources:
- StatementsFunction:
Type: AWS::Lambda::Function
Properties:
Name: hl-m09-statements
Alias: live
CurrentVersion: "3"
TargetVersion: "4"
Hooks:
- BeforeAllowTraffic: hl-m09-statements-pretraffic-check
- AfterAllowTraffic: hl-m09-statements-posttraffic-checkCurrentVersion is what the alias points at now; TargetVersion is what it should point at after the shift. A function named in Hooks receives an event, runs a check, and reports success or failure back to CodeDeploy. A failure triggers rollback.
For ECS the AppSpec names the task definition, the container and port, and optional hooks. For EC2 it lists files to copy and scripts to run. Platform-specific syntax is in the documentation page under Further reading.
Choosing between GitHub Actions and the AWS-native tools
| Question | Points to GitHub Actions | Points to CodePipeline + CodeBuild |
|---|---|---|
| Developers already live in GitHub; want the same pipeline on PRs and releases | Yes | Needs extra wiring for PR checks |
| Bank forbids third-party runners in the release path | Needs self-hosted runners | Yes: builds run in your account and VPC |
| Build must reach private subnets (databases for integration tests, internal registries) | Self-hosted runners | CodeBuild in VPC |
| Need a rich ecosystem (matrix builds, many reusable actions) | Yes | Limited |
| Need AWS-native audit trail and no external dependency for deployment | Partial (role session in CloudTrail) | Yes |
| Cost predictability for many small builds | Included minutes, then per minute | Per build minute plus V2 action minutes |
| Cross-account deploys with approvals owned by the platform team | Environments and roles | Pipeline stages and roles |
A hybrid is common and reasonable: GitHub Actions for pull-request checks (fast feedback, no AWS access), and CodePipeline for the release path inside AWS. Whichever you pick, the principles from the previous lessons apply: no long-term credentials, one role per context, build once and promote the same digest, and evidence recorded automatically.
Step-by-step implementation
Create the connection
Create a CodeConnections connection to GitHub, and have a GitHub organisation owner complete the authorisation. Restrict the app to the repositories the pipeline needs.
Create the artefact bucket and key
An S3 bucket with all public access blocked, versioning on, server-side encryption with a customer managed KMS key, and a lifecycle rule that expires pipeline artefacts after a retention period your policy sets. Release evidence belongs in a separate, locked bucket (see the lab's evidence.tf).
Create the CodeBuild project
Source type CodePipeline, the managed Amazon Linux image, privileged mode on (image builds only), a service role that can push to one ECR repository, write its own logs and reports, and read the artefact bucket. Environment variables: ECR_REGISTRY, ECR_REPOSITORY, APP_VERSION.
Create the pipeline
Type V2. Stages: Source (GitHub through the connection, branch main, trigger on push), Build (the CodeBuild project), DeployTest (ECS action reading imagedefinitions.json), Approve (manual approval with an SNS topic), DeployProd (ECS action using a role in the prod account).
Run it and read the history
Push a commit, watch each action, approve the production stage as a different person, and check the execution history shows who approved and when.
Break it on purpose
Make a test fail and confirm the pipeline stops before deploy; make the health check fail and confirm rollback (see the rollback lesson).
AWS Console instructions
Connection: Console → Developer Tools → Settings → Connections → Create connection → GitHub. Name it hl-github, choose Install a new app (or select the existing one), authorise as an organisation owner, and select the repositories. The status changes to Available.
CodeBuild project: Console → CodeBuild → Build projects → Create build project. Source: CodePipeline (when created through the pipeline wizard) or GitHub. Environment: managed image, Amazon Linux, standard runtime, Privileged ticked only for the image-build project, new or existing service role. Buildspec: Use a buildspec file. Logs: CloudWatch Logs group /aws/codebuild/hl-m09-accounts-api with retention set.
Pipeline: Console → CodePipeline → Pipelines → Create pipeline. Choose Build custom pipeline, pipeline type V2, execution mode Queued, and a new service role. Add the stages above. In the Approve stage add the action Manual approval and choose the SNS topic.
Reading the approval record: CodePipeline → pipeline → History → select an execution; the approval action's details list the approver and comment.
AWS CLI
P=learn-sandbox
# 1. Start a build manually with an overridden environment variable (useful for a one-off).
aws codebuild start-build --project-name hl-m09-accounts-api \
--environment-variables-override name=APP_VERSION,value=0.1.0,type=PLAINTEXT \
--profile $P
# 2. Watch a build's phase and status.
aws codebuild batch-get-builds --ids <build-id> \
--query 'builds[0].[buildStatus,currentPhase,phases[].[phaseType,phaseStatus]]' --profile $P
# 3. List recent test reports for the project's report group.
aws codebuild list-reports-for-report-group --report-group-arn <report-group-arn> --max-results 5 --profile $P
# 4. Pipeline state: which action is running or waiting for approval?
aws codepipeline get-pipeline-state --name hl-m09-accounts-api \
--query 'stageStates[].[stageName,latestExecution.status]' --output table --profile $P
# 5. Approve the prod stage (as the approver, never as the person who started the run).
aws codepipeline put-approval-result --pipeline-name hl-m09-accounts-api \
--stage-name Approve --action-name ApproveProd \
--result summary="CHG-104233 reviewed; evidence pack checked",status=Approved \
--token <token-from-get-pipeline-state> --profile $P
# 6. Execution history for evidence.
aws codepipeline list-pipeline-executions --pipeline-name hl-m09-accounts-api --max-items 10 --profile $P
# 7. List CodeDeploy applications and the last deployments of a group (Lambda or EC2 case).
aws deploy list-applications --profile $P
aws deploy list-deployments --application-name hl-m09-statements --deployment-group-name live-canary --max-items 5 --profile $PInfrastructure as code
using System.Collections.Generic;
using Amazon.CDK;
using Amazon.CDK.AWS.CodeBuild;
using Amazon.CDK.AWS.CodePipeline;
using Amazon.CDK.AWS.CodePipeline.Actions;
using Amazon.CDK.AWS.IAM;
using Amazon.CDK.AWS.KMS;
using Amazon.CDK.AWS.S3;
using Amazon.CDK.AWS.SNS;
using Constructs;
namespace Harbourline.Delivery.Infra;
public sealed class PipelineStack : Stack
{
public PipelineStack(Construct scope, string id, IStackProps props, string connectionArn) : base(scope, id, props)
{
var key = new Key(this, "ArtifactKey", new KeyProps { EnableKeyRotation = true });
var bucket = new Bucket(this, "Artifacts", new BucketProps
{
Encryption = BucketEncryption.KMS,
EncryptionKey = key,
BlockPublicAccess = BlockPublicAccess.BLOCK_ALL,
EnforceSSL = true,
Versioned = true,
RemovalPolicy = RemovalPolicy.DESTROY, // Learning shortcut: not for production
AutoDeleteObjects = true,
});
// Build project: image builds need privileged mode; its role gets NO deploy permissions.
var build = new PipelineProject(this, "Build", new PipelineProjectProps
{
ProjectName = "hl-m09-accounts-api",
Environment = new BuildEnvironment
{
BuildImage = LinuxBuildImage.AMAZON_LINUX_2023_5, // ⚠ VERIFY the newest image constant in your CDK version
ComputeType = ComputeType.SMALL,
Privileged = true,
},
BuildSpec = BuildSpec.FromSourceFilename("buildspec.yml"),
EnvironmentVariables = new Dictionary<string, IBuildEnvironmentVariable>
{
["ECR_REGISTRY"] = new BuildEnvironmentVariable { Value = $"{Account}.dkr.ecr.{Region}.amazonaws.com" },
["ECR_REPOSITORY"] = new BuildEnvironmentVariable { Value = "hl-m09-accounts-api" },
["APP_VERSION"] = new BuildEnvironmentVariable { Value = "0.1.0" },
},
EncryptionKey = key,
});
// Least privilege: push to ONE repository, and log in.
build.AddToRolePolicy(new PolicyStatement(new PolicyStatementProps
{
Actions = new[] { "ecr:GetAuthorizationToken" },
Resources = new[] { "*" },
}));
build.AddToRolePolicy(new PolicyStatement(new PolicyStatementProps
{
Actions = new[]
{
"ecr:BatchCheckLayerAvailability", "ecr:InitiateLayerUpload", "ecr:UploadLayerPart",
"ecr:CompleteLayerUpload", "ecr:PutImage", "ecr:BatchGetImage", "ecr:DescribeImages",
},
Resources = new[] { $"arn:aws:ecr:{Region}:{Account}:repository/hl-m09-accounts-api" },
}));
var source = new Artifact_("Source");
var built = new Artifact_("Built");
var approvals = new Topic(this, "ApprovalTopic");
var pipeline = new Pipeline(this, "Pipeline", new PipelineProps
{
PipelineName = "hl-m09-accounts-api",
PipelineType = PipelineType.V2,
ExecutionMode = ExecutionMode.QUEUED,
ArtifactBucket = bucket,
});
pipeline.AddStage(new StageOptions
{
StageName = "Source",
Actions = new IAction[]
{
new CodeStarConnectionsSourceAction(new CodeStarConnectionsSourceActionProps
{
ActionName = "GitHub",
ConnectionArn = connectionArn,
Owner = "harbourline-learn",
Repo = "accounts-api",
Branch = "main",
Output = source,
}),
},
});
pipeline.AddStage(new StageOptions
{
StageName = "Build",
Actions = new IAction[]
{
new CodeBuildAction(new CodeBuildActionProps
{
ActionName = "BuildAndPush",
Project = build,
Input = source,
Outputs = new[] { built },
}),
},
});
pipeline.AddStage(new StageOptions
{
StageName = "Approve",
Actions = new IAction[]
{
new ManualApprovalAction(new ManualApprovalActionProps
{
ActionName = "ApproveProd",
NotificationTopic = approvals,
AdditionalInformation = "Check the change ticket, the scan results and the test-stage smoke test.",
}),
},
});
// The deploy stages (EcsDeployAction using cross-account roles) are added in the project page.
// Inside a Stack, Amazon.CDK.Tags.Of(this) resolves to the stack's own property: qualify it.
Amazon.CDK.Tags.Of(this).Add("Project", "cea-lab");
Amazon.CDK.Tags.Of(this).Add("Lab", "m09-delivery-pipeline");
Amazon.CDK.Tags.Of(this).Add("Environment", "learn");
}
}The Artifact_ helper name stands for the CDK Artifact_ class in Amazon.CDK.AWS.CodePipeline, which has a trailing underscore in the C# binding to avoid clashing with the Artifact namespace ⚠ VERIFY the exact class name in your Amazon.CDK.Lib version. The source action class is still called CodeStarConnectionsSourceAction in current CDK releases, even though the service is now branded CodeConnections ⚠ VERIFY.
Complete code
The runnable parts of this lesson are the buildspec above and a small C# check that the pipeline can run before any AWS call: the lab's tag and release-policy tools. Validate the tag your build will push, from the repository root:
# Same tool in GitHub Actions and CodeBuild: validates the SHA and version, prints one tag per line.
dotnet run --project src/Harbourline.Delivery -- image-tags 3f9c2ab1d4e5f60718293a4b5c6d7e8f90a1b2c3 1.4.0
# git-3f9c2ab1d4e5
# 1.4.0And a C# snippet to read a pipeline's state with the AWS SDK for .NET v4, useful for a release dashboard (package AWSSDK.CodePipeline):
using Amazon.CodePipeline;
using Amazon.CodePipeline.Model;
var client = new AmazonCodePipelineClient();
var state = await client.GetPipelineStateAsync(new GetPipelineStateRequest { Name = "hl-m09-accounts-api" });
foreach (var stage in state.StageStates)
{
Console.WriteLine($"{stage.StageName,-12} {stage.LatestExecution?.Status}");
foreach (var action in stage.ActionStates)
{
var token = action.LatestExecution?.Token;
var waiting = !string.IsNullOrEmpty(token) && action.LatestExecution?.Status == ActionExecutionStatus.InProgress;
Console.WriteLine($" {action.ActionName,-14} {action.LatestExecution?.Status}{(waiting ? " (approval token present)" : "")}");
}
}Code explained line by line
PipelineType = PipelineType.V2/pipeline_type = "V2"— selects the V2 feature set and billing. Leave it out and the older type is created.ExecutionMode.QUEUED— runs executions in order instead of discarding waiting ones. For regulated release flow you usually want every merged change to pass through approval, so none is skipped.Privileged = true— required fordocker buildinside CodeBuild; keep it on the single image-build project.EncryptionKey = key— encrypts build artefacts and cache with your customer managed key, not the default AWS managed key, so the key policy controls who can read build outputs.- The two
ecr:policy statements —GetAuthorizationTokencannot be restricted to a repository, so it is*. All other actions are limited to one repository ARN. This matches the lab'spolicies/permissions-ecr-push.json. CodeStarConnectionsSourceAction— the source action reading GitHub through the connection.Owner/Repo/Branchdefine what triggers the pipeline.ManualApprovalActionwithNotificationTopic— pauses the pipeline and notifies approvers. The action is not billed in V2.- In
PipelineStatus.cs,action.LatestExecution?.Token— the token thatput-approval-resultneeds; it is present when an approval action is waiting.
Security considerations
⚠ Learning shortcut — not for production
The lab artefact bucket uses force_destroy / AutoDeleteObjects so teardown is one command, the build project runs in privileged mode with the default VPC-less network, and one account hosts the pipeline and both environments. In production: artefacts expire by a retention rule but are never force-deleted; builds run in a VPC with controlled egress; the pipeline lives in a tooling account and deploys to separate test and prod accounts through cross-account roles; and the approval permission belongs to a separate approver group.
- Separate roles. The pipeline role orchestrates; the build role builds; deploy roles deploy. Never merge them.
- Who can change the buildspec. The buildspec is code in the repository. A pull request can change what the build does, so require review on it (CODEOWNERS), and keep the build role incapable of deploying.
- Privileged mode. Treat the project as a high-risk workload: no secrets beyond the minimum, no network paths to production.
- Secrets. Use the
env.secrets-managerorparameter-storekeys in the buildspec for build-time secrets, scoped to the build role. Runtime secrets never pass through the pipeline (see Secrets in CI/CD). - Cross-account. The deploy role in the prod account trusts the pipeline role in the tooling account, and the artefact key policy must allow the prod deploy role to decrypt artefacts ⚠ VERIFY the exact grants for cross-account artefact access.
- Segregation of duties. The person who can edit the pipeline definition, the person who approves, and the person who can bypass protections should not be the same. See Federation and segregation of duties.
- Evidence. CloudTrail records
StartPipelineExecution,PutApprovalResultand the role assumptions; the pipeline's execution history is a second source. Neither replaces your bank's change record.
Banking use case
Harbourline's payments platform team runs the release path in AWS because the vendor-risk committee prefers a single supplier for build and deploy. Pull requests are checked by GitHub Actions without any AWS access (fast feedback). On merge to main, a CodePipeline V2 pipeline starts: CodeBuild builds and scans the image, pushes it to ECR by digest, deploys to test, runs smoke tests, then waits for the approval of two named release approvers. The approval comment must contain a change ticket number, checked by a Lambda invoked in the approval stage ⚠ design choice, not a built-in feature. The prod stage assumes a role in the prod account. The pipeline's execution history and the CloudTrail events form part of the quarterly evidence sample. All names are fictional.
Common mistakes
- Putting deploy permissions on the build role → a pull request that edits the buildspec can deploy to production → build role gets ECR push and logging only.
- Using the branch name for traceability → a branch moves → stamp the image with
CODEBUILD_RESOLVED_SOURCE_VERSION. - Assuming a variable set in the build container reaches later pipeline actions → only variables listed in
env.exported-variablesare handed on → export what the deploy stage needs and write files for the rest. - Leaving V1 and queued expectations mixed → V1 has only superseded mode, so releases silently skip → choose V2 and
QUEUEDwhen every release must be approved. - Forgetting to finish the connection handshake → pipeline fails at source with a connection-pending error → complete the authorisation in the console.
- Same role for approver and runner → approval is meaningless → separate groups.
- Giving CodeBuild
AdministratorAccess"temporarily" → it never leaves → write the narrow policy first.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Source stage fails: connection not available or pending | Handshake not completed | Open Developer Tools → Connections, complete Update pending connection |
CLIENT_ERROR: error while executing command: docker ... | Privileged mode is off | Enable privileged mode on the project |
denied: User ... is not authorized to perform: ecr:InitiateLayerUpload | Build role lacks ECR actions or resource ARN is wrong | Compare the role policy with permissions-ecr-push.json; check the repository ARN |
COMMAND_EXECUTION_ERROR in post_build, build marked failed | A command failed after a successful build | Fix the command; remember post_build failure fails the build |
Deploy action cannot find imagedefinitions.json | Artefact not declared in the buildspec artifacts section | List the file under artifacts.files and the output artefact in the action |
Insufficient permissions on the approval | Approver lacks codepipeline:PutApprovalResult for that action | Grant on the specific action ARN |
| Pipeline runs for every file change in the repository | No path filter on the trigger | Add trigger filters (V2): branches, file paths, tags |
| Build is slow on every run | No cache or cache disabled | Add cache.paths for /root/.nuget/packages/**/* and enable local or S3 caching on the project |
Cross-account deploy fails with KMS AccessDenied | Artefact key policy does not allow the prod role | Add the deploy role to the key policy and the bucket policy |
Cost and cleanup
Cost: credits if you run the pipeline once and tear it down the same day; about the price of a coffee at most, and often zero:
- CodeBuild: per build minute by compute type; a small Linux build of a few minutes costs a few cents, with a monthly free allowance for the small instance type ⚠ VERIFY the current allowance and per-minute price on the CodeBuild pricing page.
- CodePipeline V2: 0.002 US dollars per action execution minute after the first 100 free minutes per month; manual approval is free. A pipeline with a three-minute build and a one-minute deploy costs well under one cent per run.
- S3, KMS and CloudWatch Logs: cents. A customer managed KMS key costs about one US dollar per month, pro-rated, so delete it after the lab ⚠ VERIFY.
- CodeDeploy: no extra charge for ECS and Lambda deployments; EC2 on-premises has a per-instance fee for on-premises instances ⚠ VERIFY.
Free alternative: read the code, run the buildspec's commands locally with Docker, and use the GitHub Actions workflow in the lab for the same stages.
Teardown:
P=learn-sandbox
# Delete the pipeline, build project and connection (or: terraform destroy / cdk destroy).
aws codepipeline delete-pipeline --name hl-m09-accounts-api --profile $P
aws codebuild delete-project --name hl-m09-accounts-api --profile $P
aws codestar-connections delete-connection --connection-arn <connection-arn> --profile $P # ⚠ VERIFY the CLI namespace
# Empty and delete the artefact bucket, then schedule the KMS key for deletion (7-day minimum).
aws s3 rb s3://hl-m09-pipeline-artifacts-111122223333 --force --profile $P
aws kms schedule-key-deletion --key-id <key-id> --pending-window-in-days 7 --profile $P
# Confirm nothing from the lab remains.
aws resourcegroupstaggingapi get-resources --tag-filters Key=Lab,Values=m09-delivery-pipeline --profile $P --region us-east-1Exercises
- 🟢 Guided: Read the lab's
buildspec.ymland annotate every line with the phase it belongs to, the file it produces or the command's purpose. Then draw the artefact flow from source toimagedefinitions.jsonto the deploy action. - 🟡 Challenge: Write the IAM policy for the CodeBuild service role from scratch for this build: ECR push to one repository, its own log group, its own report group, read from the artefact bucket and decrypt with the pipeline key. Then explain which statement cannot be restricted to a resource.
- 🔴 Live problem: The internal-audit team says: "Anyone who can merge can already change the buildspec, so your approval gate proves nothing." Respond with a design: what must be true about the buildspec, the roles and the approval for the gate to mean something, and what you would show them.
Assignment
In your portfolio repository add docs/pipeline-design.md with a decision record: GitHub Actions only, CodePipeline only, or hybrid for Harbourline's payments team. Include the requirements you assumed, a table comparing the options, the roles each design needs, and the evidence each produces. Mark every assumption.
Solutions
pre_build logs in to ECR using the build role's temporary credentials (no stored keys). build runs the tests inside the SDK container (so the result matches a laptop), validates tags with the lab tool, and builds the image with version and commit stamped in. post_build pushes the tags, looks up the digest, exports IMAGE_URI and writes imagedefinitions.json. reports publishes the JUnit XML; artifacts uploads imagedefinitions.json and taskdef.json to the pipeline's bucket; cache keeps NuGet packages. Artefact flow: Source artefact (zip of the repository) goes into the Build action; the Build action outputs the Built artefact containing imagedefinitions.json; the ECS deploy action takes Built as input, reads the image URI and updates the service. Everything between stages travels through the encrypted S3 artefact bucket.
Statements: (1) ecr:GetAuthorizationToken on * (the action does not support resource-level restriction); (2) the seven image-push actions on the single repository ARN; (3) logs:CreateLogStream and logs:PutLogEvents on the project's log group ARN (and logs:CreateLogGroup if CodeBuild creates it); (4) codebuild:CreateReportGroup, CreateReport, UpdateReport, BatchPutTestCases on the project's report-group ARNs; (5) s3:GetObject, s3:GetObjectVersion, s3:PutObject on the artefact bucket's objects; (6) kms:Decrypt, kms:GenerateDataKey on the pipeline key. Only the ECR login action is unrestricted. If you reach for AdministratorAccess, a malicious buildspec inherits it. ⚠ VERIFY the exact list of report actions against the CodeBuild documentation.
Auditors are right if the buildspec can change without review, because then the approver approves code whose behaviour a pull request altered. The gate becomes meaningful when: (a) buildspec.yml, .github/workflows/ and IaC are under CODEOWNERS with required reviews by someone outside the author's team; (b) the build role has no ability to deploy or to approve, so changing the buildspec cannot reach production by itself; (c) the production deploy happens in a separate stage using a role the build cannot assume; (d) approval is by a group that excludes the person who started the execution and is limited to the prod approval action; (e) the approval record, the commit, the reviewers, the scan and test results, and the image digest are exported together. Show them the IAM policies, the CODEOWNERS file, the branch ruleset and one execution history with the evidence pack.
Knowledge check
Answer: CodeBuild runs one build in an ephemeral container. CodePipeline orchestrates stages and actions (source, build, approval, deploy) and passes artefacts between them. A pipeline can run without CodeBuild, and CodeBuild can run without a pipeline.
Answer: Per action execution minute (0.002 US dollars at the time of writing), rounded up, with 100 free minutes per month shared across the account. Manual approval and custom actions are not charged. V1 is charged per active pipeline per month.
Answer: A digest identifies exact bytes. Deploying by digest guarantees that the image that passed test is the one promoted to production, even if a tag is later moved.
Answer: The build container needs to run a Docker daemon. Privileged mode gives it broader access to the host, so limit that project's role and network, and do not give it deploy rights.
Answer: For Lambda alias traffic shifting with pre- and post-traffic hooks, for EC2 or on-premises fleets, and for existing ECS services already configured with it. For new ECS services, ECS's own blue/green, linear and canary strategies can replace it.
Answer: It names the function version the alias should point at after traffic shifting. CurrentVersion is the version the alias points at now. CodeDeploy shifts the alias gradually and rolls back to the current version on failure.
Interview questions
- Why might a bank prefer CodePipeline and CodeBuild over GitHub Actions for deployment? Builds and deploys run inside accounts and VPCs the bank controls, with AWS-managed roles, KMS and CloudTrail, and no third-party runner in the release path. The trade-offs are less flexibility and a smaller ecosystem.
- How do you give a build access to ECR safely? A dedicated service role with
GetAuthorizationTokenand image-push actions on one repository ARN, no deploy actions, and short sessions; never a stored credential. - What does queued execution mode give you? Executions run one after another instead of the older one being superseded, which suits flows where every change needs an approval record.
- How do you stop the person who started a release approving it? Separate IAM groups: only approvers get
codepipeline:PutApprovalResulton the approval action; the person starting the run is not in that group. Check it with IAM Access Analyzer or a policy simulation. - What is in the evidence for one pipeline run? The execution ID and history, commit SHA, build logs and test report, scan results, approver and time, the deployed image digest, and the CloudTrail events.
Certification practice
A company wants every merged change to pass a manual approval before production, in order, without any change being skipped when several merges happen close together. Which design is correct?
A. A V1 pipeline in superseded mode with a manual approval action. B. A V2 pipeline with queued execution mode and a manual approval action. C. Two V1 pipelines for the same repository. D. A CodeBuild project that sleeps until a person acts.
Answer: B. Queued mode runs executions in sequence. A drops waiting executions in favour of the newest. C creates two uncoordinated release paths. D has no approval record and wastes build minutes.
A CodeBuild project builds a Docker image but fails at docker build with an error that the Docker daemon cannot be reached. The buildspec is correct. What should the developer change?
A. Increase the build timeout.
B. Enable privileged mode on the project.
C. Add ecr:* to the service role.
D. Use a larger compute type.
Answer: B. Docker builds in CodeBuild need privileged mode so the daemon can start. A, C and D do not address daemon access.
A bank wants a pipeline where the build step cannot deploy to production, even if a pull request alters the buildspec. Which is the best control?
A. Give the build role AdministratorAccess but monitor with CloudTrail.
B. Give the CodeBuild role only ECR push and logging permissions, and deploy in a later stage using a separate role.
C. Store the production credentials in the buildspec environment variables.
D. Disable the approval action.
Answer: B. Role separation means a changed buildspec cannot reach production by itself. A grants the very power you want to prevent. C stores credentials in code. D removes a control.
Completion checklist
- I can explain in two sentences what CodeBuild, CodePipeline and CodeDeploy each do
- I annotated the lab buildspec phase by phase
- I can state the V1 and V2 billing models and why queued mode matters
- I wrote the narrow build-role policy and identified the one
*statement - I ran the cleanup steps and confirmed nothing is still billing
Key takeaways
- CodeBuild builds, CodePipeline orchestrates, CodeDeploy rolls out; use only what you need.
- V2 pipelines add queued and parallel executions, triggers, stage conditions and per-minute billing; approvals are free.
- Keep the build role, pipeline role and deploy roles separate, and deploy by digest.
- CodeConnections links GitHub without a stored token; the handshake is a manual step.
- ECS now does blue/green, linear and canary natively; CodeDeploy remains important for Lambda and EC2.
Further reading
- Build specification reference for CodeBuild
- Working with test reports in CodeBuild
- Pipeline types: V1 and V2
- CodePipeline pipeline execution concepts
- Add a GitHub connection to CodePipeline
- Manage approval actions in CodePipeline
- CodeDeploy AppSpec file reference
- CodePipeline pricing
- Next: Docker and Amazon ECR in pipelines
Independent learning resource — not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.
GitHub Actions with OIDC: deploy to AWS with no stored keys
Create an IAM OIDC identity provider for GitHub, write trust policies that pin a role to one repository and one environment or branch, and prove that forks, pull requests and sibling repositories cannot assume it.
Docker and Amazon ECR in pipelines
Build a small, reproducible, non-root .NET 10 container image, tag it so every running container can be traced to a commit, push it to Amazon ECR through a narrowly scoped role, scan it before and after the push, and deploy it by digest.