CI/CD with GitHub Actions: Automating Your Workflow
CI/CD with GitHub Actions: Automating Your Workflow
GitHub Actions makes it easy to automate all your software workflows. Let's build robust CI/CD pipelines.
Basic Workflow
# .github/workflows/ci.yml
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test
- name: Build
run: npm run build
Caching Dependencies
- name: Cache dependencies
uses: actions/cache@v3
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
Matrix Strategy
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [18, 20, 22]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
- run: npm ci
- run: npm test
Environment Variables and Secrets
jobs:
deploy:
runs-on: ubuntu-latest
env:
NODE_ENV: production
steps:
- name: Deploy
env:
API_KEY: ${{ secrets.API_KEY }}
DATABASE_URL: ${{ secrets.DATABASE_URL }}
run: |
echo "Deploying to production..."
npm run deploy
Deployment Workflow
name: Deploy
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- run: npm run build
- name: Deploy to Vercel
uses: amondnet/vercel-action@v25
with:
vercel-token: ${{ secrets.VERCEL_TOKEN }}
vercel-org-id: ${{ secrets.VERCEL_ORG_ID }}
vercel-project-id: ${{ secrets.VERCEL_PROJECT_ID }}
vercel-args: '--prod'
Conditional Workflows
jobs:
test:
if: github.event_name == 'pull_request'
runs-on: ubuntu-latest
steps:
- run: npm test
deploy:
if: github.ref == 'refs/heads/main'
needs: test
runs-on: ubuntu-latest
steps:
- run: npm run deploy
Reusable Workflows
# .github/workflows/reusable.yml
on:
workflow_call:
inputs:
node-version:
required: true
type: string
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/setup-node@v4
with:
node-version: ${{ inputs.node-version }}
# Using the reusable workflow
jobs:
call-workflow:
uses: ./.github/workflows/reusable.yml
with:
node-version: '20'
Best Practices
- Use caching for faster builds
- Pin action versions for stability
- Use secrets for sensitive data
- Test in parallel with matrix
- Use conditional execution appropriately
Conclusion
GitHub Actions provides a powerful, integrated CI/CD solution. With proper configuration, you can automate testing, building, and deployment for reliable software delivery.