Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have a reusable "post" block for my Jenkins pipelines?

I have many Jenkins pipelines for several different platforms but my "post{}" block for all those pipelines is pretty samey. And it's quite large at this point because I include success, unstable, failure and aborted in it.

Is there a way to parameterize a reusable post{} block I can import in all my pipelines? I'd like to be able to import it and pass it params as well (because while it's almost the same it varies very slightly for different pipelines).

Example post block that is currently copy and pasted inside all my pipeline{}s

post {
    success{
        script {
            // I'd like to be able to pass in values for param1 and param2
            someGroovyScript {
                param1 = 'blah1'
                param2 = 'blah2'
            }
            // maybe id want a conditional here that does something with a passed in param
            if (param3 == 'blah3') {
                echo 'doing something'
            }
        }
    }
    unstable{
        ... you get the idea
    }
    aborted{
        ... you get the idea
    }
    failure{
        ... you get the idea
    }
}

The following does not work:

// in mypipeline.groovy

...
post {
    script {
        myPost{}
    }
}

// in vars/myPost.groovy

def call(body) {

    def config = [:]
    body.resolveStrategy = Closure.DELEGATE_FIRST
    body.delegate = config
    body()

    return always {
        echo 'test'
    }
}

Invalid condition "myPost" - valid conditions are [always, changed, fixed, regression, aborted, success, unstable, failure, notBuilt, cleanup]

Can I override post{} somehow or something?

like image 213
red888 Avatar asked Oct 26 '25 23:10

red888


1 Answers

Shared libraries is one approach for this, you were pretty close.

@Library('my-shared-library')_
pipeline {
...
    post {
        always {
            script {
                myPost()
            }
        }
    }
}
  • Answer based on https://stackoverflow.com/a/48563538/1783362
  • Shared Libraries link: https://jenkins.io/doc/book/pipeline/shared-libraries/
like image 86
Adam Erstelle Avatar answered Oct 28 '25 19:10

Adam Erstelle