Building a CI/CD Pipeline for Automatic Deployment
Test, build and deploy on merge with GitHub Actions, using OIDC instead of long-lived keys where possible.
- ci-cd
- github-actions
- deployment
- devops
On this page ยท 13 sections
Manual deployments (SSH into a server, pull the code, hope nothing is different from last time) are slow and error-prone. A CI/CD pipeline replaces them with a repeatable process: every change is tested, built and, when it passes, deployed the same way every time. This guide builds a pipeline with GitHub Actions that tests on every push, builds an artifact, and deploys on merge to main, with two common targets: a static site on S3 behind CloudFront, and a Node.js app on an EC2 server.
What the pipeline does
- 1Push or pull request
triggers the workflow
- 2Test
lint, type-check, unit tests
- 3Build
produce a deployable artifact
- 4Deploy
only from main, to the target environment
Step 1: The CI part (test and build)
Create .github/workflows/ci.yml:
name: CIon: pull_request: push: branches: [main]concurrency: group: ci-${{ github.ref }} cancel-in-progress: true # a newer push cancels the older runjobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version-file: .nvmrc # or: node-version: 22 cache: npm - run: npm ci - run: npm run lint - run: npm run typecheck - run: npm test -- --ci - run: npm run buildPoints worth noticing:
npm ciinstalls exactly what the lockfile says and fails on drift.cache: npmcaches the npm download cache between runs, which speeds up installs.concurrencycancels superseded runs for the same branch so you are not paying for outdated work.- Action versions (
@v4) change over time. Check each action's repository for the current major version and consider pinning to a commit SHA for stronger supply-chain safety.
Step 2: Credentials without long-lived keys (OIDC)
Instead of storing AWS access keys as secrets, let GitHub prove its identity to AWS and assume a role with temporary credentials.
- In AWS IAM, add an OpenID Connect identity provider with URL
https://token.actions.githubusercontent.comand audiencests.amazonaws.com. - Create an IAM role with a trust policy limited to your repository and branch:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Federated": "arn:aws:iam::123456789012:oidc-provider/token.actions.githubusercontent.com" }, "Action": "sts:AssumeRoleWithWebIdentity", "Condition": { "StringEquals": { "token.actions.githubusercontent.com:aud": "sts.amazonaws.com", "token.actions.githubusercontent.com:sub": "repo:your-user/your-repo:ref:refs/heads/main" } } } ]}The sub condition is the important part: only workflows from that repository and branch can assume the role. If you deploy through a GitHub environment, the subject looks like repo:your-user/your-repo:environment:production instead.
- Attach a least-privilege permissions policy to the role (for example
s3:PutObject,s3:DeleteObject,s3:ListBucketon one bucket andcloudfront:CreateInvalidationon one distribution).
Step 3: Deploy a static site to S3 and CloudFront
name: Deploy siteon: push: branches: [main]permissions: id-token: write # required to request the OIDC token contents: readconcurrency: group: deploy-production cancel-in-progress: false # let a running deployment finishjobs: deploy: runs-on: ubuntu-latest environment: production steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 cache: npm - run: npm ci - run: npm run build - uses: aws-actions/configure-aws-credentials@v4 with: role-to-assume: arn:aws:iam::123456789012:role/github-deploy-site aws-region: us-east-1 - name: Upload fingerprinted assets (long cache) run: | aws s3 sync dist "s3://${{ vars.BUCKET }}" --delete \ --exclude "index.html" \ --cache-control "public,max-age=31536000,immutable" - name: Upload index.html (always revalidate) run: | aws s3 cp dist/index.html "s3://${{ vars.BUCKET }}/index.html" \ --cache-control "no-cache" --content-type "text/html" - name: Invalidate CloudFront run: | aws cloudfront create-invalidation \ --distribution-id "${{ vars.DISTRIBUTION_ID }}" \ --paths "/index.html"vars.* are non-secret repository or environment variables; bucket names and distribution IDs are configuration, not secrets. The environment: production line lets you add protection rules such as required reviewers or restricting deployments to the main branch.
Step 4: Deploy a Node.js app to EC2
For a server you manage, a simple and auditable approach is to connect over SSH with a dedicated deploy key and run a deploy script that already exists on the server:
name: Deploy APIon: push: branches: [main]concurrency: group: deploy-api cancel-in-progress: falsejobs: test: 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 test -- --ci deploy: needs: test runs-on: ubuntu-latest environment: production steps: - name: Set up SSH run: | install -m 700 -d ~/.ssh echo "${{ secrets.DEPLOY_SSH_KEY }}" > ~/.ssh/id_ed25519 chmod 600 ~/.ssh/id_ed25519 ssh-keyscan -H "${{ vars.DEPLOY_HOST }}" >> ~/.ssh/known_hosts - name: Run deploy script run: ssh deploy@${{ vars.DEPLOY_HOST }} "bash ~/apps/my-api/deploy.sh ${{ github.sha }}"On the server, deploy.sh checks out the given commit, installs, builds and reloads the app:
#!/usr/bin/env bashset -euo pipefailSHA="${1:?commit sha required}"cd ~/apps/my-apigit fetch --all --prunegit checkout --force "$SHA"npm cinpm run buildpm2 reload ecosystem.config.cjs --update-envcurl --fail --retry 5 --retry-delay 2 http://127.0.0.1:3000/healthThe final curl --fail is a smoke test: if the new version does not answer its health check, the script exits non-zero and the workflow fails visibly. Deploying a specific commit SHA (instead of "latest main") also makes rollbacks simple.
If you would rather not open SSH to the internet, AWS Systems Manager Run Command can run the same script on the instance using the OIDC role.
Rollbacks
Make rolling back a first-class operation, not an emergency improvisation:
- Deploy immutable versions (a commit SHA or tag), so any earlier version can be redeployed.
- Add a manual trigger with a version input:
on: workflow_dispatch: inputs: ref: description: "Commit SHA or tag to deploy" required: true- For static sites, keep S3 bucket versioning on so you can restore previous objects.
- Test the rollback path before you need it.
Environments and approvals
Use two environments, staging and production. Deploy to staging automatically on merge, then require a reviewer approval for production in the environment settings. Environment-scoped secrets and variables mean staging credentials can never be used for production.
Security considerations
- Least privilege: the workflow's role or key should only be able to do what the deployment needs.
- Pin actions: use trusted actions, pin versions (ideally SHAs), and keep them updated.
permissions:declare the minimumGITHUB_TOKENpermissions at the top of each workflow.- Pull requests from forks should not receive secrets. Do not run deployment jobs on
pull_requestevents. - Never print secrets. GitHub masks known secrets in logs, but derived values may not be masked.
- Protect the
mainbranch: require pull requests and passing checks before merge.
Performance considerations
- Cache dependencies (
cache: npm) and, for monorepos, build only what changed. - Run independent jobs (lint, tests, type-check) in parallel instead of one long job.
- Build once and pass the artifact to later jobs with
actions/upload-artifactanddownload-artifactso you deploy exactly what you tested.
Troubleshooting
| Symptom | Likely cause |
|---|---|
Not authorized to perform sts:AssumeRoleWithWebIdentity | Trust policy sub or aud does not match, or id-token: write is missing |
Credentials could not be loaded | OIDC step ran without the permission, or wrong role-to-assume |
| Deploy succeeds but old site shows | Cached index.html; check Cache-Control and invalidation |
Permission denied (publickey) | Wrong deploy key, or its public key is not in authorized_keys |
npm ci fails on CI only | Lockfile out of sync or different Node version |
| Two deploys overlap | Missing concurrency group |
| Workflow does not trigger | Wrong branch filter or workflow file not on the default branch |
Testing the pipeline
Test the pipeline itself like code: open a pull request that intentionally breaks a test and confirm the run fails and no deployment happens; merge a harmless change and watch a full deploy; deliberately deploy a broken build to staging to confirm the smoke test fails loudly; and rehearse a rollback.
Best practices
- Fail fast: cheap checks (lint, types) before slow ones.
- Deploy the artifact you tested, identified by a commit SHA.
- Use OIDC and short-lived credentials where supported.
- Add a health check after every deploy and alert on failure.
- Keep deployment steps in scripts under version control so they can be run and tested outside CI.
Conclusion
A deployment pipeline is a safety system as much as a convenience. Tests gate every change, a single automated path replaces ad-hoc SSH sessions, short-lived credentials remove stored keys, and a smoke test plus a rehearsed rollback limit the damage of a bad release. Start with CI on pull requests, add a deploy job for one environment, and grow the pipeline as your needs do.
Frequently asked questions
+What is the difference between continuous integration and continuous deployment?
Continuous integration automatically builds and tests every change. Continuous delivery keeps every passing build ready to release, and continuous deployment releases it automatically without a manual step.
+Why use OIDC instead of AWS access keys in GitHub Actions?
OIDC gives the workflow short-lived credentials by assuming an IAM role, so there are no long-lived keys stored in GitHub secrets to leak or rotate. You also restrict exactly which repository and branch can assume the role.
+How do I roll back a bad deployment?
Redeploy a previous known-good commit or tag, for example by re-running the workflow for that commit or triggering a manual workflow with a version input. Keep artifacts or versioned builds so a rollback does not require rebuilding.
+Should deployments run on every push?
Run tests on every push and pull request, but deploy only from your main branch (or on tags), ideally to staging first. Use environments with required reviewers if production deploys need approval.
+How do I stop two deployments running at the same time?
Use a concurrency group in the workflow so only one deployment per environment runs at once, and decide whether newer runs should cancel or queue behind older ones.
+Where should secrets live?
In GitHub encrypted secrets or environment secrets, scoped to the environment that needs them, and never in the repository or in workflow logs. Prefer identity federation (OIDC) over stored credentials when the provider supports it.
+How do I speed up slow pipelines?
Cache dependencies, run independent jobs in parallel, run only the tests relevant to the change when safe, and avoid rebuilding artifacts in later jobs by passing them between jobs.