获取触发 Jenkins 构建的 Git 分支名称

Get Git Branch Name that Triggered Jenkins Build

我有一个 Jenkins 文件和一个 Git 钩子,只要在任何分支中提交代码,它就会触发 Jenkins 构建。

我希望打印触发 Jenkins 构建的分支名称。

在下面的 checkout 阶段,我尝试打印分支名称,但它为 println git_params["GIT_BRANCH"] 打印“Null”,而不是提交代码并触发 Jenkins 构建的分支名称。

pipeline {
  agent any

  environment {
    GIT_CRED_ID = 'SVC-JENKINS-ADM'

    GIT_REPO = 'https://bitbucket.hmc.com/scm/mh/docker.git'
  }

  stages {
    stage('checkout') {
      steps {
        script {
          def git_params = checkout([$class: 'GitSCM'])

          println(git_params)

          println 'Getting current Branch'

          println git_params['GIT_BRANCH']
        }
      }
    }

    stage('DEV') {
      agent any

      steps {
        script {
          timeout(time: 25, unit: 'MINUTES') {
            waitUntil {
              try {
                node() {
                  timestamps {
                    task 'Build Environment Setup'
                    //Loading  environment variables
                    checkout([
                      $class: 'GitSCM',
                      branches: [
                        [name: '*/develop']
                      ],
                      [$class: 'WipeWorkspace'],
                    ],
                      userRemoteConfigs: [[credentialsId: env.GIT_CRED_ID, url: env.GIT_REPO]]
                    )
                    dir('temp1') {
                      checkout([
                        $class: 'GitSCM',
                        branches: [
                          [name: '*/master']
                        ],
                        userRemoteConfigs: [[credentialsId: env.GIT_CRED_ID, url: env.GIT_REPO]]
                      ])
                    }
                    load "temp1/${APP_NAME}_${env.ENV}_EnvFile"
                    env.APP_VERSION = sh(script: 'temp1/git_version.sh', returnStdout: true).toString().trim()
                    sh 'echo REL#=$APP_VERSION'
                  }
                }

                emailext attachLog: true, body: "PIPELINE SUCCESS - ${JOB_URL}  \n  Check the full log here", subject: "PIPELINE SUCCESS - ${env.ENV.toUpperCase()} - ${currentBuild.fullDisplayName}", recipientProviders: [developers(), requestor()], to: "$EMAIL_DEPLOYERS"

                return true
              }

              catch (error) {
                echo "Failed in stage : ${env.ENV.toUpperCase()}"

                emailext attachLog: true, body: "PIPELINE FAILED - ${JOB_URL}  \n  Check the full log here", subject: "PIPELINE FAILED - ${env.ENV.toUpperCase()} - ${currentBuild.fullDisplayName}", to: "$EMAIL_DEPLOYERS"

                throw error

                return false

                System.exit(0)
              }
            }
          }
        }
      }
    }
  }
}

注意:在调试日志中打印了分支名称,但我无法显式使用 println git_params["GIT_BRANCH"] 打印它。

你能推荐一下吗?

你试过像这样使用GIT_BRANCH吗

println GIT_BRANCH

GIT_BRANCH 作为内置环境变量注入