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

20,388

Solution 1

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"
    }
}

Solution 2

I want to share my Jenkins Pipeline Setup and my solution to publish changes/tags to git repo via SSH (While Git Publish Support is under development). Please check it out for more info, any improvement ideas are welcome.

In short you just add file git_push_ssh.groovy to your project and call method pushSSH() from Jenkinsfile like this:

env.BRANCH_NAME = "mycoolbranch"// BRANCH_NAME is predefined in multibranch pipeline job
env.J_GIT_CONFIG = "true"
env.J_USERNAME = "Jenkins CI"
env.J_EMAIL = "[email protected]"
env.J_CREDS_IDS = '02aa92ec-593e-4a90-ac85-3f43a06cfae3' // Use credentials id from Jenkins
def gitLib = load "git_push_ssh.groovy"
...
gitLib.pushSSH(commitMsg: "Jenkins build #${env.BUILD_NUMBER}", tagName: "build-${env.BUILD_NUMBER}", files: "changelog.txt someotherfile.txt");

Solution 3

For people that couldn't get the above working I used the sshagent plugin directly, which did the trick:

stage('tag build'){
checkout([
    $class: 'GitSCM', branches: [[name: '*/master']],
    userRemoteConfigs: [[credentialsId: 'git',
    url: 'ssh://<ssh URL>']],
    extensions: [[$class: 'RelativeTargetDirectory', relativeTargetDir: 'targeted-dir']]
])

sshagent(credentials: ['<credentials ID.']){
  dir('targeted-dir'){
    sh("git config user.email '<email>")
    sh("git config user.name '<user>.com'")

    // deletes current snapshot tag
    sh ("git tag -d ${PARAM_VERSION_NUMBER} || true")
    // tags current changeset
    sh ("git tag -a ${PARAM_VERSION_NUMBER} -m \"versioning ${PARAM_VERSION_NUMBER}\"")
    // 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")
    }
}

}

Solution 4

To get this working for blue ocean (which uses https connection) use the following:

sshagent(credentials: ["406ef572-9598-45ee-8d39-9c9a227a9227"]) {
                def repository = "git@" + env.GIT_URL.replaceFirst(".+://", "").replaceFirst("/", ":")
                sh("git remote set-url origin $repository")
                sh("git tag --force build-${env.BRANCH_NAME}")
                sh("git push --force origin build-${env.BRANCH_NAME}")
            }
Share:
20,388
sorin
Author by

sorin

Another geek still trying to decipher the meaning of “42”. It seems that amount his main interest are: online communities of practice and the way they evolve in time product design, simplicity in design and accessibility productivity and the way the IT solutions are impacting it

Updated on July 05, 2022

Comments

  • sorin
    sorin almost 2 years

    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?

  • bsky
    bsky about 7 years
    This is interesting. How do you do authentication to the remote(how do you send the password)?
  • Ivor
    Ivor almost 6 years
    You should set up SSH key, so you don't have to input any password or have it stored anywhere.
  • sgbel2
    sgbel2 almost 4 years
    I added the above example stage to clearly show how to add the tag, as it took me a little bit, looking at the example above the the linked code to get this working. It also requires the "ssh agent" plugin for jenkins to be installed.
  • Tristan
    Tristan over 3 years
    Not an alternative answer, but a change of perspective : when you publish a -SNAPSHOT on Nexus, it doesnt remove the old -SNAPSHOT before uploading the new one, it keeps all snapshots using a timestamp. The same thing can be done very easily with git tags.