如何在詹金斯管道之间共享阶段

时间:2020-09-28 15:25:39

标签: jenkins jenkins-pipeline jenkins-plugins jenkins-groovy

我有两个要共享相同阶段的JenkinsFile文件:

CommonJenkinsFile:

  pipeline {
  agent {
    node {
      label 'devel-slave'
    }
  }
  stages {
    stage("Select branch") {
              options {
                  timeout(time: 3, unit: 'MINUTES') 
              }
            steps {
                script {
                    env.branchName = input(
                            id: 'userInput', message: 'Enter the name of the branch you want to deploy',
                            parameters: [
                                    string(
                                        defaultValue: '', 
                                        name: 'BranchName',
                                        description: 'Name of the branch'),
                            ]).replaceAll('\\/', '%2F')
                }
            }
        }
}

我要在哪里使用

pipeline {
  agent {
    node {
        label 'devel-slave'
    }
  }
  load 'CommonJenkinsFile'
  stages {
        stage('Deploy to test') {
}
}

如何共享这些阶段?我应该更改为脚本管道吗?他们可以共享阶段还是只能共享步骤?

1 个答案:

答案 0 :(得分:0)

CommonJenkinsfile不能包含管道指令(否则,您正在管道中执行管道)。我认为您还需要将其移至脚本语法而不是声明式语法(可能在此处出错)

此文件可能如下所示:

def commonStep(){
    node('devel-slave'){
        stage("Select branch") {
            timeout(time: 3, unit: 'MINUTES'){
                env.branchName = input ...
            }
        }
    }
}

return this

然后您可以像这样加载它

stage('common step'){
    script{
        def sharedSteps = load "$workspace/common.groovy"
        sharedSteps.commonStep()
    }
}