Skip to content

Lesson 25 of 30Infrastructure as code

CI/CD to AWS with GitHub Actions

Keyless deploys from GitHub Actions to ECS, Lambda and S3: OIDC trust per environment, one image promoted by digest, approval gates and fast rollback.

14 min read0/4 questions

Terraform and CDK now give you infrastructure in reviewed code. The last step is shipping it, and your app, without anyone deploying from a laptop. The simplest pipeline pushes main straight to production with one role, which is fine for a side project. At work you will meet a different brief: two or three environments, a human approval before prod, a database migration that must run before new code, a rollback that takes two minutes rather than twenty, and a security team asking which workflow run deleted a bucket. This lesson builds that pipeline on GitHub Actions and AWS. The test and lint side of CI is covered in CI/CD for Python, and deployment strategies in general in CI/CD and Release Practices; here the focus is everything specific to getting code into AWS safely.

The pipeline you are building

Picture a FastAPI service on ECS Fargate, a React frontend on S3 and CloudFront, and a couple of Lambda functions. The team wants every merge to main to reach a dev environment automatically, and production to get exactly what was tested in dev, after someone clicks Approve.

Build once, promote the same digest
Pull request: tests, lintPull requesttests, lintBuild job: docker buildBuild jobdocker buildECR: api@sha256:9f2cECRapi@sha256:9f2cDeploy dev: role: deploy-devDeploy devrole: deploy-devIntegration tests: against devIntegration testsagainst devprod environment: required reviewerprod environmentrequired reviewerDeploy prod: role: deploy-prodDeploy prodrole: deploy-prodmerge to mainpushdigestpassapprovedsame digest

Unit tests and lint run on every pull request. No AWS credentials are needed yet, and none should be available to PR code.

1/6

Two ideas carry the whole design. First, build once: rebuilding for prod means new base-image layers, new dependency resolutions and a binary nobody tested. Second, separate credentials per stage: the dev job physically cannot change prod, so a bug in the dev half of the workflow cannot become a prod incident.

OIDC trust in depth

You already know the basic exchange: the job requests a signed token from GitHub, aws-actions/configure-aws-credentials sends it to STS with AssumeRoleWithWebIdentity, and STS checks the token's claims against the role's trust policy. The setup is one IAM OIDC identity provider per account for https://token.actions.githubusercontent.com with audience sts.amazonaws.com. Old tutorials make you paste a certificate thumbprint. You no longer need it: AWS validates GitHub's certificate itself, and a thumbprint you supply is ignored.

aws iam create-open-id-connect-provider --url https://token.actions.githubusercontent.com --client-id-list sts.amazonaws.com

The real security lives in the sub claim. Its shape depends on what triggered the job:

TriggerExample sub
Push to a branchrepo:acme/shop:ref:refs/heads/main
Push of a tagrepo:acme/shop:ref:refs/tags/v2.4.0
Pull requestrepo:acme/shop:pull_request
Job with environment: prodrepo:acme/shop:environment:prod

The last row matters most. When a job declares an environment, the sub names the environment instead of the branch. So the prod role can trust repo:acme/shop:environment:prod and nothing else, which means the only way to get prod credentials is to run a job in the prod environment, which means passing that environment's approval rules. The AWS trust policy and the GitHub approval gate now enforce the same thing from both sides.

trust policy: deploy-prod
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": { "Federated": "arn:aws:iam::222222222222:oidc-provider/token.actions.githubusercontent.com" },
    "Action": "sts:AssumeRoleWithWebIdentity",
    "Condition": {
      "StringEquals": {
        "token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
        "token.actions.githubusercontent.com:sub": "repo:acme/shop:environment:prod"
      }
    }
  }]
}

