Skip to Content
Cloud Engineering Academy
9. DevOps & CI/CD

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.

intermediate⏱ 1 h 50 min🟡 Low costDOP-C02DVA-C03

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

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:

ServiceJob in one sentence.NET analogy
CodeBuildRuns a build in a fresh container and then throws the container awayOne Azure Pipelines agent job, with the agent also created and deleted for you
CodePipelineChains actions (source, build, test, approve, deploy) in stages and passes artefacts between themThe stage and gate structure of an Azure Pipelines multi-stage YAML or a classic release pipeline
CodeDeployRolls a new version out onto compute (EC2, on-premises, ECS, Lambda) in a controlled way, with hooks and rollbackThe 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

ServiceWhat it gives youLimits and sharp edges
CodeBuildManaged 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 patchYou 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
CodePipelineVisual and auditable stage history; approvals; cross-account deploy; triggers from GitHub, S3, ECR and more; integrates with CloudFormation, ECS, CodeDeploy, LambdaLess 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
CodeDeployDeployment groups, traffic shifting configurations, lifecycle hooks, alarm-based rollback for ECS blue/green and LambdaAnother 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 equivalentWhat'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 poolCodeBuild compute (managed image)A new container per build; you pick the image and size, and pay per minute
Self-hosted agent in a VNetCodeBuild project with VPC configurationNo agent software to maintain; the project's network interface sits in your subnets
Multi-stage pipeline with environments and approvalsCodePipeline stages with a manual approval actionApproval is an action, and it records approver, comment and time
Release pipeline with deployment groupsCodeDeploy application and deployment groupCodeDeploy owns traffic shifting and rollback logic
Pipeline artifacts / PublishPipelineArtifactS3 artefact store encrypted with KMSArtefact hand-off goes through an S3 bucket the pipeline owns
Service connectionCodeConnections 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 groupsJUnit XML, Cucumber and others; keep history per group
Azure DevOps Server (on-premises)There is no direct equivalent; run CodeBuild in a VPCBuild 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:

KeyPurpose
versionAlways 0.2 for new files
envvariables (plain text), parameter-store, secrets-manager, exported-variables (values to hand to later pipeline actions), shell
phasesinstall, pre_build, build, post_build, each with commands; finally blocks run even on failure
reportsTest reports: JUnit XML and similar, grouped for history
artifactsFiles to upload as the build output
cachePaths 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:

labs/m09-delivery-pipeline/buildspec.yml (key parts)
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_VERSION is 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.json is 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 Audit setting 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:

FeatureV1V2
Execution modesSuperseded onlySuperseded, queued and parallel
Pipeline-level variablesNoYes
Triggers with filters on Git tags, pull requests, branches and file pathsNoYes
Stage conditions (entry, on-success, on-failure) and automatic rollback of stagesNoYes
Automatic retry on stage failureNoYes
Source revision overrides, Commands actionNoYes
BillingAbout 1 US dollar per active pipeline per month; the first 30 days of a new pipeline are free; one free active V1 pipeline per month0.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:

CategoryProviders you will use
SourceCodeConnections (GitHub, GitLab, Bitbucket), CodeCommit, S3, ECR
BuildCodeBuild
TestCodeBuild, third-party
ApprovalManual approval
DeployAmazon ECS, CodeDeploy, CloudFormation, Lambda, S3, and others
InvokeLambda, 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 PENDING state 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:UseConnection on that one connection ARN (or the older codestar-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.

approver-policy.json (identity policy for the release-approver group)
{
  "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 platformWhat CodeDeploy doesRollback mechanism
EC2 / on-premisesAn agent on each instance downloads a revision and runs scripts at lifecycle hooks; in-place or blue/green with a load balancerRedeploy the last good revision; optional alarm trigger
Amazon ECSCreates 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 LambdaShifts an alias between two function versions (all at once, linear or canary), with BeforeAllowTraffic and AfterAllowTraffic hook functionsAlias points back to the old version
Amazon ECS native (no CodeDeploy)ECS does blue/green, linear and canary itself in the service configurationECS 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):

labs/m09-delivery-pipeline/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-check

CurrentVersion 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

QuestionPoints to GitHub ActionsPoints to CodePipeline + CodeBuild
Developers already live in GitHub; want the same pipeline on PRs and releasesYesNeeds extra wiring for PR checks
Bank forbids third-party runners in the release pathNeeds self-hosted runnersYes: builds run in your account and VPC
Build must reach private subnets (databases for integration tests, internal registries)Self-hosted runnersCodeBuild in VPC
Need a rich ecosystem (matrix builds, many reusable actions)YesLimited
Need AWS-native audit trail and no external dependency for deploymentPartial (role session in CloudTrail)Yes
Cost predictability for many small buildsIncluded minutes, then per minutePer build minute plus V2 action minutes
Cross-account deploys with approvals owned by the platform teamEnvironments and rolesPipeline 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 $P

Infrastructure as code

PipelineStack.cs
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.0

And a C# snippet to read a pipeline's state with the AWS SDK for .NET v4, useful for a release dashboard (package AWSSDK.CodePipeline):

PipelineStatus.cs
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

  1. PipelineType = PipelineType.V2 / pipeline_type = "V2" — selects the V2 feature set and billing. Leave it out and the older type is created.
  2. 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.
  3. Privileged = true — required for docker build inside CodeBuild; keep it on the single image-build project.
  4. 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.
  5. The two ecr: policy statements — GetAuthorizationToken cannot be restricted to a repository, so it is *. All other actions are limited to one repository ARN. This matches the lab's policies/permissions-ecr-push.json.
  6. CodeStarConnectionsSourceAction — the source action reading GitHub through the connection. Owner/Repo/Branch define what triggers the pipeline.
  7. ManualApprovalAction with NotificationTopic — pauses the pipeline and notifies approvers. The action is not billed in V2.
  8. In PipelineStatus.cs, action.LatestExecution?.Token — the token that put-approval-result needs; 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-manager or parameter-store keys 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, PutApprovalResult and 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-variables are 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 QUEUED when 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

SymptomLikely causeFix
Source stage fails: connection not available or pendingHandshake not completedOpen Developer Tools → Connections, complete Update pending connection
CLIENT_ERROR: error while executing command: docker ...Privileged mode is offEnable privileged mode on the project
denied: User ... is not authorized to perform: ecr:InitiateLayerUploadBuild role lacks ECR actions or resource ARN is wrongCompare the role policy with permissions-ecr-push.json; check the repository ARN
COMMAND_EXECUTION_ERROR in post_build, build marked failedA command failed after a successful buildFix the command; remember post_build failure fails the build
Deploy action cannot find imagedefinitions.jsonArtefact not declared in the buildspec artifacts sectionList the file under artifacts.files and the output artefact in the action
Insufficient permissions on the approvalApprover lacks codepipeline:PutApprovalResult for that actionGrant on the specific action ARN
Pipeline runs for every file change in the repositoryNo path filter on the triggerAdd trigger filters (V2): branches, file paths, tags
Build is slow on every runNo cache or cache disabledAdd cache.paths for /root/.nuget/packages/**/* and enable local or S3 caching on the project
Cross-account deploy fails with KMS AccessDeniedArtefact key policy does not allow the prod roleAdd 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-1

Exercises

  • 🟢 Guided: Read the lab's buildspec.yml and 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 to imagedefinitions.json to 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

Knowledge check

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 GetAuthorizationToken and 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:PutApprovalResult on 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

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

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.

On this page