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.
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.
Unit tests and lint run on every pull request. No AWS credentials are needed yet, and none should be available to PR code.
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.comThe real security lives in the sub claim. Its shape depends on what triggered the job:
| Trigger | Example sub |
|---|---|
| Push to a branch | repo:acme/shop:ref:refs/heads/main |
| Push of a tag | repo:acme/shop:ref:refs/tags/v2.4.0 |
| Pull request | repo:acme/shop:pull_request |
Job with environment: prod | repo: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.
{
"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.
StringLikewithrepo: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 withid-token: write, the PR author gets your role. - No
subcondition 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.
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(orv*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.
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.
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:
- 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: truewait-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.
The service now wants revision 42 with the new digest.
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: readat the top; addid-token: writeonly 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_targetworkflows that check out PR code any AWS role. - Guard the account.
allowed-account-idson 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.
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?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))Put the steps of a safe production release in order.
- Tap the steps below in the right order.
Match each deploy target to its usual rollback move.
- 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.