CI/CD Cheat Cards

Scan references for GitHub Actions and the path from a git push to a running container. Commands, tables, the gotcha, the docs path. Written while building the pipeline, so the failures in here are ones I actually hit.

ASKED — the interview question this card answers. SECURITY — getting this wrong is a finding, not a bug. Cards 01–03 are CI, 04–05 are the hand-off to AWS, 06 is debugging.

01 — Actions fundamentals

Read first

The five nouns, as Kubernetes

ActionsKubernetes
workflow = .github/workflows/*.ymlthe manifest
run = one execution—
jobPod — own VM, own empty disk, dies at the end
stepa container inside it, in order
runner (runs-on:)the node
  • Steps share a disk. Jobs do not → that's what upload-artifact / download-artifact are for.
  • Your repository is not on the runner → uses: actions/checkout@v5. This is the number-one first-workflow failure.
  • Default is parallel. needs: is the only thing that waits.
  • uses: calls a published action · run: runs shell.
  • A step passes or fails on its exit code. || true gives you green that did nothing.

Skeleton

name: ci
on:
  push:
    branches: [main]
  pull_request:
  workflow_dispatch:          # the manual button
permissions:
  contents: read
  id-token: write             # only if this file talks to AWS
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5
      - run: make test
  deploy:
    needs: build
    runs-on: ubuntu-latest
    steps:
      - run: ./deploy.sh

on: is a list of triggers, not one. All three above can fire the same file.

gh CLI

gh run list --limit 5
gh run watch                  # live tail of the current run
gh run view <ID> --log
gh workflow run <file.yml>    # fire workflow_dispatch
gh pr checks <N> --watch

workflow_dispatch only offers a button for workflows that already exist on the default branch. A new one has to be merged before you can fire it.

Hosted against self-hosted runners

hostedself-hosted
statenothing survivesleftovers survive — a feature and a risk
networkpublic internet onlyreaches your private VPC or LAN
costfree on public repos; 2000 min/month free on privateyour hardware

Pre-installed on hosted runners: git, docker, aws, node, python, jq. Not Terraform → hashicorp/setup-terraform.

In VS Code

  • GitHub.vscode-github-actions: Actions icon in the rail → Workflow Runs → job → step → the log in a tab. No browser round-trip.
  • Ctrl+Space is schema completion, and indentation decides which keys you are offered — at column zero you get top-level keys, not triggers.
Docs: docs.github.com → Actions → Writing workflows → Workflow syntax

02 — The CI gate

How do you keep CI fast?

Matrix + caching

  test:
    strategy:
      fail-fast: false        # or one failing leg kills the others
      matrix:
        node-version: [20, 22, 24]
    steps:
      - uses: actions/checkout@v5
      - uses: actions/setup-node@v4
        with:
          node-version: ${{ matrix.node-version }}
          cache: npm         # key = hash of package-lock.json
      - run: npm ci          # NOT npm install
      - run: npm test
  • One job definition becomes N parallel jobs, named test (22).
  • npm ci installs the exact lockfile, wipes node_modules first, and fails if the lockfile and manifest disagree. Same intent as pinning a provider version.
  • The cache key is content-derived — a hash of the lockfile, not the branch. So it is never stale and never needs manual busting. That's the answer to "how do you avoid a poisoned cache".
  • Three different things in the log are called cache: the tool cache (the node binary), the dependency cache, and Cache mode: write. The result lines are npm cache is not found (miss) and Cache restored from key (hit).

Artifacts — the cross-job hand-off

      - run: mkdir -p dist && npm pack --pack-destination dist
      - uses: actions/upload-artifact@v4
        with: {name: package, path: dist/*.tgz, retention-days: 1}
# a later job:
      - uses: actions/download-artifact@v4
        with: {name: package, path: dist}

Build once, pass the bytes. Rebuilding in the deploy job can ship something you never tested — the same reasoning that makes you pin an image digest. needs: [a, b] waits for all of them, and a matrix job counts as done only when every leg is.

  • retention-days or the storage bills.
  • Never commit build output (dist/, *.tgz). If you already did: git rm -r --cached plus a .gitignore. Derived files belong in the artifact store, not in history.
  • npm pack is not a build step. npm run build is a convention, not a builtin — it runs whatever scripts.build says.
Docs: docs.github.com → Actions → Using workflows → Caching dependencies · Storing workflow artifacts

03 — Branch protection

Who can push to main?Needs a public repo on Free

Settings → Rules → Rulesets

Rulesets are the current mechanism. The old "Branch protection rules" screen still exists in older repositories; say "ruleset" in an interview.

RuleWhat it buys you
Restrict deletionsnobody deletes main
Block force pushesthe history of main is what actually happened
Require a pull requestno direct pushes; everything is reviewable
Require status checksa red PR cannot be merged

The trap

  • Required checks are named per matrix leg: test (20), test (22), test (24). Add node 26 later and that leg is silently not required — a check that quietly stopped being a gate.
  • A brand-new job name is not required either. Adding push-image does not make it a gate until you add it to the ruleset.
  • On GitHub Free, rulesets need a public repository. Public also means unlimited Actions minutes.

The refusals, so you recognise them

! [remote rejected] main -> main
  (push declined due to repository rule violations)

not mergeable: the base branch policy prohibits the merge

The working pattern

gh pr create --fill
gh pr merge --auto --squash --delete-branch   # merges itself when checks go green
gh pr merge --admin                           # bypass. audited. a smell.

Open the PR, set auto-merge, walk away. --admin exists and is logged — "who can bypass, and is it recorded?" is the follow-up question.

Docs: docs.github.com → Repositories → Managing rulesets

04 — OIDC to AWS

How does your pipeline authenticate to AWS?Security

Answering this with "an access key in repo secrets" marks you junior. Answering it with "OIDC federation to a scoped role" does not.

Acronyms, once

ShortFull nameWhat it is
OIDCOpenID Connectthe standard "sign in with X" protocol — a provider signs a token, the other side verifies the signature
JWTJSON Web Tokenthe token itself: base64 JSON claims plus a signature. Readable, not forgeable
STSSecurity Token Servicethe AWS service that mints temporary credentials
ARNAmazon Resource Namethe unique identifier of any AWS object

The chain

GitHub mints a signed JWT for that one job, carrying claims — which repository, which branch, which workflow. STS verifies the signature against the identity provider you registered, checks the claims against the role's trust policy, and returns credentials that expire in about an hour. Nothing is stored in the repository.

Two AWS resources, both free

resource "aws_iam_openid_connect_provider" "github" {
  url            = "https://token.actions.githubusercontent.com"
  client_id_list = ["sts.amazonaws.com"]        # the aud claim
}

and the role's trust policy:

Action    = "sts:AssumeRoleWithWebIdentity"      # NOT sts:AssumeRole
Principal = { Federated = <oidc provider arn> }  # 3rd shape: Service / AWS / Federated
Condition = {
  StringEquals = { "...githubusercontent.com:aud" = "sts.amazonaws.com" }
  StringLike   = { "...githubusercontent.com:sub" = "repo:OWNER@<id>/REPO@<id>:ref:refs/heads/main" }
}

Why both conditions, and why sub is the only one that matters

ConditionWhat it provesWho passes it
aud = sts.amazonaws.comthe token was minted to be handed to AWS STSeveryone — every OIDC-to-AWS setup requests exactly this
sub = repo:…:ref:refs/heads/mainwhich repository and branch the run came fromonly you
  • Drop the sub condition and any GitHub repository on earth can assume your role. The provider trusts the issuer, and every Actions run in the world gets its token from that same issuer. Scoped to an admin policy, that's account takeover.
  • The sub claim carries numeric IDs: repo:owner@253738265/repo@1441488176:ref:refs/heads/main. Names are mutable — rename or transfer the repository, someone re-registers the old name, and a name-matched policy hands them your role. IDs are never reused.
  • Tighten further where you can: :ref:refs/heads/main for one branch, :environment:prod for an environment, :pull_request for PR runs. repo:owner/repo:* only if you genuinely need every ref.

The workflow side

permissions:
  id-token: write        # injects ACTIONS_ID_TOKEN_REQUEST_URL / _TOKEN
  contents: read
steps:
  - uses: aws-actions/configure-aws-credentials@v5
    with:
      role-to-assume: <role arn>
      aws-region: eu-west-1

Put permissions: on the job, not the file, so only the job that needs AWS can mint a token. The grant is what creates those two environment variables — without it the action fails with Credentials could not be loaded, which is a different error from AccessDenied.

Debugging: CloudTrail is the answer

aws cloudtrail lookup-events \
  --lookup-attributes AttributeKey=EventName,AttributeValue=AssumeRoleWithWebIdentity \
  --start-time <iso> --end-time <iso> --region <r> --max-results 3

On a failed call, the event's Username field is the exact sub claim STS rejected. Free, ninety days of history, no code change, and no token in a log. The trust policy is nothing but a string comparison against a claim you cannot otherwise see — so go and read the claim instead of guessing at its format.

Two gates, not one

PolicyQuestion it answersWhere it lives
trust policy (assume_role_policy)who may become this roleon the role, one per role
permission policywhat it may do once assumedattached, zero or many

A role with a trust policy and no permission policy authenticates perfectly and can do nothing: not authorized to perform: s3:ListAllMyBuckets because no identity-based policy allows. Build identity first, permissions second.

The caller is a session

"Arn": "arn:aws:sts::<acct>:assumed-role/<role>/<session-name>"

Not your user, not the role — a session. The session name is what CloudTrail attributes every subsequent call to, which is how you tell which workflow run did a thing.

Is the role ARN in a public repo a leak?

No. An ARN and an account ID are identifiers, not credentials. Without a signed token whose sub matches the trust policy they buy nothing, and the signing key is GitHub's and never leaves them. The honest caveat is that account IDs help reconnaissance, so some organisations treat them as sensitive — but confusing an identifier with a secret is itself a junior tell. What would be a leak is a secret access key in that file, which is exactly what you no longer have.

Docs: docs.github.com → Actions → Security → OpenID Connect → Configuring AWS · github.com/aws-actions/configure-aws-credentials

05 — Build & push to ECR

What gets deployed, exactly?

The job

  push-image:
    needs: [lint, test]                       # no untested image can exist
    if: github.ref == 'refs/heads/main'        # never push from a PR
    runs-on: ubuntu-latest
    permissions: { id-token: write, contents: read }
    steps:
      - uses: actions/checkout@v5
      - uses: aws-actions/configure-aws-credentials@v5
        with: { role-to-assume: <role arn>, aws-region: eu-west-1 }
      - id: login
        uses: aws-actions/amazon-ecr-login@v2
      - env:
          IMAGE: ${{ steps.login.outputs.registry }}/<repo>:${{ github.sha }}
        run: |
          docker build -t "$IMAGE" .
          docker push "$IMAGE"
  • Tag with github.sha, never latest. latest cannot tell you what is running and cannot be rolled back to. A SHA tag names exactly one build, forever — and it means any running container maps back to one commit.
  • The if: is belt and braces: a sub-pinned trust policy means a PR run could not assume the role even if you forgot it.
  • permissions: on the job keeps lint and test unable to touch AWS.

IAM for a push — two statements, two resource shapes

ActionResourceWhy
ecr:GetAuthorizationToken"*"mints the 12-hour token for the whole registry; it isn't a repository operation
BatchCheckLayerAvailability InitiateLayerUpload UploadLayerPart CompleteLayerUpload PutImage BatchGetImagethe repository ARNthese act on one repository

The rule: the resource you name has to match the thing the operation acts on. The S3 version of the same rule is s3:ListBucket → the bucket ARN, while GetObject/PutObject → bucket/*. And bucket/* alone is a blind read: fetch a key you already know, but you cannot enumerate.

A Dockerfile for a Node service

FROM node:24-alpine
WORKDIR /app
COPY package*.json ./        # before the source: the deps layer stays cached
RUN npm ci --omit=dev          # exact lockfile, no linter in the runtime image
COPY src/ ./
USER node                    # default is root = the first scanner finding
EXPOSE 8080
CMD ["node", "server.js"]

Copy the manifest and lockfile before the source, or every one-character edit reinstalls every dependency — Docker caches per layer, and dependencies change far less often than code.

Gotchas

  • aws_ecr_repository needs force_delete = true or terraform destroy fails while images are present.
  • One push writes three ECR records — the tagged index, the manifest, and a provenance attestation. --provenance=false drops the third.
  • ECR and your infrastructure are two lifecycles: a fresh apply creates an empty repository and nothing can pull until a push lands. Fix with a bootstrap stack, or have the pipeline push before deploying.
  • Free tier is 500 MB-month. Re-pushing a tag orphans the old digest, which is still stored and still billed — hence a lifecycle policy on untagged images.
Docs: github.com/aws-actions/amazon-ecr-login · more ECR detail on the AWS cards

06 — Debugging a red run

Discipline

Order of operations

gh run view <ID> --log-failed     # FIRST. not --log
gh run view <ID> --log            # returns NOTHING while the run is in progress
gh run list --limit 6             # PR runs show the PR TITLE, not the commit
  • Reproduce locally before pushing. A red run is a slow, public way to find a typo.
  • Read ENOENT properly: syscall open + a path + errno -2 means the directory does not exist, not that the file is missing.
  • Pinned action versions age. actions/download-artifact@v4 targeting Node 20 shows up as a deprecation warning on every run; Dependabot opening the bump PR is the real-job answer.

Reading a run

Step bars, then the ▶ Run line showing the command, then its output below it. A tick means exit 0. In VS Code the Actions sidebar gives the same tree without a browser.

When a container doesn't answer

curl saysWhat it means
Connection refusednothing is listening on that port at all — no port mapping
Connection reset by peer, empty replysomething accepted then dropped it — the mapping exists, but the process inside is dead or not yet bound
  • docker run -d returns the moment the container is created, not when it is listening. An immediate curl is a race. This is why smoke tests use curl --retry and why a load balancer returns 503 until a target passes its health check.
  • docker logs <name> before docker rm -f. Removing the container first destroys the only evidence.
  • Better still, drop -d: docker run --rm -p 8080:8080 img prints the crash straight to your terminal.

The same distinction, one layer up

Timeout means something silently dropped the packet — a security group, a NetworkPolicy, a firewall. Refused means it arrived somewhere with nothing listening. 503 means the load balancer is up with no healthy target. Three different failures that all look like "the site is down", and naming the right one is most of the diagnosis.

Docs: cli.github.com/manual → gh run · docs.docker.com → docker logs

Related: AWS & Terraform cheat cards · CKA cheat cards · CKS cheat cards · DevOps interview bank