Search code examples
jenkinsjenkins-workflowjenkins-pipeline

How do I tag the current git changeset from inside the Jenkinsfile?


I want to tag the current git changeset and push the tag from inside the Jenkinsfile. If the tag already exists it must be replaced.

I want to use this logic in order to tag the build that passed with the snapshot tag, which would be a mobile tag.

How can I do this?


Solution

  • Here is the way I was able to implement this this way, but if you know a better way I am more than willing to hear it.

    #!groovy
    
    stage 'build'
    node {
    
        repositoryCommiterEmail = '[email protected]'
        repositoryCommiterUsername = 'examle.com'
    
        checkout scm
    
        sh "echo done"
    
        if (env.BRANCH_NAME == 'master') {
            stage 'tagging'
    
            sh("git config user.email ${repositoryCommiterEmail}")
            sh("git config user.name '${repositoryCommiterUsername}'")
    
            sh "git remote set-url origin [email protected]:..."
    
            // deletes current snapshot tag
            sh "git tag -d snapshot || true"
            // tags current changeset
            sh "git tag -a snapshot -m \"passed CI\""
            // deletes tag on remote in order not to fail pushing the new one
            sh "git push origin :refs/tags/snapshot"
            // pushes the tags
            sh "git push --tags"
        }
    }