Skip to main content

Building CI/CD Pipelines with GitHub Actions

Build a production GitHub Actions pipeline: Docker build to ECR with OIDC, tests, image scanning, and Helm deploys with approval gates.

22 Terms

Overview and What You Will Learn

GitHub Actions is GitHub's built-in automation platform: workflow files in .github/workflows/ run jobs on hosted or self-hosted runners in response to events such as a push or a pull request. A complete pipeline that tests, builds, scans, and deploys needs no extra infrastructure, and results appear directly on the pull request.

In this lab you will build one workflow that tests and lints in parallel, builds and scans a Docker image, pushes it to Amazon ECR using OIDC (no stored AWS keys), and deploys with Helm to staging and then production behind an approval gate.

By the end you will be able to:

  • Order jobs so cheap checks run first and failures stop the pipeline early
  • Authenticate to AWS with OIDC and give each job only the permissions it needs
  • Build an image with layer caching and scan it before it is pushed
  • Deploy with Helm through GitHub Environments with required reviewers
  • Reuse deployment logic across environments with a reusable workflow
  • Run a test matrix across Node.js versions

Why This Matters in Production

A good pipeline gives every pull request fast, trustworthy feedback and makes releases routine. Engineers see test results, scan findings, and deployment status without leaving GitHub, merges deploy to staging automatically, and production waits for a person to approve.

How the pipeline is secured matters as much as what it does. Teams at companies like Shopify or Stripe keep cloud credentials short-lived, separate staging and production roles, and gate production by environment rules rather than by trust in each author.

Core Principles

Jobs without dependencies run in parallel, and needs creates the order. Checks that are cheap and independent run first, the image is built and scanned once they pass, and each environment deploys after the one before it.

flowchart TD A(["Push or pull request"]):::slate B["test and lint"]:::blue C["semgrep"]:::blue D["build, scan, push"]:::orange E["deploy-staging"]:::green F{"Required reviewers"}:::red G["deploy-production"]:::green A --> B A --> C B --> D C --> D D -->|"main only"| E E --> F --> G classDef slate fill:#475569,color:#ffffff classDef blue fill:#326CE5,color:#ffffff classDef orange fill:#F97316,color:#ffffff classDef green fill:#10B981,color:#ffffff classDef red fill:#EF4444,color:#ffffff

Three design rules shape the workflow below:

  1. Pull requests never need cloud credentials. They build and scan locally. Only pushes to main log in to AWS and push the image, so fork pull requests, which get no OIDC token, still work.
  2. Build once, deploy that image. Deploy jobs use the commit SHA as the image tag, so staging and production run exactly what was scanned.
  3. Permissions are per job. The workflow default is read-only, and a job asks for id-token: write or security-events: write only where it needs them.

Detailed Step-by-Step Practical Lab

You need an ECR repository named payment-api, an IAM role for GitHub OIDC per environment, and two EKS clusters or namespaces. Replace the account ID 123456789012 and names with yours.

Step 1 - Set Triggers, Permissions, and Global Settings

Default to read-only for the token. Anything more is granted inside the job that needs it.

YAML
name: CI/CD Pipeline
on:
push:
branches: [main]
pull_request:
branches: [main]
permissions:
contents: read
env:
AWS_REGION: ap-south-1
ECR_REGISTRY: 123456789012.dkr.ecr.ap-south-1.amazonaws.com
IMAGE_NAME: payment-api
Step 2 - Add Tests with a Matrix, Lint, and SAST

A matrix runs the same job against several versions. fail-fast: false lets every version finish, so you see which ones break. Use the Node.js versions you actually support, which should be currently maintained LTS releases. Coverage thresholds belong in the test runner's config, for example Jest's coverageThreshold, so the test command itself fails when coverage drops.

YAML
jobs:
test:
name: Test (Node ${{ matrix.node-version }})
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
node-version: [22, 24]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: npm
- run: npm ci
- run: npm test -- --coverage
- uses: actions/upload-artifact@v4
if: always()
with:
name: coverage-node-${{ matrix.node-version }}
path: coverage/
retention-days: 7
lint:
name: Lint and Format
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- run: npm ci
- run: npm run lint
- run: npm run format:check
semgrep:
name: SAST with Semgrep
runs-on: ubuntu-latest
container:
image: semgrep/semgrep:<pinned-version>
steps:
- uses: actions/checkout@v4
- run: semgrep scan --config p/nodejs --config p/secrets --error
Step 3 - Build, Scan, and Push the Image

The job builds the image into the local Docker daemon, scans it, and only then pushes. A vulnerable image never reaches ECR. The second build reuses the cache from the first, so pushing costs almost nothing. Login and push run on main only.

