Reputation: 586
Is there a way to reuse groovy script loaded once in Jenkinsfile.
Right now this is what I am doing
steps {
script {
def util = load("${env.WORKSPACE}/scripts/build_util.groovy")
util.runStep1()
}
}
steps {
script {
def util = load("${env.WORKSPACE}/scripts/build_util.groovy")
util.runStep2()
}
}
steps {
script {
def util = load("${env.WORKSPACE}/scripts/build_util.groovy")
util.runStep3()
}
}
I am doing the same again in post build with multiple script blocks step to send mails.
Is there a better way to do this? I cannot use shared libraries.
Upvotes: 8
Views: 15017
Reputation: 1974
Yes, you just need to load the script only once.
def util = load("${env.WORKSPACE}/scripts/build_util.groovy")
You can create a stage and load the script there and store in a variable and then do something like this:-
stage('Environment') {
agent { node { label 'master' } }
steps {
script {
def util = load("${env.WORKSPACE}/scripts/build_util.groovy")
}
}
}
post {
// Things that we want done regardless of pipeline's outcome
//
always {
// Push the overall statistics from all the stages to InfluxDB
//
node (LINUX_BUILD_NODE){
script{
//Mail sending function call
//
util.runStep1()
util.runStep2()
util.runStep3()
}
}
}
}
You can use "util" in any stage to call the different functions.
Upvotes: 11
Reputation: 13712
You can declare the variable util
at top level, then assign value to it in the first stage, after than you can use it in any stage.
def util;
pipeline {
agent any
stages {
stage('one') {
steps {
script {
util = load("${env.WORKSPACE}/scripts/build_util.groovy")
util.runStep1()
}
}
}
post {
util.xxxx
}
stage('two') {
steps {
script {
util = load("${env.WORKSPACE}/scripts/build_util.groovy")
util.runStep2()
}
}
}
post {
util.xxxx
}
}
post {
util.xxxx
}
}
Upvotes: 1