©Code by Samnoon
Blog
← All posts

Jenkins + Ansible

Jenkins pipeline tips that keep builds boring

Timeouts, credentials, parallel stages, approvals and the linter: the small Jenkinsfile habits that keep pipelines fast and boring.

7 min readPart 1 of 4

A lot of Jenkinsfiles start life as a copy of some other Jenkinsfile. That works until a build hangs for hours on an ssh call that never returns, or a password turns up in a console log, or two builds deploy to staging at once and nobody can say which one won.

None of what follows is clever. It's the kind of thing worth putting in every pipeline before anything else. All examples use declarative syntax; if you're on scripted pipelines the ideas carry over, the syntax doesn't.

Start with an options block

A good first block for any new Jenkinsfile:

Jenkinsfile
pipeline {
  agent { label 'linux' }
 
  options {
    timeout(time: 30, unit: 'MINUTES')
    timestamps()
    disableConcurrentBuilds(abortPrevious: true)
    buildDiscarder(logRotator(numToKeepStr: '30', artifactNumToKeepStr: '5'))
  }
 
  stages {
    // ...
  }
}

timeout matters most. Without it, a build waiting on a network call that never comes back holds an executor until someone notices. Set it a bit above your slowest normal run, not at some huge number "to be safe".

timestamps() comes from the Timestamper plugin and prefixes every log line with the time. You'll want it the first time you're trying to work out which step ate four minutes.

disableConcurrentBuilds(abortPrevious: true) cancels the running build when a new commit lands on the same branch. Great for PR builds. For deploy jobs, the plain disableConcurrentBuilds() is usually safer: it queues the new build instead of killing one that might be halfway through a deploy.

buildDiscarder stops the controller's disk from slowly filling with years of logs and artifacts. It's boring until the disk is full.

Put timeouts on the risky steps too

The pipeline-wide timeout is a safety net. Steps that talk to the network deserve their own, tighter one:

stage('Integration tests') {
  steps {
    timeout(time: 10, unit: 'MINUTES') {
      sh './run-integration-tests.sh'
    }
  }
}

For things that fail for dull reasons, like a package mirror having a bad minute, add retry:

retry(3) {
  sh 'pip install -r requirements.txt'
}

Please don't wrap your tests in retry, though. A test that passes on the third attempt is a flaky test that nobody will ever look at again.

Keep secrets out of Groovy strings

Jenkins won't stop you doing this:

withCredentials([usernamePassword(credentialsId: 'nexus-deploy',
                                  usernameVariable: 'NEXUS_USER',
                                  passwordVariable: 'NEXUS_PASS')]) {
  // Wrong: Groovy builds the string, so the password is baked into the command
  sh "curl -u ${NEXUS_USER}:${NEXUS_PASS} -T app.tar.gz https://nexus.example.com/repo/"
 
  // Right: single quotes, and the shell expands the variables at run time
  sh 'curl -u "$NEXUS_USER:$NEXUS_PASS" -T app.tar.gz https://nexus.example.com/repo/'
}

With double quotes, Groovy interpolates the values before the sh step ever runs, and the secret becomes part of the command Jenkins records. The Jenkins handbook is blunt about it: Groovy string interpolation should never be used with credentials. Recent versions print a warning in the console log when they catch it happening, mentioning "Groovy String interpolation", so searching your build logs for that phrase is a quick way to find every pipeline that needs fixing.

The same rule applies to the environment shortcut. NEXUS = credentials('nexus-deploy') gives you NEXUS_USR and NEXUS_PSW, and they belong inside single quotes too.

Skip stages early with when

stage('Deploy to staging') {
  when {
    branch 'main'
    beforeAgent true
  }
  agent { label 'deploy' }
  steps {
    sh './deploy.sh staging'
  }
}

beforeAgent true makes Jenkins check the condition before it grabs an agent for the stage. Without it, a feature-branch build can sit in the queue waiting for a free deploy agent only to find out it had nothing to do.

In a monorepo, changeset saves a lot of pointless builds:

when { changeset 'docs/**' }

Move files between agents with stash

If you build on one agent and test on another, stash and unstash carry files across without an artifact repository:

stage('Build') {
  agent { label 'linux' }
  steps {
    sh 'make release'
    stash name: 'bin', includes: 'build/release/**'
  }
}
stage('Test on target') {
  agent { label 'arm64' }
  steps {
    unstash 'bin'
    sh './run-tests.sh build/release'
  }
}

