gitjenkinsbranchjenkins-pipeline

Get git branch name in Jenkins Pipeline/Jenkinsfile


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 branch.

How do I access the branch name causing this build from the Jenkinsfile?

Everything I have tried echos out null except

sh(returnStdout: true, script: 'git rev-parse --abbrev-ref HEAD').trim()

which is always master.


Solution

  • 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: