How can I read a GIT tag from the current branch into a variable?

Viewed 7445

I want to use git tags within my declarative Jenkins pipeline. My Jenkinsfile looks like this

pipeline {
    agent any
    stages {
        stage('Setup') {
            steps {
                script {
                    env.MY_GIT_TAG = sh(returnStdout: true, script: 'git tag -l --points-at HEAD')
                    // ... 
                }
            }
        }
        stage('Build'){
            // build my code etc ....
        }
        stage('Publish') {
            // push code somewhere depending on tag
            sh "curl -X POST --upload-file ./MyDeployable https://someserver/uri/MyDeployable-${env.MY_GIT_TAG}"
        }
    }
}

But the environment variable MY_GIT_TAG was always empty. After some investigation i noticed this in my Jenkins logs: git fetch --no-tags --progress ...

Is there a way to tell Jenkins to skip the --no-tags argument?

As i do not know beforehand how the commit is tagged i want to checkout the tag from git and use it as a variable. So the solution in this question is not viable here.

3 Answers

We can use, sh(returnStdout: true, script: "git tag --sort=-creatordate | head -n 1").trim() take this into a variable and use it.

pipeline {
  agent any
    stages {
        stage('get git tag') {
            steps {
             script {
             latestTag = sh(returnStdout:  true, script: "git tag --sort=-creatordate | head -n 1").trim()
             env.BUILD_VERSION = latestTag
             echo "env-BUILD_VERSION"
             echo "${env.BUILD_VERSION}"
            }
        }
    }
  }
}

As mentioned in the comments, the sh returns nothing. You can do env.MY_GIT_TAG = sh(returnStdout: true, script: 'git tag -l --points-at HEAD').trim() to return the stdout.

As mentioned by Tai Ly there is a description of two possible solutions here

Solution 1)

You can create a custom checkout in your Jenkinsfile that sets noTags to false.

checkout([
    $class: 'GitSCM',
    branches: scm.branches,
    doGenerateSubmoduleConfigurations: scm.doGenerateSubmoduleConfigurations,
    extensions: [[$class: 'CloneOption', noTags: false, shallow: false, depth: 0, reference: '']],
    userRemoteConfigs: scm.userRemoteConfigs,
 ])

Soltion 2)

Add an "Advanced Clone Behaviours" entry in the branch source behaviors in the Jenkins web interface. It can also be set at the Organization/Team-level for GitHub/Bitbucket plugins & co.

Related