YAML
build:
name: Build, Scan, Push
needs: [test, lint, semgrep]
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write # OIDC token request (main only, used below)
security-events: write # upload scan results to code scanning
steps:
- uses: actions/checkout@v4
- uses: docker/setup-buildx-action@v3
- name: Build image for scanning
uses: docker/build-push-action@v6
with:
context: .
load: true
tags: ${{ env.IMAGE_NAME }}:scan
cache-from: type=gha
cache-to: type=gha,mode=max
- name: Scan image with Trivy
uses: aquasecurity/trivy-action@<pinned-commit-sha> # 0.x.x
with:
image-ref: ${{ env.IMAGE_NAME }}:scan
format: sarif
output: trivy-results.sarif
severity: HIGH,CRITICAL
exit-code: "1"
- name: Upload scan results
if: always()
uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: trivy-results.sarif
- name: Configure AWS credentials via OIDC
if: github.ref == 'refs/heads/main'
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789012:role/gha-payment-api-build-role
aws-region: ${{ env.AWS_REGION }}
- name: Log in to ECR
if: github.ref == 'refs/heads/main'
uses: aws-actions/amazon-ecr-login@v2
- name: Push image
if: github.ref == 'refs/heads/main'
uses: docker/build-push-action@v6
with:
context: .
push: true
tags: ${{ env.ECR_REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}
cache-from: type=gha
Remember

Uploading SARIF results to the Security tab uses code scanning, which is available on public repositories and on private ones with GitHub Advanced Security. If you do not have it, remove that step and keep the scan as a gate.

Step 4 - Write a Reusable Deployment Workflow

Staging and production differ only in their settings, so put the deploy steps in one reusable workflow. The called job declares environment, which means it reads that environment's own variables and secrets. Store AWS_ROLE_ARN and EKS_CLUSTER as variables on each environment, so the same workflow resolves to different values for staging and production.

Bash
gh variable set AWS_ROLE_ARN --env staging \
--body arn:aws:iam::123456789012:role/gha-payment-api-staging-role
gh variable set EKS_CLUSTER --env staging --body mumbai-staging-cluster
gh variable set AWS_ROLE_ARN --env production \
--body arn:aws:iam::123456789012:role/gha-payment-api-prod-role
gh variable set EKS_CLUSTER --env production --body mumbai-prod-cluster
YAML
# .github/workflows/deploy-env.yaml
name: Deploy to environment
on:
workflow_call:
inputs:
environment:
required: true
type: string
image-tag:
required: true
type: string
jobs:
deploy:
runs-on: ubuntu-latest
environment: ${{ inputs.environment }}
permissions:
contents: read
id-token: write
concurrency:
group: deploy-${{ inputs.environment }}
cancel-in-progress: false # never cancel a Helm upgrade mid-flight
steps:
- uses: actions/checkout@v4
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ vars.AWS_ROLE_ARN }}
aws-region: ap-south-1
- name: Point kubectl at the cluster
run: aws eks update-kubeconfig --name "${{ vars.EKS_CLUSTER }}" --region ap-south-1
- name: Deploy with Helm
env:
IMAGE_TAG: ${{ inputs.image-tag }}
ENVIRONMENT: ${{ inputs.environment }}
run: |
helm upgrade --install payment-api ./charts/payment-api \
--namespace "payment-api-$ENVIRONMENT" \
--create-namespace \
--values "./charts/payment-api/values-$ENVIRONMENT.yaml" \
--set image.repository="123456789012.dkr.ecr.ap-south-1.amazonaws.com/payment-api" \
--set image.tag="$IMAGE_TAG" \
--atomic --timeout 10m

--atomic waits for readiness and rolls back automatically if the release does not become healthy. The GitHub-hosted Ubuntu runner already includes kubectl and Helm.

Common Mistake

Using concurrency with cancel-in-progress: true on deployments. A newer push can cancel a Helm upgrade halfway and leave the release stuck in a pending state. Cancel stale test runs, but let deployments queue.

Step 5 - Call It for Staging and Production

Both deploy jobs depend on build, so the order is enforced, and they pass the commit SHA that was scanned and pushed. A job that uses a reusable workflow grants the permissions that workflow needs.

YAML
deploy-staging:
needs: build
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
permissions:
contents: read
id-token: write
uses: ./.github/workflows/deploy-env.yaml
with:
environment: staging
image-tag: ${{ github.sha }}
deploy-production:
needs: [build, deploy-staging]
permissions:
contents: read
id-token: write
uses: ./.github/workflows/deploy-env.yaml
with:
environment: production
image-tag: ${{ github.sha }}

