Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 890
user2393256 Avatar asked Nov 02 '25 12:11

user2393256


2 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}"
            }
        }
    }
  }
}
like image 130
Aditya Malviya Avatar answered Nov 04 '25 03:11

Aditya Malviya


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.

like image 24
Tai Ly Avatar answered Nov 04 '25 01:11

Tai Ly