DevopsIntermediate

CI/CD Pipelines 101: Automating Code Delivery with Jenkins and AWS CodePipeline

DeveloperHat Team
8 min read

TL;DR

Learn how to set up and optimize continuous integration and delivery pipelines using Jenkins and AWS CodePipeline.

Executive Summary

This guide explains how CI/CD pipelines work and how to build one with Jenkins and AWS CodePipeline. Continuous integration merges and tests every change automatically; continuous delivery keeps the built artifact permanently deployable; continuous deployment releases it without a human gate. You will learn the stage model both tools share, how to write a declarative Jenkinsfile, how CodePipeline composes source, build, test, and deploy actions around a CodeBuild buildspec, and how to handle secrets, parallel tests, caching, and failure recovery. After reading it, you should be able to choose between a self-hosted and a managed pipeline and structure one that a team can trust.

Commit git push Build compile + image Test unit + scan Deploy staging → prod Monitor metrics + alerts One change, one pipeline Every stage is a gate: a failure stops the line and notifies the author. Monitoring feeds back into the next commit — the loop never really ends.

Why This Matters

Without a pipeline, quality depends on individual discipline and releases depend on individual availability. Changes batch up, integration problems surface late when they are hardest to attribute, and deployments become events that teams schedule around and dread. A pipeline makes the path to production identical for every change, which is what makes releases boring, auditable, and reversible. It is also a security control: the pipeline is the one sanctioned path by which code reaches production, so credentials, checks, and approvals can be enforced in exactly one place instead of being re-implemented, or skipped, per release.

Core Concepts

CI, Delivery, and Deployment

The three terms describe increasing automation of the same flow. CI ends at a tested artifact. Continuous delivery adds automated deployment to staging and a manual decision for production. Continuous deployment removes that decision, which is only safe when automated verification (tests, canary analysis, automatic rollback) is strong enough to replace it. Most teams should aim for continuous delivery first and earn deployment through evidence.

The pipeline as a stack — the artifact that deploys is the one that was tested Source + trigger — one commit, one pipeline run Build — compile once, the artifact is immutable Test — unit, then integration, then end-to-end; fail fast Deploy — promote the same artifact, per environment Observe — metrics, alerts, and the rollback signal Rebuild at deploy time and the tests prove nothing — the artifact is the unit of trust.

The Jenkins Declarative Model

A Jenkins pipeline is stages of steps executed on agents. The declarative syntax wraps that in a predictable structure with built-in handling for environment, parameters, and post-build actions:

pipeline {
    agent any

    stages {
        stage('Build') {
            steps {
                sh 'npm install'
                sh 'npm run build'
            }
        }

        stage('Test') {
            steps {
                sh 'npm run test'
            }
        }

        stage('Deploy') {
            steps {
                sh './deploy.sh'
            }
        }
    }

    post {
        success {
            echo 'Pipeline succeeded!'
        }
        failure {
            echo 'Pipeline failed!'
        }
    }
}

Use declarative syntax for new pipelines, keep the Jenkinsfile in the repository it builds, and run builds on labelled ephemeral agents so build environments are reproducible and the controller never executes build code itself.

The CodePipeline Stage Model

CodePipeline organises work as stages containing actions, with artifacts flowing between them. A typical arrangement is: a source action (CodeCommit or GitHub) that emits the repository; a build action running CodeBuild; a test action (another CodeBuild project or a testing provider); and deploy actions targeting ECS, Elastic Beanstalk, S3, or CloudFormation, separated by environment with approval actions before production. CodeBuild behaviour lives in the buildspec:

version: 0.2

phases:
  install:
    runtime-versions:
      nodejs: 18
    commands:
      - npm install

  build:
    commands:
      - npm run build

  test:
    commands:
      - npm run test

artifacts:
  files:
    - '**/*'
  base-directory: 'build'

Note the discipline the model enforces: the deploy stage consumes the artifact produced earlier in the same execution. Rebuilding inside a deploy action breaks traceability between what was tested and what is running.

Testing Strategy Inside the Pipeline

Order tests by cost and signal. Unit tests run on every commit; integration tests run in the build or a dedicated test stage; end-to-end tests run against a staging deployment and, if slow, on merge rather than on every pull request. Independent suites should run concurrently rather than serially:

stage('Tests') {
    parallel {
        stage('Unit Tests') {
            steps {
                sh 'npm run test:unit'
            }
        }
        stage('Integration Tests') {
            steps {
                sh 'npm run test:integration'
            }
        }
    }
}

Flaky tests are a pipeline defect, not a nuisance: quarantine and fix them, because a suite the team retries reflexively provides no signal at all.

Secrets and Access Control

Bind credentials at the step that needs them and nowhere else. In Jenkins, the credentials store plus withCredentials scopes a secret to a block and masks it in logs; in AWS, IAM roles attached to CodePipeline and CodeBuild replace stored keys entirely:

