Ci cd pipeline design

From FerroxLabs/murage · View interactive version

Ci cd pipeline design is an AI agent skill from the GitHub repository FerroxLabs/murage. Guides expert-level ci/cd pipeline design implementation: ci-cd and automation decision frameworks, production-ready patterns, and concrete templates for ci cd pipeline design workflows. Use when the user asks about ci/cd pipeline design, ci cd pipeline design configuration, or ci-cd best practices

How to use this skill

Skill file

CI/CD Pipeline Design

When to Use

Use this skill when:

Do NOT use this skill when:


Process

1. Gather Pipeline Context and Constraints

Before producing any pipeline design, collect the following inputs explicitly from the user. Each answer materially changes the recommended architecture.

2. Choose the Pipeline Topology

Apply this decision framework based on collected context:

3. Design Stage Structure and Sequencing

Define each stage explicitly with its purpose, inputs, outputs, and failure behavior:

4. Design the Artifact Strategy

Artifact management is where most pipeline designs have critical gaps:

5. Implement Caching and Performance Optimization

Pipeline speed directly affects developer productivity. A pipeline exceeding 15 minutes total causes developers to context-switch and reduces merge frequency:

6. Implement Security and Compliance Controls

Security must be embedded in the pipeline design, not bolted on:

7. Design for Failure and Recovery

Every pipeline design must answer: what happens when things go wrong?

8. Document and Operationalize the Pipeline

A pipeline that only the person who built it can maintain is a liability:


Output Format

Produce the following artifacts when designing a CI/CD pipeline. Use this exact structure.

Pipeline Architecture Summary

Application:        [name and type]
Repository layout:  [single-repo / monorepo / polyrepo]
CI Platform:        [GitHub Actions / GitLab CI / CircleCI / etc.]
CD Target:          [Kubernetes / Lambda / VM / PaaS]
Deployment strategy:[rolling / blue-green / canary]
Environments:       [dev → staging → production or custom chain]
Expected pipeline duration: [X minutes end-to-end]

Stage Map

| Stage | Trigger | Runs On | Target Duration | Failure Behavior |

|---|---|---|---|---|

| Lint & Unit Test | Every push | linux/amd64 small runner | < 3 min | Block all downstream |

| Build & Package | main branch, release tags | linux/amd64 medium runner | < 5 min | Block deployment stages |

| Integration Test | main branch | linux/amd64 medium runner (parallel x3) | < 8 min | Block deployment stages |

| Security Scan | main branch | linux/amd64 small runner | < 6 min | Block on CRITICAL/HIGH |

| Deploy Staging | main branch, after tests pass | linux/amd64 small runner | < 4 min | Auto-rollback after 5 min |

| Smoke Test Staging | After deploy-staging | linux/amd64 small runner | < 3 min | Block production gate |

| Deploy Production | Manual approval after staging pass | linux/amd64 small runner | < 5 min | Auto-rollback after 10 min |

Pipeline Definition (GitHub Actions example)

# .github/workflows/ci-cd.yaml
name: CI/CD Pipeline

on:
  push:
    branches: [main, "release/**"]
  pull_request:
    branches: [main]

permissions:
  contents: read
  packages: write
  id-token: write  # Required for OIDC cloud credential federation

env:
  IMAGE_REGISTRY: ghcr.io
  IMAGE_NAME: ${{ github.repository }}

