本文介绍了如何在Jenkins管道中将阶段内的步骤移至函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的Jenkins文件

I have a Jenkinsfile like this

pipeline {
    agent { label 'master' }
    stages {
        stage('1') {
            steps {
                script {
                    sh '''#!/bin/bash
                    source $EXPORT_PATH_SCRIPT
                    cd $SCRIPT_PATH
                    python -m scripts.test.test
                    '''
                }
            }
        }
        stage('2') {
            steps {
                script {
                    sh '''#!/bin/bash
                    source $EXPORT_PATH_SCRIPT
                    cd $SCRIPT_PATH
                    python -m scripts.test.test
                    '''
                }
            }
        }
    }
}

如您所见,在两个阶段中,我都使用相同的脚本并调用相同的文件.我可以将此步骤移至Jenkinsfile中的函数并在脚本中调用该函数吗?像这样

As you can see, In both stages I am using the same script and calling the same file.Can I move this step to a function in Jenkinsfile and call that function in script? like this

def execute script() {
     return {
       sh '''#!/bin/bash
       source $EXPORT_PATH_SCRIPT
       cd $SCRIPT_PATH
       python -m scripts.test.test
       '''  
}
}

推荐答案

是的,可能像下面的示例所示:

Yes, It's possible like below example:

Jenkinsfile

Jenkinsfile

def doIt(name) {
    return "The name is : ${name}"
}

def executeScript() {
    sh "echo HelloWorld"
}

pipeline {
    agent any;
    stages {
        stage('01') {
            steps {
                println doIt("stage 01")
                executeScript()
            }
        }
        stage('02') {
            steps {
                println doIt("stage 02")
                executeScript()
            }
        }
    }
}

这篇关于如何在Jenkins管道中将阶段内的步骤移至函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 14:12