pipeline {
    environment {
        AWS_CREDENTIALS = credentials('aws-credentials')
    }

    stages {
        stage('Deploy') {
            steps {
                withCredentials([
                    string(credentialsId: 'api-key', variable: 'API_KEY')
                ]) {
                    sh 'deploy.sh'
                }
            }
        }
    }
}

Apply role-based access control to who can create and edit pipelines, because pipeline edit rights are production deploy rights. Rotate credentials on a schedule and audit pipeline changes the way you audit code changes.

Environments and Configuration

Configuration must vary per environment while the artifact does not. Inject environment-specific values at deploy time (environment variables, parameter stores, configuration files rendered per target), and declare the target environment explicitly in the pipeline so a run's destination is never ambiguous:

pipeline {
    environment {
        NODE_ENV = 'production'
        AWS_REGION = 'us-west-2'
    }

    stages {
        stage('Deploy') {
            environment {
                DEPLOY_ENV = 'staging'
            }
            steps {
                // Deploy using environment variables
            }
        }
    }
}

Failure Handling and Observability

Pipelines fail; the design question is how visibly and how recoverably. Wrap fragile steps with explicit error handling that marks the build failed with a useful message rather than a stack trace, publish test and coverage reports as build artefacts, and alert the owning team on failure:

pipeline {
    stages {
        stage('Build') {
            steps {
                script {
                    try {
                        sh 'npm run build'
                    } catch (err) {
                        echo "Build failed: ${err}"
                        currentBuild.result = 'FAILURE'
                        error("Build stage failed")
                    }
                }
            }
        }
    }
}

Track build duration, success rate, deployment frequency, and mean time to restore. A rising build duration is a roadmap item, not background noise: slow pipelines train developers to batch changes and bypass checks.

Self-host or managed? Delivery or deployment? The honest answers are about who patches the fleet — and how strong the tests are. Who owns the build fleet? how strong is verification? Team will own it Jenkins, ephemeral agents AWS-only, small ops CodePipeline + CodeBuild Multi-cloud, no fleet Managed neutral runner Weak verification Delivery + approval gate Continuous deployment is earned with tests and automatic rollback — until then, keep the human gate.

Decision Framework

SituationRecommendation
Need full control over build environment and pluginsJenkins on ephemeral agents
AWS-only estate, minimal operations capacityCodePipeline with CodeBuild
Production change requires a named human decisionContinuous delivery with an approval action, not full deployment
Test stage dominates pipeline durationParallelise suites, cache dependencies, move end-to-end tests post-merge
Secrets currently live in pipeline definitionsMove to a credentials store or IAM roles before anything else
Multiple teams duplicating pipeline logicShared libraries (Jenkins) or standard buildspec templates (AWS)

Implementation Checklist

  • [ ] Pipeline defined as code and versioned with the application
  • [ ] Stages follow source, build, test, artifact, deploy with fail-fast ordering
  • [ ] The artifact deployed to production is bit-identical to the one tested in staging
  • [ ] Unit and integration tests gate the pipeline; flaky tests are quarantined and fixed
  • [ ] Credentials bound per step via a credentials store or IAM roles; nothing secret in pipeline files
  • [ ] Pipeline creation and edit permissions restricted and audited
  • [ ] Environment configuration injected at deploy time, never baked into the artifact
  • [ ] Failure alerts reach the owning team; build duration and success rate are tracked
  • Trade-offs

    Self-hosting Jenkins buys flexibility at the price of operating a critical, credential-rich system: upgrades, plugin compatibility, agent fleets, and backups are yours. CodePipeline removes that work but ties delivery to AWS services and IAM patterns, and its stage model can feel rigid for unusual flows. Both approaches share the fundamental tension: gates reduce risk and add lead time. The correct amount of pipeline is determined by the failures you have actually had, reviewed regularly, rather than by a template copied from a larger company.

    When Not to Use

  • CodePipeline outside an AWS estate: its value is integration with AWS deploy targets; multi-cloud delivery belongs on Jenkins or a neutral platform.
  • Jenkins when nobody will own it: an unpatched, plugin-rotted controller is a liability worse than a managed service's constraints.
  • Continuous deployment for systems with weak automated verification: without trustworthy tests and automatic rollback, keep a human approval before production.
  • Heavyweight pipelines for trivial projects: a single small service may need three stages and nothing more; ceremony beyond that slows delivery without reducing risk.
  • Conclusion

    Jenkins and CodePipeline are two operating models for the same discipline: build once, test automatically, promote a known artifact, and keep the path to production singular and auditable. Choose based on where your infrastructure and operational capacity live, then invest in the unglamorous parts (test reliability, credential hygiene, build speed) that determine whether the team trusts the pipeline enough to use it for everything.

    References

  • Jenkins Documentation
  • AWS CodePipeline User Guide
  • CI/CD Best Practices
  • Pipeline Security Guidelines
  • Why This Matters

    Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.

    Trade-offs to Consider

    Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.

    When NOT to Use This

    Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.

    Decision Framework

    Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.

    Share this articleShare on XShare on LinkedIn

    Keep the decision frameworks coming

    One practical architecture guide a week — patterns, trade-offs, and when not to use them. No spam, unsubscribe anytime.