The first CI pipeline I ever wrote ran for 23 minutes per push. It cached nothing, ran every job on every push to every branch, and used the macOS runner for tests that didn't need macOS. After a month, my organization got a $400 bill from GitHub for Actions overage, and I learned that "free tier" is a generous description if you don't understand how the billing works. The second pipeline I wrote ran in 3 minutes and cost roughly nothing. The difference was about fifteen specific things, all of which I'll cover in this article.
GitHub Actions is the most accessible CI/CD system on the planet for projects that already live on GitHub. It's also the easiest one to write badly, because the YAML is permissive and the failure modes are subtle. We're going to build a real pipeline-build, test, security scan, build Docker image, push, deploy-and we're going to do it the way I'd do it for a paying client.
What GitHub Actions Actually Is
GitHub Actions is a YAML-driven workflow engine that runs jobs on GitHub-hosted or self-hosted runners in response to events: pushes, pull requests, scheduled times, issue comments, webhook deliveries, even manually via workflow_dispatch. Each workflow is a YAML file in .github/workflows/. Each workflow has one or more jobs; each job has steps; each step is either a shell command or a reference to an "action" (a reusable unit, often from the Marketplace).
The mental model: a workflow is a graph of jobs that runs when something happens. Jobs run in parallel by default. Steps within a job run sequentially. Jobs can depend on each other via needs:. Artifacts can be passed between jobs. Secrets are scoped to the repo or the environment.
| GitHub Actions | CircleCI | GitLab CI | Jenkins | Buildkite | |
|---|---|---|---|---|---|
| Hosting | Hosted + self-hosted | Hosted + self-hosted | Hosted + self-hosted | Self-hosted | Hosted control plane + self-hosted runners |
| Free tier | Generous | Limited | Generous (on GitLab.com) | N/A | Paid only |
| Config | YAML in repo | YAML in repo | YAML in repo | Groovy in repo | YAML in repo |
| Marketplace | Huge | Smaller | Built-in | Plugins | Smaller |
| Best for | GitHub-hosted projects | Polyglot, complex pipelines | GitLab users | Heavy customization | Huge fleets, security-conscious |
If your code is on GitHub, GitHub Actions is almost always the right answer. If you're not on GitHub, pick what integrates with your platform.
Architecture at a Glance
CodeCopy
Push / PR / Schedule / Manual
|
v
+----------------+ +-----------------+
| Workflow YAML | -----> | GitHub's event |
| .github/wf.yml | | router |
+----------------+ +--------+--------+
|
+-----------------------+----------------------+
| | |
+-----v------+ +------v-------+ +-----v------+
| Job A | needs | Job B | needs | Job C |
| (ubuntu) |<--------| (ubuntu) |<-------| (macos) |
| - checkout | | - checkout | | - checkout |
| - setup X | | - download | | - setup X |
| - run test | | artifact | | - run e2e |
| - upload | | - build img | +-----+------+
| artifact | | - push img | |
+-----+------+ +-------+------+ |
| | |
+-----------+------------+---------------------+
|
+------v-------+
| Deploy job |
| (ubuntu) |
| - OIDC -> AWS |
| - kubectl ...|
+--------------+
The event router triggers a workflow run. The runner picks up the job. Each step runs in the runner's shell. Artifacts (build outputs, test results) can be uploaded and downloaded between jobs. Secrets are injected as env vars. OIDC tokens can be exchanged for cloud credentials-no long-lived AWS keys in your repo.
Prerequisites
You need:
- A GitHub repo. Public repos get unlimited Actions minutes (for hosted Linux/Windows runners; macOS is metered). Private repos get 2,000 free minutes/month on the Free plan, 3,000 on Team, 50,000 on Enterprise.
- Basic YAML literacy. If you don't know YAML's indentation rules, learn them before writing workflows-GitHub Actions YAML is unforgiving.
-
ghCLI (brew install ghorsudo apt install gh). Lets you trigger workflows, watch runs, and download logs from the terminal. - An understanding of the difference between CI (continuous integration: build + test on every change) and CD (continuous delivery/deployment: ship to environments). They're related but distinct, and a good workflow separates them.
Folder Structure
CodeCopy
plaintext
.github/
workflows/
ci.yml # build, test, lint on every push/PR
deploy.yml # deploy on merge to main or tag
security.yml # nightly security scans
release.yml # publish release artifacts on tag
actions/
setup-node/ # local composite action
action.yml
dependabot.yml # dependency update config
markdown
One workflow file per concern. Don't put CI and CD in the same file unless they're tightly coupled. Keep ci.yml fast (under 5 minutes) and put slow things (security scans, integration tests) in separate workflows.
Anatomy of a Workflow File
YAMLCopy
yaml
name: CI
on:
push:
branches: [main]
pull_request:
workflow_dispatch: # manual trigger from the Actions UI
permissions:
contents: read
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
env:
NODE_VERSION: "20"
REGISTRY: ghcr.io
jobs:
lint:
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4 with: node-version: ${{ env.NODE_VERSION }} cache: npm
- run: npm ci
- run: npm run lint
test:
runs-on: ubuntu-latest
timeout-minutes: 15
needs: lint
strategy:
fail-fast: false
matrix:
shard: [1, 2, 3, 4]
services:
postgres:
image: postgres:16
env:
POSTGRES_PASSWORD: test
POSTGRES_DB: test
ports: [5432:5432]
options: >-
--health-cmd pg_isready
--health-interval 5s
--health-timeout 3s
--health-retries 10
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4 with: node-version: ${{ env.NODE_VERSION }} cache: npm
- run: npm ci
- run: npx playwright install --with-deps chromium
- run: npm test -- --shard=${{ matrix.shard }}/${{ strategy.job-total }}
- uses: actions/upload-artifact@v4 if: always() with: name: test-results-shard-${{ matrix.shard }} path: | test-results/ coverage/ retention-days: 7
build:
runs-on: ubuntu-latest
needs: test
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@v4
- uses: docker/setup-buildx-action@v3
- uses: docker/login-action@v3 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }}
- uses: docker/build-push-action@v6 with: context: . push: true tags: | ${{ env.REGISTRY }}/${{ github.repository }}:latest ${{ env.REGISTRY }}/${{ github.repository }}:${{ github.sha }} cache-from: type=gha cache-to: type=gha,mode=max
markdown
There's a lot there. Let me walk through the parts that matter.
Walkthrough
on:. The trigger. push to main, any pull_request, and workflow_dispatch for manual runs. Don't use on: [push, pull_request] as a single list-it triggers duplicate runs on PRs from the same repo. Use the explicit form.
permissions: at the top. Scopes the auto-injected GITHUB_TOKEN to the minimum needed. The default token has broad permissions; restrict to contents: read for CI workflows. Jobs that need to push images or update commits override this with their own permissions: block.
concurrency:. Cancels superseded runs. If you push twice in quick succession to a PR, the first run is cancelled mid-flight. The group key is what defines "the same workflow"-using github.ref means each branch/PR gets its own group.
timeout-minutes:. Set it on every job. The default is 360 minutes. A job that hangs for 6 hours because of a missing test cleanup costs real money.
actions/checkout@v4. Always pin to a major version. @v4 tracks the latest v4.x release. Pinning to a SHA is more secure for high-privilege workflows but harder to maintain; do it for workflows with secrets.
actions/setup-node@v4 with cache: npm. Built-in dependency caching. The action detects your package-lock.json and caches ~/.npm automatically. No more manual actions/cache steps for node_modules.
strategy: matrix:. Runs the job once per matrix value. Here, tests run in 4 shards in parallel. Combine matrices for fan-out: matrix: { os: [ubuntu, macos], node: [18, 20] } runs 4 jobs.
services:. Sidecar containers, equivalent to docker run -d on the runner. Useful for databases, Redis, etc. They're scoped to the job and torn down automatically. Limitation: only one network, no custom networks, no depends_on. For complex setups, use a docker-compose file and docker compose up -d in a step.
if: always(). Upload artifacts even if tests fail. Without this, a failing test run leaves you with no test report to debug.
docker/build-push-action with cache-from: type=gha. Uses GitHub Actions cache for Docker layer cache. Drastically speeds up image builds. mode=max caches intermediate layers too.
Runners: Hosted, Self-Hosted, and ARC
GitHub-hosted runners are the default. They're clean VMs, you don't manage them, and they have a generous free tier. They're also slow to start (30-60s cold start), publicly addressable (good for outbound, problematic for some compliance), and shared (no, your neighbor can't see your data, but it's still a multi-tenant environment).
Self-hosted runners are your own machines. They're faster (no cold start if always-on), can live inside your VPC, and have no per-minute billing. They're also your responsibility: updates, security, scaling. Don't put a self-hosted runner on a public repo without understanding the security implications-anyone who can open a PR can run arbitrary code on your runner.
Actions Runner Controller (ARC) is the modern answer for self-hosted at scale. It runs runners as pods in a Kubernetes cluster, autoscaling them based on queue depth. You get the cost savings of self-hosted, the isolation of ephemeral runners, and the scale of K8s.
YAMLCopy
yaml
A self-hosted job
deploy:
runs-on: self-hosted
environment: production
steps:
- uses: actions/checkout@v4
- run: ./deploy.sh
markdown
environment: production adds a deployment gate. Configure it in the repo settings to require manual approval, restrict to specific branches, and inject environment-scoped secrets.
Caching
Caching is where most pipelines waste the most money. The rules:
- Cache dependencies (
~/.npm,~/.cache/pip,~/.m2/repository). - Cache build outputs (compiled artifacts, Docker layers).
- Cache tools that are slow to install (Playwright browsers, Cypress, Terraform providers).
- Use a cache key that invalidates when the lockfile changes, with
restore-keysfor partial fallback.
YAMLCopy
yaml
- uses: actions/cache@v4 with: path: | ~/.cache/pip .venv key: ${{ runner.os }}-pip-${{ hashFiles('*/requirements.txt') }} restore-keys: | ${{ runner.os }}-pip-
markdown
For Docker, use type=gha cache as shown above. For monorepos, scope cache keys by package to avoid invalidating everything when one package changes.
The cache size limit is 10GB per repo. If you exceed it, older caches are evicted. Watch this-if your cache hit rate drops to 0%, you have a problem with your key.
Conditional Execution
YAMLCopy
yaml
if: github.ref == 'refs/heads/main'
run: ./deploy.shif: failure() && github.event_name == 'push'
run: ./notify-slack.shif: startsWith(github.ref, 'refs/tags/v')
run: ./publish-release.sh
plaintext
Contexts: github, env, job, steps, runner, strategy, matrix, needs, inputs, secrets. The expression syntax is ${{ ... }}. Use it sparingly; deeply conditional workflows are hard to read.
A common pattern-deploy only on main, but always run tests:
YAMLCopy
yaml
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npm ci && npm test
deploy:
needs: test
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/checkout@v4
- run: ./deploy.sh
markdown
Secrets and OIDC
Secrets. Repo secrets are available to all workflows. Environment secrets are only available to jobs that target that environment. Org secrets can be scoped to specific repos. Secrets are masked in logs.
OIDC for cloud auth. This is the modern pattern. Instead of storing long-lived AWS keys in GitHub secrets, you configure AWS (or GCP, or Azure) to trust GitHub's OIDC provider, and GitHub issues short-lived tokens that AWS exchanges for credentials.
Setup on the AWS side (CloudFormation snippet):
YAMLCopy
yaml
AWSTemplateFormatVersion: '2010-09-09'
Resources:
GithubOidc:
Type: AWS::IAM::OIDCProvider
Properties:
Url: https://token.actions.githubusercontent.com
ClientIdList: [sts.amazonaws.com]
ThumbprintList: ["6938fd4d98bab03faadb97b34396831e3780aea1"]
GithubRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow Principal: Federated: !Ref GithubOidc Action: sts:AssumeRoleWithWebIdentity Condition: StringEquals: token.actions.githubusercontent.com:aud: sts.amazonaws.com StringLike: token.actions.githubusercontent.com:sub: repo:myorg/myrepo:ref:refs/heads/main ManagedPolicyArns:
- arn:aws:iam::aws:policy/AmazonEKSDeveloperAccess
plaintext
Workflow:
YAMLCopy
yaml
permissions:
id-token: write
contents: read
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: aws-actions/configure-aws-credentials@v4 with: role-to-assume: arn:aws:iam::123456789012:role/github-actions-deploy aws-region: us-east-1
- run: kubectl apply -k overlays/prod
markdown
No long-lived AWS keys. The role is only assumable from your repo's main branch. Beautiful.
Reusable Workflows and Composite Actions
When you have the same job pattern across multiple repos, extract it.
Reusable workflows. A workflow that other workflows call:
YAMLCopy
yaml
.github/workflows/ci-node.yml (in a shared repo)
on:
workflow_call:
inputs:
node-version:
type: string
default: '20'
secrets:
npm-token:
required: false
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4 with: node-version: ${{ inputs.node-version }} cache: npm registry-url: https://registry.npmjs.org
- run: npm ci
- run: npm test
plaintext
YAMLCopy
yaml
In a consumer repo
jobs:
ci:
uses: myorg/shared-workflows/.github/workflows/ci-node.yml@v1
with:
node-version: '20'
secrets:
npm-token: ${{ secrets.NPM_TOKEN }}
markdown
Composite actions. A bundle of steps that you can use like any other action:
YAMLCopy
yaml
.github/actions/setup-node/action.yml
name: Setup Node
inputs:
node-version:
required: true
runs:
using: composite
steps:
- uses: actions/setup-node@v4 with: node-version: ${{ inputs.node-version }} cache: npm
- run: npm ci shell: bash
plaintext
YAMLCopy
yaml
In a workflow
- uses: ./.github/actions/setup-node with: node-version: '20'
markdown
Composite actions for steps you repeat within a repo. Reusable workflows for jobs you repeat across repos.
Environments, Required Reviewers, and Branch Policies
Environments are GitHub's deployment gates. Configure them in repo settings -> Environments. Each environment can have:
- Required reviewers (someone has to click "Approve" before the job runs).
- Wait timer (e.g., 5 minutes between deploy and approval).
- Branch restriction (only
maincan deploy toproduction). - Environment secrets (only injected for jobs targeting this environment).
YAMLCopy
yaml
deploy:
needs: build
runs-on: ubuntu-latest
environment:
name: production
url: https://api.example.com
steps:
- run: ./deploy.sh
markdown
A typical setup: staging (auto-deploy on merge to main), production (manual approval required, branch-locked to main, deploy on tag or manual dispatch).
Security
GitHub Actions security is a real concern. The major risks:
pull_request_target trap. This event runs in the context of the base branch, with write access to secrets. Don't use it for workflows that check out PR code and run it-if you do, a malicious PR can exfiltrate your secrets. Use pull_request for untrusted code. If you need pull_request_target's permissions, check out the PR explicitly and run only trusted actions on it.
Secrets in PRs. By default, PRs from forks don't have access to repo secrets. This is correct. Don't disable it. For PRs that need secrets (e.g., integration tests), use a pull_request workflow that requires a maintainer to label the PR first.
Third-party actions. Anyone can publish an action. Pin to a SHA, not a tag, for actions that handle secrets. Audit with actions/dependency-review-action.
Self-hosted runners on public repos. Don't. A PR can rm -rf your runner or steal cached tokens. Use ephemeral runners (ARC) if you must.
The GITHUB_TOKEN is more powerful than you think. It can create commits, push branches, and trigger workflows. Restrict its permissions via permissions: at the workflow level. For workflows that need more, create a dedicated GitHub App and use its token.
Cost Optimization
The levers, in order of impact:
-
cancel-in-progress: true. Stop paying for runs that are superseded. -
Cache dependencies and Docker layers. A 5-minute
npm cibecomes 30 seconds. - Split slow jobs into shards. Four parallel 5-minute jobs finish faster than one 20-minute job, but cost the same. The win is in feedback speed, not money.
- Don't run macOS unless you need to. macOS runners cost 10x Linux.
-
Use smaller runners. The default
ubuntu-latestis 4 CPU, 16GB. If your job is I/O bound, it'll be just as fast on a 2-CPU runner. - Self-host or ARC for high-volume workloads. Break-even is roughly 50,000 minutes/month.
-
Skip CI on doc-only changes.
paths-ignore: ['docs/**', '*.md']or use a path filter.
A reasonable cost for a small project: $0. For a team of 10 doing 100 PRs/week: $50-200/month on Actions.
Common Mistakes
Committing secrets. Even for a minute, even in a draft PR. Use git-secrets or trufflehog in pre-commit. Rotate any secret that touches git history.
Pin to @main or @latest. Don't. A malicious maintainer of a popular action can push a backdoor and you'll run it on your next CI run. Pin to @v4 (tracks minor releases) or @<sha> (immutable).
No timeout-minutes. A hung job runs for 6 hours. Set timeout-minutes: 15 on every job.
Running everything on every push. Use paths: filters to skip CI on doc changes. Use concurrency: to cancel old runs.
Cache key is too specific. ${{ runner.os }}-npm-${{ hashFiles('**/package-lock.json') }}-${{ github.sha }} will never hit. Don't include github.sha in cache keys.
Cache key is too broad. ${{ runner.os }}-npm will return stale caches forever. Include the lockfile hash.
Not using needs:. Without needs:, all jobs run in parallel. If build doesn't depend on test, you'll build a broken image. The graph matters.
fail-fast: true in matrix. The default. If one shard fails, the others are cancelled. Sometimes you want that; for tests, often you want to see all failures. Set fail-fast: false.
Troubleshooting
"Job is queued and not starting." For hosted runners: GitHub is having capacity issues, or you've hit concurrency limits. Check www.githubstatus.com. For self-hosted: your runner is offline, or all runners are busy. gh runner list to check.
"Runner disconnected." Self-hosted runner crashed or lost network. Check the runner service logs. For ARC, check the runner pod.
"Unexpected input 'X'." Your action version doesn't support that input. Check the action's README for the version you pinned to.
"Unable to resolve action X@v1, repository not found." Either the action was deleted, renamed, or you're on a private repo and don't have access. Pin to a SHA of a published version.
Slow macOS builds. macOS runners are slow for non-mac-specific work. If you're running npm test on macOS just to test on macOS, ask if you really need to.
Cache not hitting. Check actions/cache output for "Cache hit" or "Cache restored from key". If "miss", your key is wrong or the cache was evicted. Look at the cache size in repo settings.
Self-Hosted Runners with ARC
The high-value setup for teams running a lot of CI:
- Install ARC on a Kubernetes cluster.
- Configure a RunnerDeployment that autoscales based on queue depth.
- Each job gets a fresh pod as the runner.
- Pod is destroyed after the job.
No persistent state, no shared filesystem between jobs, no "the previous job left a process running" surprises. The setup is non-trivial but pays for itself fast at scale.
YAMLCopy
yaml
ARC RunnerDeployment (Helm values)
apiVersion: actions.summerwind.dev/v1alpha1
kind: RunnerDeployment
metadata:
name: github-runner
namespace: actions-runner-system
spec:
replicas: 2
template:
spec:
repository: myorg/myrepo
labels:
- self-hosted
- arc resources: requests: { cpu: 1, memory: 2Gi } limits: { cpu: 2, memory: 4Gi }
Pair with a HorizontalRunnerAutoscaler for queue-based scaling.
Alternatives Comparison
| Tool | Best for | Why switch |
|---|---|---|
| CircleCI | Complex pipelines, SSH into runner | Better orchestration, but paid |
| GitLab CI | GitLab-hosted | If you're already on GitLab |
| Jenkins | Heavy customization, plugins | If you have a Jenkins team |
| Buildkite | Huge fleets, security | You control the runners, pay per minute |
| Drone | Lightweight, containerized | If you want simple and self-hosted |
| Woodpecker | OSS Drone fork | Free, modern |
If GitHub Actions does what you need, switching has a high switching cost and limited upside. The grass is rarely greener.
Real-World Use Cases
- Web app CI/CD. Build, test, build image, push, deploy. The canonical example.
- Mobile apps. Build on macOS runners, sign with secrets, deploy to TestFlight / Play Store via fastlane.
-
Monorepos. Use
paths:filters or Nx/Turborepo to run only affected jobs. -
Infrastructure as Code. Run
terraform planon PR,terraform applyon merge, with OIDC auth to the cloud. -
Scheduled jobs.
on: schedule: - cron: "0 2 * * *"for nightly tasks, backups, security scans. - Release pipelines. Build artifacts on tag, publish to npm/PyPI/registry, create GitHub Release with auto-generated notes.
Conclusion
GitHub Actions has eaten the CI/CD world for GitHub-hosted projects, and for good reason. It's well-integrated, the free tier is generous, and the ecosystem is huge. The cost of entry is YAML literacy and an understanding of a few non-obvious concepts: the permissions: field, concurrency:, OIDC, and the difference between pull_request and pull_request_target.
Write your CI like you'd write production code. Pin action versions. Set timeouts. Restrict permissions. Cache aggressively. Cancel superseded runs. The teams that do this have CI that takes 3 minutes and costs nothing; the teams that don't have CI that takes 20 minutes and costs a fortune. The difference isn't tooling-it's discipline.
Originally published on Mango Developer.
Top comments (1)
This is one of the few CI guides that treats trust as a first-class cost, not an appendix. The pull_request_target warning is the one I would underline twice — it runs in base-branch context with secrets, and I have seen teams reach for it just to make a comment bot work. Pairing that with OIDC scoped to main, minimal permissions: contents: read, and a timeout-minutes on every job is exactly the posture that turns a $400 surprise bill into a boring 3-minute pipeline. One question: with the deploy role locked to main, how do you handle preview deployments for PRs that genuinely need AWS credentials — a separate short-lived role gated by a maintainer label, or do you keep previews off AWS entirely?