Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override a Jenkinsfile library function locally?

I have a standardized declarative Jenkinsfile used in many projects. I have moved the entire pipeline into a library, so my Jenkinsfile looks like this:

@Library('default_jenkins_libs') _
default_pipeline();

The library (var/default_pipeline.groovy):

def call() {
pipeline {
  node { <snip> }
  stages {
    stage('Lint and style') {
      steps {
      //stuff
      }
    }
    //etc...
    stage('Post-build') {
      steps {
        PostBuildStep();
      }
    }
  }
}

def PostBuildStep() {
  echo 'Running default post-build step';
}

I want to be able to add a definition to the actual pipeline code in the Jenkinsfile, like so:

@Library('default_jenkins_libs') _

def PostBuildStep() {
  echo 'Running customized post-build step'
  //do custom stuff
}

default_pipeline();

I have not been able to figure out how to do this. I've suspect this may be doable by the library calling the object represented by the Jenkinsfile and calling its "PostBuildStep()", maybe like 'parent.PostBuildStep()" but I do not have the class structure/naming reference.

Any suggestions? Bottom line is, I want a standardized pipeline that is changeable en masse via a library change, but still give some control to jobs that use it.

TIA

like image 770
Mike Rysanek Avatar asked Feb 10 '18 18:02

Mike Rysanek


1 Answers

You cannot override a function defined inside library script. But you can consider defining custom post build step as a closure passed to default_pipeline(). Consider following example:

vars/default_pipeline.groovy

def call(body = null) {
    pipeline {
        agent any
        stages {
            stage('Build') {
                steps {
                    script {
                        body != null ? body() : PostBuildStep()
                    }
                }
            }
        }
    }
}

def PostBuildStep() {
    echo 'Running default post-build step';
}

Jenkinsfile

@Library('default_jenkins_libs') _

default_pipeline({
    echo 'Running customized post-build step'
})

In this case default_pipeline has a single optional parameter that is a closure that defines your custom post build step. Running following example will produce following output:

[Pipeline] node
Running on Jenkins in /var/jenkins_home/workspace/test-pipeline
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Build)
[Pipeline] script
[Pipeline] {
[Pipeline] echo
Running customized post-build step
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

Hope it helps.

like image 195
Szymon Stepniak Avatar answered Sep 29 '22 20:09

Szymon Stepniak