Search code examples
jenkins-pipelinejenkins-groovygit-checkout

GitHub checkout with environmental variable in Jenkinsfile


In Jenkins, I have a multibranch pipeline job using a Jenkinsfile. I have disabled the default SCM checkout via:

options {skipDefaultCheckout(true)}

so that I can control the checkout for each stage and use the SSH URL from GitHub. I have a working stage that checks out the "main" branch using:

   checkout([
       $class: 'GitSCM', 
       branches: [[name: '*/main']], 
       extensions: [[$class: 'LocalBranch', localBranch: 'main']], 
       userRemoteConfigs: [[credentialsId: 'XXX', url: '[email protected]:XXX.git']]
    ])

For another stage, I would like to checkout and build/test the branch that is triggered (in this case a feature branch called "feature-0001"). I have tried this (note the change for the branches and extensions lines):

 checkout([
       $class: 'GitSCM', 
       branches: [[name: env.BRANCH_NAME]], 
       extensions: [[$class: 'LocalBranch']], 
       userRemoteConfigs: [[credentialsId: XXX, url: '[email protected]:XXX.git']]
    ])

but I get the following error:

Error when executing failure post condition:

java.io.IOException: Cannot retrieve Git metadata for the build

In addition, the build log also has:

git rev-parse "origin/feature-0001^{commit}" # timeout=10

git rev-parse "feature-0001^{commit}" # timeout=10

I'm not sure where the "^{commit}" comes from or if it's causing any issues.

Any guidance would be appreciated, thank you!

P.S. I have also tried many variations of BRANCH_NAME including

$env.BRANCH_NAME, ${env.BRANCH_NAME}, $BRANCH_NAME, ${BRANCH_NAME}

Solution

  • If you want an unambiguous way to reference your branch name in the SCM checkout step, try (as explained here):

    branches: [[name: 'refs/heads/${env.BRANCH_NAME}']]
    

    The ^{commit} revision specification would therefore apply to the ref refs/heads/${env.BRANCH_NAME}

    <rev>^{<type>}, e.g. v0.99.8^{commit}

    A suffix ^ followed by an object type name enclosed in brace pair means dereference the object at <rev> recursively until an object of type <type> is found or the object cannot be dereferenced anymore (in which case, barf).

    For example, if <rev> is a commit-ish, <rev>^{commit} describes the corresponding commit object.