Add a tag to a repository with Jenkinsfile pipeline with credentials

Viewed 6727

I'm new on Jenkinsfile and I'm trying to pass a job I have to a Jenkinsfile. I've successfully created all steps I needed but I can't add a tag to my git repository like I use to with the interface and the "git publisher" plugin.

Here is what I've got now :

stage('Tag') {
 steps {
     script {
         env.POM_VERSION = readMavenPom().getVersion()
     }
     // creating the name of the tag
     sh '''#!/bin/bash -xe
       currentDate=$(date +"%Y-%m-%d_%Hh%Mm%Ss")
       customTagName="${CUSTOMER_NAME}--${POM_VERSION}--${currentDate}"
       echo CUSTOM_TAG_NAME=${customTagName} >> ${PROPERTIES_FILE_NAME}
     '''
     script {
         def PROPERTIES = readProperties file: "${PROPERTIES_FILE_NAME}"
         env.CUSTOM_TAG_NAME = PROPERTIES.CUSTOM_TAG_NAME
     }
     withCredentials([usernamePassword(credentialsId: "${GIT_CREDENTIALS_ID}", passwordVariable: 'GIT_PASSWORD', usernameVariable: 'GIT_USERNAME')]) {
         sh "git tag -a ${CUSTOM_TAG_NAME} -m 'Jenkinsfile push tag'"
         sh "git push https://${GIT_USERNAME}:${GIT_PASSWORD}@git.repohere.com/scm/reponamehere.git ${CUSTOM_TAG_NAME}"
     }
  }

}

but then I've got this issue in logs:

[Pipeline] sh + git push 'https://****:****@git.repohere.com/scm/reponamehere.git' name--4.36.0--2020-04-10_22h00m50s

fatal: unable to access 'https://****:****@git.repohere.com/scm/reponamehere.git/': Could not resolve host: ****; Unknown error [Pipeline] } [Pipeline] // withCredentials

I'm stuck on this for hours now, how can I add and push a tag with credentials added in jenkins config. Thank you!

3 Answers

Do you have this variable ${GIT_CREDENTIALS_ID} declared already in the environment directive in your pipeline first? If not declare it first or use the value of the variable directly as listed below:

withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'MyID', usernameVariable: 'GIT_USERNAME', passwordVariable: 'GIT_PASSWORD']]) {
    sh("git tag -a some_tag -m 'Jenkins'")
    sh("git push https://${env.GIT_USERNAME}:${env.GIT_PASSWORD}@<REPO> --tags")
}

OR

You don't need to pass your password with your GIT repo url in jenkinsfile if you're using the sshagent to create tag and push.

pipeline {
    agent any
    stages {
        stage("Tag and Push") {
            when { branch 'master' }
            environment { 
                GIT_TAG = "jenkins-$BUILD_NUMBER"
            }
            steps {
                sh('''
                    git config user.name 'my-ci-user'
                    git config user.email 'my-ci-user@users.noreply.github.example.com'
                    git tag -a \$GIT_TAG -m "[Jenkins CI] New Tag"
                ''')
                
                sshagent(['my-ssh-credentials-id']) {
                    sh("""
                        #!/usr/bin/env bash
                        set +x
                        export GIT_SSH_COMMAND="ssh -oStrictHostKeyChecking=no"
                        git push origin \$GIT_TAG
                     """)
                }
            }
        }
    }
}

Here's another example to use Jenkins credentials for Git

withCredentials([usernamePassword(
    credentialsId: gitCred,
    passwordVariable: 'GIT_PASSWORD',
    usernameVariable: 'GIT_USERNAME')]) {
  sh '''
    git config --global credential.username $GIT_USERNAME
    git config --global credential.helper '!f() { echo password=$GIT_PASSWORD; }; f'
  '''
}

Here is my version, a mix of former answers:

def branch = 'test'
def repoUrl = 'https://bitbucket.example-group.com/scm/xxx/example-app.git'

pipeline {
    agent any
    tools {
        maven '3'
        jdk '11 (OpenJDK)'
    }
    stages {
        stage('Checkout example-app') {
            steps {
                git branch: branch,
                    credentialsId: 'gitCred',
                    url: repoUrl
            }
        }
        stage('Create version') {
            steps {
                script {
                    currentDateTime = sh script: """
                        date +"-%Y%m%d_%H%M"
                        """.trim(), returnStdout: true
                    version = currentDateTime.trim()  // the .trim() is necessary
                    echo "version: " + version
                }
            }
        }
        stage('Build and deploy') {
            ...
        }
        stage('Adding the version to the latest commit as a tag') {
            steps {
                withCredentials([[$class: 'UsernamePasswordMultiBinding',
                        credentialsId: 'gitCred',
                        usernameVariable: 'GIT_USERNAME',
                        passwordVariable: 'GIT_PASSWORD']]) {
                    sh '''
                        git config --global credential.username $GIT_USERNAME
                        git config --global credential.helper '!f() { echo password=$GIT_PASSWORD; }; f'
                    '''
                    sh """
                        git tag ${version}
                        git push ${repoUrl} --tags
                    """
                }
            }
        }
    }
}
Related