jobs:
  lint-and-unit-test:
    name: Lint & Unit Tests
    runs-on: ubuntu-22.04
    timeout-minutes: 10
    steps:
      - uses: actions/checkout@v4

      - name: Cache dependencies
        uses: actions/cache@v4
        with:
          path: ~/.npm
          key: npm-${{ hashFiles('**/package-lock.json') }}
          restore-keys: npm-

      - name: Install dependencies
        run: npm ci --prefer-offline

      - name: Lint
        run: npm run lint

      - name: Unit tests
        run: npm test -- --coverage --ci
        env:
          CI: true

  build-and-push:
    name: Build & Push Image
    runs-on: ubuntu-22.04
    needs: lint-and-unit-test
    # Only build images on main branch and release tags, not PRs
    if: github.event_name == 'push'
    timeout-minutes: 15
    outputs:
      image-digest: ${{ steps.push.outputs.digest }}
      image-tag: ${{ steps.meta.outputs.tags }}
    steps:
      - uses: actions/checkout@v4

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Log in to Container Registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.IMAGE_REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Extract image metadata
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.IMAGE_REGISTRY }}/${{ env.IMAGE_NAME }}
          tags: |
            # Tag with full git SHA for immutable references
            type=sha,format=long
            # Tag with semver if triggered by a version tag
            type=semver,pattern={{version}}

      - name: Build and push with cache
        id: push
        uses: docker/build-push-action@v5
        with:
          context: .
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=registry,ref=${{ env.IMAGE_REGISTRY }}/${{ env.IMAGE_NAME }}:cache
          cache-to: type=registry,ref=${{ env.IMAGE_REGISTRY }}/${{ env.IMAGE_NAME }}:cache,mode=max
          # Multi-platform build for ARM64 support
          platforms: linux/amd64,linux/arm64
          provenance: true
          sbom: true

  security-scan:
    name: Security Scan
    runs-on: ubuntu-22.04
    needs: build-and-push
    timeout-minutes: 15
    steps:
      - name: Scan image with Trivy
        uses: aquasecurity/trivy-action@master
        with:
          image-ref: "${{ env.IMAGE_REGISTRY }}/${{ env.IMAGE_NAME }}@${{ needs.build-and-push.outputs.image-digest }}"
          format: sarif
          output: trivy-results.sarif
          severity: CRITICAL,HIGH
          exit-code: 1  # Fail on CRITICAL or HIGH
          ignore-unfixed: true  # Do not fail on CVEs without a fix available

      - name: Upload scan results
        uses: github/codeql-action/upload-sarif@v3
        if: always()
        with:
          sarif_file: trivy-results.sarif

  integration-test:
    name: Integration Tests (Shard ${{ matrix.shard }}/${{ matrix.total }})
    runs-on: ubuntu-22.04
    needs: build-and-push
    timeout-minutes: 20
    strategy:
      fail-fast: false  # Let all shards complete for full failure picture
      matrix:
        shard: [1, 2, 3]
        total: [3]
    steps:
      - uses: actions/checkout@v4

      - name: Run integration test shard
        run: |
          npm run test:integration -- \
            --shard=${{ matrix.shard }}/${{ matrix.total }} \
            --forceExit
        env:
          TEST_IMAGE: "${{ env.IMAGE_REGISTRY }}/${{ env.IMAGE_NAME }}@${{ needs.build-and-push.outputs.image-digest }}"

  deploy-staging:
    name: Deploy to Staging
    runs-on: ubuntu-22.04
    needs: [integration-test, security-scan]
    environment:
      name: staging
      url: https://staging.example.com
    timeout-minutes: 15
    steps:
      - uses: actions/checkout@v4

      - name: Configure AWS credentials via OIDC
        uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::123456789012:role/github-actions-staging-deploy
          aws-region: us-east-1
          # No access keys stored -- federated via OIDC

      - name: Deploy to Kubernetes staging namespace
        run: |
          # Update the image tag in the Kubernetes deployment
          kubectl set image deployment/app \
            app=${{ env.IMAGE_REGISTRY }}/${{ env.IMAGE_NAME }}@${{ needs.build-and-push.outputs.image-digest }} \
            --namespace=staging
          # Wait for rollout with timeout
          kubectl rollout status deployment/app --namespace=staging --timeout=300s

      - name: Run smoke tests against staging
        run: npm run test:smoke -- --baseUrl=https://staging.example.com
        timeout-minutes: 5

  deploy-production:
    name: Deploy to Production
    runs-on: ubuntu-22.04
    needs: deploy-staging
    # Requires manual approval via GitHub Environments protection rules
    environment:
      name: production
      url: https://example.com
    timeout-minutes: 20
    steps:
      - uses: actions/checkout@v4

      - name: Configure AWS credentials via OIDC
        uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::123456789012:role/github-actions-prod-deploy
          aws-region: us-east-1

      - name: Deploy to Kubernetes production namespace
        run: |
          kubectl set image deployment/app \
            app=${{ env.IMAGE_REGISTRY }}/${{ env.IMAGE_NAME }}@${{ needs.build-and-push.outputs.image-digest }} \
            --namespace=production
          kubectl rollout status deployment/app --namespace=production --timeout=300s

      - name: Run post-deploy smoke tests
        run: npm run test:smoke -- --baseUrl=https://example.com
        timeout-minutes: 10

      - name: Notify on failure and rollback
        if: failure()
        run: |
          kubectl rollout undo deployment/app --namespace=production
          echo "::error::Production deploy failed -- rolled back to previous version"

Decision Matrix: Deployment Strategy Selection

| Criterion | Rolling Update | Blue/Green | Canary |

|---|---|---|---|

| Rollback speed | 2--5 min | < 30 sec | Depends on ramp |

| Infrastructure cost | 1x | 2x during deploy | 1.1--1.5x |

| Traffic cutover control | None | Instant all-or-nothing | Percentage-based |

| Database migration safety | Risky with schema changes | Safe with dual-write | Safe with feature flags |

| Best for | Stateless services with backward-compatible changes | Services with risky changes or SLA requirements | High-traffic services where % rollout reduces blast radius |

| Minimum Kubernetes version | 1.1+ | Requires Ingress or Service Mesh | Requires Ingress or Service Mesh (Istio, Linkerd, NGINX) |

Caching Strategy Reference

| Ecosystem | Cache Key Pattern | Cache Path | Estimated Speedup |

|---|---|---|---|

| Node.js / npm | npm-${{ hashFiles('**/package-lock.json') }} | ~/.npm | 60--80% |

| Python / pip | pip-${{ hashFiles('**/requirements.txt') }} | ~/.cache/pip | 50--70% |

| Go modules | go-${{ hashFiles('**/go.sum') }} | ~/go/pkg/mod | 70--85% |

| Java / Maven | maven-${{ hashFiles('**/pom.xml') }} | ~/.m2 | 60--75% |

| Docker layers | Registry cache with type=registry,mode=max | Registry | 40--60% |

| Gradle | gradle-${{ hashFiles('**/*.gradle') }} | ~/.gradle | 65--80% |


Rules

  1. NEVER rebuild artifacts per environment. Build once, tag with the git SHA, promote the same artifact through environments. Rebuilding introduces the risk that staging and production run different code even with the same commit SHA if build inputs change between runs.
  1. NEVER use mutable image tags ("latest", "main", "stable") as deployment references. These tags silently change, making it impossible to know what is actually deployed. Always reference images by digest (sha256:...) in deployment manifests and pipeline deploy steps.
  1. NEVER store cloud credentials as long-lived CI secrets. Use OIDC federation to assume roles directly from GitHub Actions, GitLab CI, or CircleCI. Long-lived access keys in CI secrets are a top-3 cloud security incident cause. OIDC-based roles can be scoped per branch, per job, and with session duration limits.
  1. ALWAYS enforce a maximum timeout on every CI job. Default timeouts (GitHub Actions: 360 minutes) allow a single hung job to consume a runner for hours. Set job timeouts to 2x the expected runtime: if a build typically takes 7 minutes, set timeout-minutes: 15. Alert when jobs approach the timeout threshold.
  1. NEVER make security scans optional on the main branch. It is acceptable to run security scans in audit-only mode on feature branches during initial rollout, but all merges to main must pass CRITICAL and HIGH severity gates before the artifact can be promoted to any deployment environment.
  1. ALWAYS use fail-fast: false in parallel test matrix jobs. When parallelizing tests, a failure in shard 1 should not cancel shards 2 and 3. Collecting all failures in a single run dramatically reduces debugging time compared to finding one failure at a time on successive runs.
  1. NEVER commit secrets, tokens, or credentials to pipeline definition files. Pipeline YAML files are version-controlled and readable by anyone with repository access. All secrets must come from the CI platform's secrets store, injected at runtime. Scan pipeline files with tools like Gitleaks or Trufflesecurity as part of the lint stage.
  1. ALWAYS implement automated rollback for production deployments. A deploy step must be followed by a validation step (smoke tests, health check polling). If validation fails within the defined window (typically 5--10 minutes), the pipeline must automatically revert to the previous known-good artifact. Do not rely on humans to detect and initiate rollback during an incident.
  1. NEVER couple application secrets to container images. Configuration and secrets must be injected at runtime (Kubernetes Secrets, AWS SSM Parameter Store, HashiCorp Vault agent injection) not baked into the image at build time. An image containing secrets cannot be stored in a shared registry, cannot be promoted between environments, and creates a permanent secret exposure in image layers.
  1. ALWAYS track pipeline metrics and treat pipeline health as a first-class operational concern. A main branch with a build success rate below 90% over 7 days indicates a systemic problem (flaky tests, bad dependencies, environment drift) that reduces team velocity more than any feature work. Alert on build success rate drops and treat pipeline failures as production incidents when they block the main branch for more than 1 hour.

Edge Cases

Monorepo with Dozens of Services

When a single repository contains 10--50 independent services, a naive "build everything on every commit" approach becomes untenable -- pipelines exceeding 30 minutes for an unrelated change destroy developer velocity. Implement change detection using one of these strategies:

