©Code by Samnoon
Blog
← All posts

Jenkins + Ansible

Jenkins shared libraries: stop copy-pasting Jenkinsfiles

When ten repos carry the same 200-line Jenkinsfile, it's time for a versioned library. Layout, vars vs src, pinning and testing.

4 min readPart 2 of 4

Every team with more than a handful of repos ends up with the same Jenkinsfile in all of them. Each copy drifts a little. Someone fixes a bug in one and not in the other nine. Then the deploy step has to change everywhere, and you lose an afternoon to a stack of identical pull requests.

Shared libraries fix this by moving pipeline code into its own Git repository, which every Jenkinsfile then loads by name.

What goes where

jenkins-lib/
├── vars/
│   ├── standardPipeline.groovy
│   └── deployWithAnsible.groovy
├── src/
│   └── com/example/ci/Versions.groovy
└── resources/
    └── com/example/ci/ansible.cfg

vars/ holds global steps. A file called deployWithAnsible.groovy with a call method becomes a step called deployWithAnsible in every pipeline that loads the library. This is where most of the value is.

src/ is plain Groovy classes on the classpath, imported like any other package. Handy for real logic, but remember that all of it runs on the controller, under the same restrictions as pipeline code. Keep it small.

resources/ holds non-Groovy files (config templates, scripts) that the library reads with libraryResource.

In practice, most shared libraries end up almost entirely vars/.

A first shared step

vars/deployWithAnsible.groovy
def call(Map config) {
  def inventory = config.inventory ?: error('deployWithAnsible: inventory is required')
  def playbook  = config.playbook ?: 'site.yml'
  def limit     = config.limit ? "--limit '${config.limit}'" : ''
 
  withCredentials([sshUserPrivateKey(credentialsId: config.sshKey ?: 'deploy-ssh',
                                     keyFileVariable: 'SSH_KEY')]) {
    sh """
      ansible-playbook -i '${inventory}' ${limit} \
        --private-key "\$SSH_KEY" '${playbook}'
    """
  }
}

The triple-quoted string is a Groovy GString, so inventory and playbook get filled in by Groovy. The key path is escaped as \$SSH_KEY so the shell expands it instead, for the same reason as in the pipeline tips post: anything that came out of withCredentials should never pass through Groovy interpolation.

Using it from a repo:

Jenkinsfile
@Library('jenkins-lib@v1.4.0') _
 
pipeline {
  agent { label 'deploy' }
  stages {
    stage('Deploy') {
      steps {
        deployWithAnsible inventory: 'inventories/staging', limit: 'web'
      }
    }
  }
}

The lonely _ after the annotation is there because a Groovy annotation needs something to attach to. It looks like a typo the first time you see it, and everyone asks.

A whole pipeline as one step

Once the steps are shared, the next move is sharing the pipeline itself. A vars/ file can contain an entire declarative pipeline block:

vars/standardPipeline.groovy
def call(Map config = [:]) {
  def agentLabel = config.agent ?: 'linux'
  def minutes    = config.timeoutMinutes ?: 30
 
  pipeline {
    agent { label "${agentLabel}" }
    options {
      timeout(time: minutes, unit: 'MINUTES')
      timestamps()
      disableConcurrentBuilds(abortPrevious: true)
    }
    stages {
      stage('Build') {
        steps { sh config.buildCommand ?: 'make' }
      }
      stage('Test') {
        steps { sh config.testCommand ?: 'make test' }
      }
      stage('Deploy') {
        when { branch 'main' }
        steps { deployWithAnsible inventory: config.inventory }
      }
    }
    post {
      cleanup { cleanWs() }
    }
  }
}

And each repo's Jenkinsfile shrinks to this:

Jenkinsfile
@Library('jenkins-lib@v1.4.0') _
 
standardPipeline(
  buildCommand: './build.sh',
  testCommand: './run-tests.sh',
  inventory: 'inventories/staging'
)

Ten repos, ten tiny Jenkinsfiles, one place to fix things.

The price is flexibility. A repo that needs one extra stage either gets a new config option or opts out of the standard pipeline. Config options are tempting, and that road ends with a 40-key map that nobody can reason about. It's usually better to keep the standard pipeline small and let the odd repo write its own Jenkinsfile out of the shared steps.

Pin the version

@Library('jenkins-lib') with no version loads whatever the library's default branch looks like right now. So one bad merge to the library breaks every pipeline at once, including ones nobody has touched in months, and you find out from a flood of red builds.

Tag releases and pin them: @Library('jenkins-lib@v1.4.0') _. Upgrading becomes a normal one-line change in each repo, and you can test it in a pull request like anything else. For the @version syntax to work, the library's configuration (Manage Jenkins → System → Global Pipeline Libraries, labelled Global Trusted Pipeline Libraries in some versions) needs "Allow default version to be overridden" ticked.

That same setting lets you try a library branch from one repo without affecting anyone else. Point a throwaway branch's Jenkinsfile at @Library('jenkins-lib@feature/new-deploy') _ and run it.

Trusted means trusted

Libraries configured globally by an admin run outside the Groovy sandbox. They can do anything the controller can do, which includes reading every credential stored in Jenkins. Treat the library repo like production code: protected main branch, required reviews, and a short list of people who can merge.

Testing it

JenkinsPipelineUnit runs vars/ scripts in plain unit tests with the pipeline steps mocked out:

test/DeployWithAnsibleTest.groovy
import com.lesfurets.jenkins.unit.BasePipelineTest
import org.junit.Before
import org.junit.Test
 
import static org.junit.Assert.assertTrue
 
class DeployWithAnsibleTest extends BasePipelineTest {
 
  @Before
  void setUp() {
    super.setUp()
    helper.registerAllowedMethod('sshUserPrivateKey', [Map]) { it }
    helper.registerAllowedMethod('withCredentials', [List, Closure]) { creds, body -> body() }
  }
 
  @Test
  void passesTheLimitToAnsible() {
    def step = loadScript('vars/deployWithAnsible.groovy')
    step.call(inventory: 'inventories/staging', limit: 'web')
 
    assertTrue(helper.callStack.any {
      it.methodName == 'sh' && it.argsToString().contains("--limit 'web'")
    })
  }
}

It won't catch everything. Its support for full declarative pipelines is limited, and it can't tell you whether ansible-playbook will actually succeed. What it does catch is the wrong-argument, missing-parameter, typo-in-a-map-key class of bug before it ships to every repo at once, which is exactly the class of bug a shared library makes expensive.

References

#jenkins #groovy #ci-cd