Stashes travel through the controller and are meant for small files. A few megabytes of binaries is fine. A 2 GB build context is not, and your controller will tell you so in the least helpful way possible. Push big things to a registry instead.

Run checks in parallel, and fail fast

stage('Checks') {
  failFast true
  parallel {
    stage('Unit')   { steps { sh 'make test' } }
    stage('Lint')   { steps { sh 'make lint' } }
    stage('cppcheck') { steps { sh 'cppcheck --error-exitcode=1 src/' } }
  }
}

failFast true aborts the other branches as soon as one fails, so you hear about the lint error in 30 seconds rather than after the full test run. If you want that behavior everywhere, parallelsAlwaysFailFast() goes in the options block.

One trap: parallel stages without their own agent share the parent's workspace. Two branches both writing to build/ will trample each other and fail in ways that make no sense. Give each branch its own agent or its own output directory.

Approvals that don't hold an executor

input pauses a pipeline until someone clicks a button. Used naively, it waits forever and keeps an agent busy the whole time. Declare agent none at the top, let each stage pick its own agent, and use the stage-level input directive:

Jenkinsfile
pipeline {
  agent none
 
  stages {
    stage('Build') {
      agent { label 'linux' }
      steps { sh 'make release' }
    }
 
    stage('Deploy to production') {
      options { timeout(time: 4, unit: 'HOURS') }
      input {
        message 'Deploy to production?'
        ok 'Ship it'
        submitter 'release-managers'
      }
      agent { label 'deploy' }
      steps { sh './deploy.sh production' }
    }
  }
}

The input directive is evaluated before Jenkins allocates the stage's agent, so nothing sits idle while the approver is at lunch. The stage timeout covers the wait as well. If nobody answers in four hours the build aborts instead of hanging around for a week, and submitter limits who's allowed to click "Ship it".

Use post, and clean up after yourself

post {
  always {
    junit allowEmptyResults: true, testResults: 'reports/**/*.xml'
  }
  failure {
    mail to: 'team@example.com',
         subject: "Failed: ${env.JOB_NAME} #${env.BUILD_NUMBER}",
         body: env.BUILD_URL
  }
  cleanup {
    cleanWs()
  }
}

cleanup runs last, after every other post condition, whatever the result. cleanWs() (from the Workspace Cleanup plugin) wipes the workspace so the next build doesn't pick up leftovers from this one. Stale files in a reused workspace cause some of the most confusing build failures there are.

Lock shared environments

If two pipelines can deploy to the same staging servers, make them take turns. The Lockable Resources plugin does this in one line:

stage('Deploy to staging') {
  options { lock('staging-env') }
  steps { sh './deploy.sh staging' }
}

The second pipeline waits at that stage until the first one is done with it, instead of both running Ansible against the same hosts at the same moment.

Lint the Jenkinsfile before you push

Pushing a commit to find out your Jenkinsfile has a missing brace is a slow way to work. Jenkins will validate declarative syntax over HTTP:

curl --user "$JENKINS_USER:$JENKINS_TOKEN" -X POST \
  -F "jenkinsfile=<Jenkinsfile" \
  "$JENKINS_URL/pipeline-model-converter/validate"

It only checks structure (unknown directives, missing sections, bad nesting), not whether your shell commands work. Still, put it in a pre-commit hook and the "fix jenkinsfile" commits mostly go away.

When a build fails because of the pipeline code itself, the Replay button on the build page lets you edit the Jenkinsfile in the browser and rerun it without committing. Just remember to copy the fix back into Git. Replay doesn't save anything.

Keep the Groovy thin

Pipeline Groovy runs on the controller, not the agent. Every readJSON, every loop over a long list, every bit of string wrangling in a script block uses the controller's CPU and memory. And because pipelines are built to survive restarts, that Groovy runs through a transformation that makes it noticeably slower than plain Groovy.

So push the work down into sh and bring back only the answer. Instead of parsing the whole file on the controller:

def version = readJSON(file: 'build/manifest.json').components[0].version

let the agent do it and hand back one short string:

def version = sh(script: "jq -r '.components[0].version' build/manifest.json",
                 returnStdout: true).trim()

A reasonable rule of thumb: when a script block grows past a dozen lines, it wants to be a shell script in the repo or a step in a shared library.

References

#jenkins #ci-cd