Database Migrations in Continuous Deployment

Database schema changes are the most dangerous operation in a CD pipeline. The schema and application code can be briefly out of sync during a rolling deployment:

Pipeline for a Regulated Environment (SOC 2 / PCI-DSS)

Standard pipeline designs lack the audit trail and separation-of-duty controls required for formal compliance:

Slow Pipeline Performance Degradation Over Time

Pipelines that start at 8 minutes frequently reach 25--30 minutes after 12--18 months as test suites grow and dependencies accumulate. Treat this as a performance regression:

Multi-Cloud or Multi-Region Deployments

When an application deploys to multiple cloud providers or regions simultaneously, the pipeline must handle deployment fan-out without creating a partial-deployment failure scenario:

Self-Hosted Runners in Air-Gapped Environments

Enterprises with air-gapped or private cloud deployments cannot use cloud-hosted CI runners or public container registries:

Incident During a Deployment in Progress

When a production incident is detected while a deployment is mid-flight:


Example

Input: "We have a Node.js API service (Express, TypeScript) deployed to Kubernetes on AWS EKS. The team is 8 engineers. Right now we have a basic Jenkins pipeline that does build and deploy in about 20 minutes. We want to migrate to GitHub Actions with proper stages, security scanning, and blue/green deployments. How should we design this?"


Output:

Assessment

Current state analysis:

The 20-minute Jenkins pipeline is likely suffering from: no dependency caching, sequential test execution, single-stage build with no parallelism, and no distinct artifact promotion (probably rebuilding on every deploy). The migration to GitHub Actions is the right move -- it enables pipeline-as-code without a separate Jenkins server, native OIDC for AWS credential federation, and GitHub Environment protection rules for production approval gates.

Key constraints from your context:


Recommended Pipeline Architecture

Application:         express-api (Node.js 20, TypeScript)
Repository layout:   Single-repo single-service
CI Platform:         GitHub Actions
CD Target:           AWS EKS (Kubernetes 1.28)
Deployment strategy: Blue/Green via AWS Load Balancer Controller
Environments:        PR preview → staging → production
Expected pipeline duration: 12-14 minutes end-to-end (target after caching)
Rollback time:       < 45 seconds (ALB target group swap)

Stage Map

| Stage | Trigger | Runs On | Target Duration | Failure Behavior |

|---|---|---|---|---|

| Lint & Unit Test | Every push | ubuntu-22.04 (2-core) | < 3 min | Block all downstream |

| Type Check | Every push (parallel) | ubuntu-22.04 (2-core) | < 2 min | Block all downstream |

| Build & Push Image | Push to main only | ubuntu-22.04 (4-core) | < 5 min | Block deployment |

| Security Scan (Trivy) | After build | ubuntu-22.04 (2-core) | < 4 min | Block on CRITICAL/HIGH |

| Integration Tests (3 shards) | Push to main only | ubuntu-22.04 (2-core) x3 | < 8 min | Block deployment |

| Deploy Staging (Blue/Green) | After all tests pass | ubuntu-22.04 (2-core) | < 4 min | Auto-rollback |

| Smoke Tests Staging | After staging deploy | ubuntu-22.04 (2-core) | < 2 min | Block production gate |

| Deploy Production (Blue/Green) | Manual approval + staging pass | ubuntu-22.04 (2-core) | < 5 min | Auto-rollback + alert |


Dockerfile (Multi-stage, TypeScript)

# Build stage -- compiles TypeScript, installs ALL deps including devDeps
FROM node:20-alpine AS builder
WORKDIR /app
# Copy lockfiles first for layer caching
COPY package.json package-lock.json ./
RUN npm ci
COPY tsconfig.json ./
COPY src ./src
RUN npm run build
# Prune devDependencies from node_modules for production
RUN npm prune --production

# Production stage -- only runtime artifacts, no build tools
FROM node:20-alpine AS production
# Run as non-root user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
WORKDIR /app
# Copy compiled output and pruned node_modules from builder
COPY --from=builder --chown=appuser:appgroup /app/dist ./dist
COPY --from=builder --chown=appuser:appgroup /app/node_modules ./node_modules
COPY --from=builder --chown=appuser:appgroup /app/package.json ./
USER appuser
EXPOSE 3000
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \
  CMD wget -qO- http://localhost:3000/health || exit 1
CMD ["node", "dist/index.js"]

This produces a final image of approximately 80--120 MB compared to 600+ MB for a naive single-stage build. The non-root USER directive prevents container breakout escalation.


GitHub Actions Pipeline

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.