In the repository, open Settings > Environments > production and add required reviewers. Enable "Prevent self-review" and restrict deployment to the main branch. The deploy-production job then pauses until a reviewer approves, and its OIDC subject proves it ran in the production environment.

Step 6 - Verify the Release with a Smoke Test

Add a check after deploy. A GitHub-hosted runner cannot reach internal hostnames, so test a public URL, or run this step on a self-hosted runner inside your network. Retries absorb the moment between a rollout finishing and traffic arriving.

YAML
- name: Smoke test
run: |
curl -sf --retry 6 --retry-delay 5 --retry-all-errors \
https://staging-api.razorpay.in/health
Step 7 - Notify the Team

Notifications should fire on failure, since steps after a failed step are skipped by default. Use if: failure() to alert only on problems, or if: always() to report every result.

YAML
- name: Notify Slack on failure
if: failure()
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }}
run: |
curl -sf -X POST -H 'Content-type: application/json' \
--data "{\"text\":\"Deploy failed for ${GITHUB_REPOSITORY} at ${GITHUB_SHA}\"}" \
"$SLACK_WEBHOOK_URL"

Production Best Practices & Common Pitfalls

Scenario Wrong Correct
AWS credentials Access keys in repository secrets OIDC role assumption
Action versions Floating @master or @v4 for third parties Pin to a commit SHA
Token permissions One broad workflow-level block Read-only default, grant per job
Deploy tag Rebuild per environment One image, tagged by commit SHA
Concurrent deploys Cancel in-progress deploys Queue deploys, cancel only tests
Fork pull requests Needs secrets or OIDC Build and scan locally, no cloud login
  • Use separate IAM roles per environment. The staging role should reach only staging resources. Never share one role across environments.
  • Match the OIDC trust policy to the environment. For a job that declares an environment, the token's sub claim is repo:razorpay/payment-api:environment:production, not a branch ref, so a trust policy written for ref:refs/heads/main will reject it.
  • Pin third-party actions to commit SHAs. Let Dependabot propose updates, and keep a version comment beside each pin.
  • Prefer deploying by immutable references. The commit SHA tag is a good start, and the image digest is stricter.
  • Cache dependencies and layers. Use cache: npm and type=gha layer caching to keep runs fast.
  • Alert on failure, not on everything. Constant success messages train people to ignore the channel.
Tip

To cancel outdated pull request runs without touching deployments, add concurrency: { group: ci-${{ github.ref }}, cancel-in-progress: ${{ github.event_name == 'pull_request' }} } at the workflow level. Deploy jobs keep their own non-cancelling group.

Remember

A job's needs context only contains the jobs it lists directly. Reading needs.build.outputs.* from a job that does not list build returns an empty value, which is why this pipeline passes github.sha instead of a job output.

Security

Do not interpolate untrusted values such as pull request titles or branch names into run: scripts. Pass them through env and quote them, so they cannot inject shell commands.

Common Mistake

Missing if: failure() or if: always() on a notification step. When an earlier step fails, later steps are skipped by default, so the alert never fires exactly when you need it.

Quick Reference & Troubleshooting Commands

Task Command
Trigger a workflow manually gh workflow run ci.yaml
List workflow runs gh run list --workflow=ci.yaml
View failed logs gh run view <run-id> --log-failed
Cancel a run gh run cancel <run-id>
Re-run failed jobs gh run rerun <run-id> --failed
List secret names gh secret list
Set an environment variable gh variable set NAME --env <env> --body <value>
Symptom Likely Cause Fix
Not authorized to perform sts:AssumeRoleWithWebIdentity Trust policy sub does not match Match the environment or ref in the claim
OIDC step fails on a pull request from a fork Forks get no OIDC token Skip cloud steps for pull requests
Deploy job gets an empty image tag Value read from a job not in needs Use github.sha or list the job in needs
SARIF upload fails Code scanning not available Enable it or remove the upload step
Deploy stuck in pending-upgrade A deploy was cancelled mid-run Use cancel-in-progress: false and roll back
vars.AWS_ROLE_ARN is empty Variable set on the wrong environment Set it on the environment the job declares

Resources

Explore More in CI/CD Tools and Platforms

All 3 Topics

Frequently Asked Questions

Is Building CI/CD Pipelines with GitHub Actions free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Building CI/CD Pipelines with GitHub Actions topic cover?

Build a production GitHub Actions pipeline: Docker build to ECR with OIDC, tests, image scanning, and Helm deploys with approval gates.

Found a mistake, an outdated step or a broken link?