在 jenkins 声明性管道文件中重用 groovy 脚本

use*_*954 6 jenkins jenkins-pipeline

有没有办法重用在 Jenkinsfile.js 中加载一次的 groovy 脚本。

现在这就是我正在做的

            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()
                }
            }
Run Code Online (Sandbox Code Playgroud)

我在后期构建中再次使用多个脚本块步骤发送邮件。

有一个更好的方法吗?我不能使用共享库

use*_*090 9

是的,您只需要加载脚本一次。

def util = load("${env.WORKSPACE}/scripts/build_util.groovy")
Run Code Online (Sandbox Code Playgroud)

您可以创建一个阶段并在那里加载脚本并存储在一个变量中,然后执行以下操作:-

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()                        
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

您可以在任何阶段使用“ util ”来调用不同的功能。