·9 min read

Understanding Jenkins - Simplifying the Complexities

A practical guide to understanding Jenkins, CI/CD fundamentals, pipelines, testing, security, and useful tools.

Jenkins is still the workhorse of CI/CD in a lot of shops, especially anywhere you need full control over the build environment or you're stuck on-prem for compliance reasons. GitHub Actions and GitLab CI cover most hosted use cases just fine, but Jenkins keeps showing up wherever the build is multi-platform, the secrets are sensitive, or the auditors are involved.

This is the working set of patterns I lean on when building Jenkins pipelines that don't fall over: CI validation, deployment, security scanning, and the operational bits that matter once more than one team is using it.


What is Jenkins?

Jenkins is an open-source automation server. You give it a pipeline (as code, in a Jenkinsfile), it runs that pipeline on agents, and it keeps a record of every run. Build, test, scan, deploy: all the same mechanism.


Continuous Integration (CI)

CI means every change gets validated against the mainline before it lands. In practice: a webhook from GitHub/GitLab hits Jenkins, Jenkins runs tests, static analysis, and a security scan, and the PR gets a red or green check. If broken code can merge without a red check, you don't have CI, you have a build server.

Testing Strategy

A CI pipeline should validate code at more than one level:

  • Unit tests: fast, isolated (JUnit, pytest, Jest).
  • Integration tests: services talking to real databases, queues, and APIs.
  • Contract tests: API compatibility between microservices (Pact, Spring Cloud Contract). Worth it once you have more than a handful of services owned by different teams.

Publish test results with the JUnit plugin so you get per-test history and trends:

post {
  always {
    junit allowEmptyResults: false, testResults: '**/target/surefire-reports/*.xml'
  }
}

Two things that catch people:

  • Put it in post { always }, not in a stage. If the test step fails the stage, anything after it in that stage never runs and you lose the report exactly when you need it.
  • When junit finds failing tests it marks the build UNSTABLE (yellow), not FAILURE. If your merge check treats yellow as passing, failing tests can merge. Decide which one you want and make the PR status match.

Static Analysis and Quality Gates

I use SonarQube for anything beyond basic linting: coverage, duplication, code smells, and security hotspots (hardcoded credentials, injection patterns).

The part that matters is the quality gate, and it should be on new code, not the whole codebase. Block merges when a change introduces blocker/critical issues or drops coverage on the lines it touched. Existing tech debt gets paid down over time. If you gate on the whole codebase on day one, everything is red, and people learn to ignore red.

With the SonarQube Scanner plugin, the pipeline waits for the gate result like this:

stage('SonarQube') {
  steps {
    withSonarQubeEnv('sonar') {
      sh 'mvn sonar:sonar'
    }
  }
}
stage('Quality Gate') {
  steps {
    timeout(time: 10, unit: 'MINUTES') {
      waitForQualityGate abortPipeline: true
    }
  }
}