Three mistakes show up again and again in real accounts:

  • Wildcards on the repo. StringLike with repo:acme/* trusts every repository in the organization, including the intern's experiment and any repo someone creates next year. Whoever can push a workflow to any of them can deploy to prod.
  • Wildcards on the ref. repo:acme/shop:* matches pull requests too. If a workflow runs PR code with id-token: write, the PR author gets your role.
  • No sub condition at all. Then any GitHub repository in the world can assume the role. Old tutorials produced roles like this, and some are still out there.

A newer wrinkle: GitHub now puts immutable numeric IDs in the sub claim, as in repo:acme@123456/shop@789012:ref:refs/heads/main. It is the default for repositories created (or renamed or transferred) from 15 July 2026, and older repositories can opt in. It stops someone who registers a deleted org or repo name from matching your stale trust policy. If a freshly created repo gets Not authorized to perform sts:AssumeRoleWithWebIdentity with a policy that looks right, compare the claim format first.

Pythonsub_matcher.py
from fnmatch import fnmatchcase ROLES = { "ecr-push (StringEquals)": ("eq", "repo:acme/shop:ref:refs/heads/main"), "deploy-dev (StringEquals)": ("eq", "repo:acme/shop:environment:dev"), "deploy-prod (StringEquals)": ("eq", "repo:acme/shop:environment:prod"), "sloppy (StringLike repo:acme/*)": ("like", "repo:acme/*"),} TOKENS = [ "repo:acme/shop:ref:refs/heads/main", "repo:acme/shop:environment:dev", "repo:acme/shop:environment:prod", "repo:acme/shop:pull_request", "repo:acme/intern-sandbox:ref:refs/heads/main", "repo:acme@123456/shop@789012:environment:prod",] for token in TOKENS: allowed = [] for role, (op, pattern) in ROLES.items(): ok = token == pattern if op == "eq" else fnmatchcase(token, pattern) if ok: allowed.append(role.split(" ")[0]) print(f"{token:<48} -> {allowed or 'denied'}")
Output
Press Run (⌘ Enter) to see what happens.

Look at the last two lines of output. The sandbox repo gets the sloppy role, and the immutable-format token matches nothing, not even the sloppy wildcard, because acme@123456 is not acme/.

One role per environment per repo

Give each repository a separate role in each environment: shop-deploy-dev, shop-deploy-prod. Ideally dev and prod also live in separate AWS accounts, so even a too-broad permissions policy on the dev role cannot see prod resources. Then scope the permissions policy to what a deploy actually does: push to one ECR repository, register task definitions, update one ECS service, pass the two roles that service uses (iam:PassRole limited to those ARNs), sync one bucket, invalidate one distribution. If you deploy with CDK, the deploy role mostly needs permission to assume the CDK bootstrap roles, and CloudFormation does the work.

Set role-session-name to something that identifies the run. Every API call the job makes lands in CloudTrail with that session name, so "who deleted this?" becomes a link to one workflow run rather than "the GitHub role".

Environments as the approval gate

A GitHub environment is a named deployment target with its own protection rules, secrets and variables. For prod you typically turn on:

  • Required reviewers, plus "prevent self-review" so the author cannot approve their own deploy.
  • Deployment branches and tags, so only main (or v* tags) can target it. A job from a feature branch fails before it even gets a token.
  • Environment variables for everything that differs: account ID, role ARN, cluster, service, bucket. The workflow references vars.DEPLOY_ROLE_ARN, and each environment fills it differently. Role ARNs are not secrets; keep actual secrets in Secrets Manager, read by the application at runtime.

Required reviewers on private repositories depend on your GitHub plan, so check what your organization has.

The workflow

Here is the core of the pipeline. It builds once, captures the digest, and passes it to both deploy jobs.

.github/workflows/deploy.yml
name: deploy
on:
  push:
    branches: [main]
 
permissions:
  contents: read
 
jobs:
  build:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      id-token: write
    outputs:
      image: ${{ steps.push.outputs.image }}
    steps:
      - uses: actions/checkout@v7
      - uses: aws-actions/configure-aws-credentials@v6
        with:
          role-to-assume: ${{ vars.ECR_PUSH_ROLE_ARN }}
          role-session-name: build-${{ github.run_id }}
          aws-region: eu-west-1
      - id: ecr
        uses: aws-actions/amazon-ecr-login@v2
      - id: push
        env:
          REPO: ${{ steps.ecr.outputs.registry }}/shop-api
        run: |
          docker build -t "$REPO:${GITHUB_SHA}" .
          docker push "$REPO:${GITHUB_SHA}"
          digest=$(docker inspect --format '{{index .RepoDigests 0}}' "$REPO:${GITHUB_SHA}")
          echo "image=$digest" >> "$GITHUB_OUTPUT"
 
  deploy-dev:
    needs: build
    permissions:
      contents: read
      id-token: write
    uses: ./.github/workflows/deploy-ecs.yml
    with:
      environment: dev
      image: ${{ needs.build.outputs.image }}
 
  integration-tests:
    needs: deploy-dev
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - run: ./scripts/smoke.sh https://dev.shop.example.com
 
  deploy-prod:
    needs: [build, integration-tests]
    permissions:
      contents: read
      id-token: write
    uses: ./.github/workflows/deploy-ecs.yml
    with:
      environment: prod
      image: ${{ needs.build.outputs.image }}

The image reference that flows between jobs looks like 123456789012.dkr.ecr.eu-west-1.amazonaws.com/shop-api@sha256:9f2c.... Tags are mutable: anyone with push rights can move v2.4.0 or latest to other bytes. A digest cannot move. Turning on tag immutability in the ECR repository adds a second guard.

Notice that id-token: write is granted per job, not to the whole workflow (a called workflow can never get more than its caller job grants), and that the reusable deploy workflow is called once per environment. Inside it, the job declares environment: ${{ inputs.environment }}, so the sub claim and the environment variables both switch together.

Pythontag_vs_digest.py
import hashlib registry = {} # tag -> digestblobs = {} # digest -> content def push(tag, content): digest = "sha256:" + hashlib.sha256(content.encode()).hexdigest()[:12] blobs[digest] = content registry[tag] = digest return digest tested = push("v2.4.0", "app code + deps resolved on Monday")print("dev tested:", tested) # Someone rebuilds and re-pushes the same tag on Tuesdaypush("v2.4.0", "app code + deps resolved on Tuesday") print("prod by tag: ", registry["v2.4.0"], "same as tested?", registry["v2.4.0"] == tested)print("prod by digest:", tested, "content:", blobs[tested])
Output
Press Run (⌘ Enter) to see what happens.

Deploying to ECS

The deploy job takes the task definition JSON from the repo, swaps in the new image, registers a new revision and updates the service:

.github/workflows/deploy-ecs.yml (steps)
      - id: render
        uses: aws-actions/amazon-ecs-render-task-definition@v1
        with:
          task-definition: infra/taskdef.json
          container-name: api
          image: ${{ inputs.image }}
      - uses: aws-actions/amazon-ecs-deploy-task-definition@v2
        with:
          task-definition: ${{ steps.render.outputs.task-definition }}
          cluster: ${{ vars.ECS_CLUSTER }}
          service: shop-api
          wait-for-service-stability: true

wait-for-service-stability makes the job wait until the new tasks are running and healthy, so a red pipeline actually means a failed deploy. On the service, turn on the deployment circuit breaker with rollback: if new tasks keep failing to start or failing health checks, ECS stops the rollout and returns to the last working revision on its own.

For safer cutovers, ECS has built-in blue/green (since July 2025) and linear and canary strategies (since October 2025). The new revision starts alongside the old one, traffic shifts through the load balancer in one step, in equal slices, or as a small canary first, and there is a bake time before the old revision is removed. Lifecycle hooks can run a Lambda function to test the new revision before it takes traffic. These used to require CodeDeploy; now they are a setting on the service. Check the ECS documentation for which load balancer types each strategy supports in your Region.

A rolling ECS deploy with the circuit breaker
WorkflowECSALBregister taskdef :42, update servicestart :42 tasks, register targetshealth checks failingcircuit breaker tripsservice unstable: job fails

The service now wants revision 42 with the new digest.

1/5

Migrations, Lambda and static sites

Database migrations run before the new code, as a one-off ECS task from the new task definition with the command overridden to alembic upgrade head (or your tool). It runs inside the VPC with the same network access and secrets as the app, so CI never needs a database password. The step must wait for the task to stop and fail the pipeline if the exit code is not zero. Write migrations to be backward compatible (expand, then contract) so the old code still running during a rolling deploy does not break against the new schema.

Lambda deploys publish a new immutable version and move an alias such as live to it. API Gateway or the event source points at the alias, never at $LATEST. An alias can split traffic between two versions with a weight, which is how canaries work: SAM's AutoPublishAlias with a DeploymentPreference such as Canary10Percent5Minutes uses CodeDeploy to shift 10 percent, watch CloudWatch alarms, then shift the rest or roll back. Rolling back is moving the alias, which takes seconds.

Static sites need two passes so caching behaves: hashed assets with a year-long immutable cache, then index.html with no cache, then a small CloudFront invalidation.

aws s3 sync dist/ s3://shop-site-prod --delete --exclude index.html --cache-control "public,max-age=31536000,immutable"aws s3 cp dist/index.html s3://shop-site-prod/index.html --cache-control "no-cache"aws cloudfront create-invalidation --distribution-id E2ABCDEF123 --paths "/index.html"

Upload assets before index.html, or a user can load new HTML that points at a bundle that does not exist yet.

Rollback: redeploy, do not rebuild

When prod breaks at 6 pm, you have two options. Revert the commit and let the pipeline rebuild: that means CI time, a fresh dependency resolution that might pull a different version of something, and a new image no one has tested. Or redeploy the previous digest, which is already in ECR and already ran in prod yesterday. The second is faster and lower risk, so make it a button: a workflow_dispatch workflow that takes a digest (or a previous task definition revision) and runs the same deploy job. Lambda rollback is moving the alias back. Then fix forward through the normal pipeline.

Rollback has a limit: the database. If a migration dropped a column, old code cannot come back. That is the real reason for expand-and-contract migrations, and why seniors ask "is this migration reversible?" in review.

Securing the pipeline

Treat the pipeline as production infrastructure, because it can change production.

  • Pin actions by SHA. uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0. Organization policy can require it.
  • Least-privilege tokens. Default permissions: contents: read at the top; add id-token: write only on jobs that deploy.
  • No long-lived keys. No IAM users, no access keys in GitHub secrets. If a tool insists on keys, find another tool.
  • Never deploy from untrusted code. Do not give pull_request_target workflows that check out PR code any AWS role.
  • Guard the account. allowed-account-ids on the credentials action makes the job fail if it somehow gets credentials for the wrong account.
  • Protect the workflow files. CODEOWNERS on .github/workflows/ means changing the pipeline needs a platform engineer's review.
Quick check
Your prod role trusts repo:acme/shop:environment:prod. A developer adds a job without an environment: key that tries to assume the prod role from main. What happens?
Need a nudge? A hint rules out a wrong answer.
Predict the outputPython

What does this print?

from fnmatch import fnmatchcase
pattern = "repo:acme/shop:*"
subs = ["repo:acme/shop:ref:refs/heads/main",
      "repo:acme/shop:pull_request",
      "repo:acme/shopping:ref:refs/heads/main",
      "repo:acme/shop:environment:prod"]
print(sum(fnmatchcase(s, pattern) for s in subs))
Need a nudge? Hints walk you through it.
Put it in order5 steps

Put the steps of a safe production release in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Match the pairs0/4 matched

Match each deploy target to its usual rollback move.

Choose an item, then its match on the other side.
Key terms
sub claim
The OIDC token field naming the repo and the branch, tag, pull request or environment that the job ran for. Trust policies match on it.
GitHub environment
A named deploy target with protection rules such as required reviewers and allowed branches, plus its own variables and secrets.
image digest
The sha256 content hash of an image. Unlike a tag, it can never point at different bytes.
deployment circuit breaker
An ECS service setting that stops a failing rollout and returns to the last working revision.
Lambda alias
A named pointer to a function version that can split traffic between two versions for canary releases.
expand and contract
Changing a schema in backward-compatible steps across releases so old and new code both work during a deploy.
SHA pinning
Referencing an action by full commit hash so a moved tag cannot change the code your workflow runs.