使用多分支流水线时减少 Jenkinsfile 中的阶段

时间:2021-05-09 02:09:41

标签: jenkins continuous-integration jenkins-pipeline jenkins-plugins jenkins-job-dsl

在这个 Jenkinsfile 中,我试图为多分支管道中的不同分支执行相同的阶段。我每次都需要配置每个分支名称的环境变量。有没有更好的方法来做到这一点?

        stage('Create New AMI for master branch') {
            when { branch 'master' }
            environment {
                BRANCH_NAME = "${env.BRANCH_NAME}"
                ENV_NAME = "prod"
            }
            steps {
                sh "packer build jenkins/${PROJECT_NAME}/${PROJECT_NAME}-ami.json"
            }
        }
        stage('Create New AMI for development branch') {
            when { branch 'development' }
            environment {
                BRANCH_NAME = "${env.BRANCH_NAME}"
                ENV_NAME = "dev"
            }
            steps {
                sh "packer build jenkins/${PROJECT_NAME}/${PROJECT_NAME}-ami.json"
            }
        }
        stage('Create New AMI for staging branch') {
            when { branch 'staging' }
            environment {
                BRANCH_NAME = "${env.BRANCH_NAME}"
                ENV_NAME = "staging"
            }
            steps {
                sh "packer build jenkins/${PROJECT_NAME}/${PROJECT_NAME}-ami.json"
            }
        }

1 个答案:

答案 0 :(得分:0)

在这种情况下,请使用共享库,其中将包含您所有的阶段实现。参考示例实现如下所示。
创建一个名为:sharedlibraries(groovy 文件)的文件

#!groovy
// Write or add Functions(definations of stages) which will be called from your jenkins file
def Create_AMI(PROJECT_NAME, ENV_NAME)
 {
     echo ENV_NAME
     sh "packer build jenkins/${PROJECT_NAME}/${PROJECT_NAME}-ami.json"
     // You can also set the environment below example:
     env.ENV_NAME ="dev"
 }

return this

在您的 Jenkinsfile 中写入以下代码:

// Global variable is used to get data from groovy file(shared library)
def stagelibrary
stage('Create New AMI') {   
            steps {
              script {
                        // Load Shared library Groovy file stagelibraries.Give your path of stagelibraries file whic is created
                        stagelibrary = load 'C:\\Jenkins\\stagelibraries'
                        // Execute Create_AMI function. You can add if else conditions over here, based on your branches. But am not sure of your conditions.
                        // You can also pass your environment variable 
                        // in the Crete_AMI function using env.<YOURENVVARIABLE>
                        stagelibrary.Create_AMI(PROJECT_NAME,env.ENV_NAME)       
                      }               
                  }
        }

以上示例旨在提供共享库的概览,您无需编写相同的函数/或冗余阶段。