waitForQualityGate depends on a webhook from SonarQube back to Jenkins (https://<jenkins>/sonarqube-webhook/). Without it the step just sits there until the timeout. That's why the timeout wrapper is not optional.

Other CI Tools

For context: GitHub Actions, GitLab CI, and CircleCI all do CI well, and for a small team on a hosted Git provider I'd usually start there. Jenkins wins when you need your own agents, unusual hardware, or everything to stay inside your network.


Continuous Delivery (CD)

CD keeps the main branch deployable at all times and automates promotion through environments, while production stays under control.

Deployment Patterns

Blue-green: two identical production environments. Deploy to the idle one, validate, switch traffic. Rollback is switching back. Costs double the capacity during the switch.

Canary: send a small slice of traffic (5-10%) to the new version first. Watch error rate and latency, roll back automatically if they degrade. Only works if you actually have metrics good enough to make that call.

Feature flags: ship the code dark and turn features on per user or environment without redeploying. Separates "deployed" from "released".

Jenkins CD Integrations

  • Kubernetes + Helm: Jenkins runs helm upgrade --install with a versioned chart.
  • ArgoCD: GitOps. Jenkins builds the image and bumps the tag in Git, ArgoCD syncs the cluster.
  • Terraform: infrastructure (databases, networks, load balancers) before the app.
  • Ansible: configuration for VM-based deployments.

The pattern I prefer: Jenkins builds and tests, pushes the image to the registry, updates the image tag in the deployment repo, and ArgoCD deploys from Git. Jenkins never holds cluster-admin credentials, and the cluster state lives in Git, not in someone's last build log.


Shift-Left Security with Trivy

Security scanning has to happen before deployment, not after. Trivy scans container images, IaC, and dependency manifests for known CVEs and misconfigurations. Why I use it: one binary covers OS packages, app dependencies, and IaC; it has proper exit codes, JSON output, and severity filters, so it drops into a pipeline without glue code; and it's fast once the vulnerability DB is cached.

Production Implementation

stage('Security Scan') {
  steps {
    // Fail on HIGH and CRITICAL, skip CVEs that have no fix yet
    sh '''
      trivy image --exit-code 1 --severity HIGH,CRITICAL \
        --ignore-unfixed \
        --format json --output trivy-report.json \
        my-app:${BUILD_NUMBER}
    '''
  }
  post {
    always {
      archiveArtifacts artifacts: 'trivy-report.json', allowEmptyArchive: true
    }
  }
}

Notes:

  • --exit-code 1 is what actually fails the build. Without it Trivy prints the vulnerabilities and exits 0.
  • Archive the report in post { always }. If you put archiveArtifacts right after the sh step, it never runs when Trivy fails, which is the one time you want the report.
  • --ignore-unfixed is a judgment call. Without it you'll block builds on CVEs nobody can fix yet. With it, you need some other process that keeps an eye on them.
  • For accepted risks, use a .trivyignore file in the repo with a comment per CVE explaining why. Not || true on the whole command.
  • In regulated environments, feed the JSON into whatever tracks remediation (Jira, ServiceNow) so findings turn into tickets with owners.

Jenkins Pipelines

Pipelines are Groovy code in a Jenkinsfile, versioned next to the app. Two flavors:

  • Declarative: structured pipeline { } syntax. Covers most cases, easier to read, better error messages.
  • Scripted: plain Groovy, full control.

I start everything declarative and drop into a script { } block only where I really need logic. If a Jenkinsfile is mostly script blocks, that logic probably belongs in a shared library or a shell script.

Declarative Pipeline Example

pipeline {
  agent any
  stages {
    stage('Install') {
      steps {
        sh 'npm ci'
      }
    }
    stage('Lint') {
      steps {
        sh 'npm run lint'
      }
    }
    stage('Unit Test') {
      steps {
        sh 'npm test'
      }
    }
    stage('Security Scan') {
      steps {
        sh 'trivy image --exit-code 1 --severity HIGH,CRITICAL my-app:${BUILD_NUMBER}'
      }
    }
    stage('Deploy') {
      when { branch 'main' }
      steps {
        sh './deploy.sh'
      }
    }
  }
}

npm ci instead of npm install because it installs exactly what's in the lockfile and fails if the lockfile is out of sync. when { branch 'main' } keeps feature branches from deploying (it works in multibranch pipelines, where Jenkins knows the branch name).


Key Concepts in Jenkins

ConceptDescription
JobsTasks Jenkins performs (build, test, deploy).
BuildsEach execution of a job.
AgentsWhere the work happens (Jenkins workers). The controller should not run builds itself.
PluginsJenkins' superpower, and its biggest maintenance burden.
ArtifactsBuild outputs that can be passed to later stages.

Example Jenkins Workflow

  1. Install Jenkins: locally, on a VM, or in a container.
  2. Configure agents: Kubernetes pod agents, Docker agents, or static VMs. Set the controller's executors to 0.
  3. Create a pipeline job: a multibranch pipeline pointing at a repo with a Jenkinsfile.
  4. Connect the Git repo: add the GitHub or GitLab webhook.
  5. Run jobs: build, test, scan, deploy.
  6. Monitor: test reports, Slack/email notifications. Blue Ocean still works, but it's no longer actively developed, so I wouldn't build habits around it.

Scaling Jenkins in Production

Agent Architecture

  • Static agents: VMs or physical machines that persist between builds. Use them for builds that need expensive setup (big dependency caches, special hardware).
  • Ephemeral agents: Kubernetes pods or Docker containers that spin up per build. Clean environment every time, scale horizontally, no configuration drift.

My default: Kubernetes ephemeral agents for most builds. Keep static agents for builds that really benefit from warm caches (Android/iOS, large monorepos).

Pipeline Performance

Slow pipelines kill productivity. What helps:

  • Parallel stages for independent checks (unit tests, linters, security scans).
  • Dependency caching for node_modules, .m2, pip. On ephemeral agents this means a shared volume or a remote cache, otherwise every build starts cold.
  • Fail fast: cheapest checks first (lint before integration tests).
  • Stash/unstash to pass files between stages without rebuilding. Fine for small things, slow for big ones, because it goes through the controller.
stage('Parallel Tests') {
  failFast true
  parallel {
    stage('Unit')     { steps { sh 'npm run test:unit' } }
    stage('Lint')     { steps { sh 'npm run lint' } }
    stage('Security') { steps { sh 'npm audit --audit-level=high' } }
  }
}

failFast true aborts the other branches as soon as one fails. Without it you wait for the slowest branch just to learn the build is red.

Security Hardening

  • Credentials: never hardcode secrets. Use the Credentials plugin (backed by Vault or AWS Secrets Manager if you have one) and withCredentials. Keep the sh string in single quotes so the shell expands the variable, not Groovy. With double quotes Groovy interpolates the secret into the command line, and Jenkins prints a warning about insecure interpolation in the log.
withCredentials([string(credentialsId: 'registry-token', variable: 'TOKEN')]) {
  sh 'echo "$TOKEN" | docker login -u ci --password-stdin registry.example.com'
}
  • RBAC: developers shouldn't be able to trigger or edit production deployment jobs. Role-based or folder-level permissions, not "everyone is admin".
  • Audit logging: who triggered what, who changed which pipeline, which credentials were used.
  • Plugins: keep them updated and keep the list short. In my experience outdated plugins are the most common Jenkins security problem, and every plugin you install is one more thing to patch.

Monitoring and Observability

Instrument Jenkins so you see problems before the teams do:

  • Prometheus metrics: the Prometheus plugin exposes /prometheus with build durations, queue size, and executor counts.
  • Log aggregation: ship build logs to ELK/Splunk/Loki so you can search across builds.
  • Alerting: notify on-call when critical pipelines fail or the queue keeps growing.

The metric I care about most is lead time (commit to production). If it goes over 30 minutes, go look for the bottleneck in test execution or deployment automation.


A note on how this was written: I used AI to help with phrasing and structure. The tone, the opinions, the war stories, the code, and everything else here are mine.