Get git branch name in Jenkins Pipeline/Jenkinsfile

前端 未结 7 1324
借酒劲吻你
借酒劲吻你 2020-12-13 08:06

I\'ve create a jenkins pipeline and it is pulling the pipeline script from scm.
I set the branch specifier to \'all\', so it builds on any change to any bra

相关标签:
7条回答
  • 2020-12-13 08:51

    If you have a jenkinsfile for your pipeline, check if you see at execution time your branch name in your environment variables.

    You can print them with:

    pipeline {
        agent any
    
        environment {
            DISABLE_AUTH = 'true'
            DB_ENGINE    = 'sqlite'
        }
    
        stages {
            stage('Build') {
                steps {
                    sh 'printenv'
                }
            }
        }
    }
    

    However, PR 91 shows that the branch name is only set in certain pipeline configurations:

    • Branch Conditional (see this groovy script)
    • parallel branches pipeline (as seen by the OP)
    0 讨论(0)
  • 2020-12-13 08:51

    For me this worked: (using Jenkins 2.150, using simple Pipeline type - not multibranch, my branch specifier: '**')

    echo 'Pulling... ' + env.GIT_BRANCH
    

    Output:

    Pulling... origin/myBranch
    

    where myBranch is the name of the feature branch

    0 讨论(0)
  • 2020-12-13 08:52

    This is for simple Pipeline type - not multibranch. Using Jenkins 2.150.1

    environment { FULL_PATH_BRANCH = "${sh(script:'git name-rev --name-only HEAD', returnStdout: true)}" GIT_BRANCH = FULL_PATH_BRANCH.substring(FULL_PATH_BRANCH.lastIndexOf('/') + 1, FULL_PATH_BRANCH.length()) }

    then use it env.GIT_BRANCH

    0 讨论(0)
  • 2020-12-13 08:53

    Switching to a multibranch pipeline allowed me to access the branch name. A regular pipeline was not advised.

    0 讨论(0)
  • 2020-12-13 08:54

    A colleague told me to use scm.branches[0].name and it worked. I wrapped it to a function in my Jenkinsfile:

    def getGitBranchName() {
        return scm.branches[0].name
    }
    
    0 讨论(0)
  • 2020-12-13 09:04

    Use multibranch pipeline.. not pipeline

    In my script..

    stage('Build') {
        node {
            echo 'Pulling...' + env.BRANCH_NAME
            checkout scm
    
        }
    }
    

    Yields...

    Pulling...master
    
    0 讨论(0)
提交回复
热议问题