pipeline {
agent any
parameters {
string(name: 'srcUrl',
description: 'Source (URL)')
credentials(name: 'srcCredentials',
description: 'Source (credentials)',
credentialType: 'com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl',
required: true)
string(name: 'dstUrl',
description: 'Destination (URL)')
credentials(name: 'dstCredentials',
description: 'Destination (credentials)',
credentialType: 'com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl',
required: true)
}
stages {
stage('Clean') {
steps {
script {
def tmp = pwd(tmp: true)
sh "rm -rf $tmp/repository"
}
}
}
stage('Credentials') {
steps {
script {
def tmp = pwd(tmp: true)
withCredentials([usernamePassword(credentialsId: params.srcCredentials, usernameVariable: 'username', passwordVariable: 'password')]) {
writeFile file: "$tmp/src-username.txt", text: username
writeFile file: "$tmp/src-password.txt", text: password
}
writeFile file: "$tmp/src-askpass.sh", text: """#!/bin/sh
case "\$1" in
Username*) cat "$tmp/src-username.txt" ;;
Password*) cat "$tmp/src-password.txt" ;;
esac
"""
sh "chmod +x $tmp/src-askpass.sh"
withCredentials([usernamePassword(credentialsId: params.dstCredentials, usernameVariable: 'username', passwordVariable: 'password')]) {
writeFile file: "$tmp/dst-username.txt", text: username
writeFile file: "$tmp/dst-password.txt", text: password
}
writeFile file: "$tmp/dst-askpass.sh", text: """#!/bin/sh
case "\$1" in
Username*) cat "$tmp/dst-username.txt" ;;
Password*) cat "$tmp/dst-password.txt" ;;
esac
"""
sh "chmod +x $tmp/dst-askpass.sh"
}
}
}
stage('Pull') {
steps {
script {
def tmp = pwd(tmp: true)
withEnv(["GIT_ASKPASS=$tmp/src-askpass.sh"]) {
sh "git clone --mirror ${params.srcUrl} $tmp/repository"
}
}
}
}
stage('Push') {
steps {
script {
def tmp = pwd(tmp: true)
withEnv(["GIT_ASKPASS=$tmp/dst-askpass.sh"]) {
dir("$tmp/repository") {
sh "git push --mirror ${params.dstUrl}"
}
}
}
}
}
}
}
As far as I understand the withCredentials syntax, it already can do that for https protocol. The withCredentials step defines variables for the username and password which the statements inside the block can use to reference the username and password in the git command line. Refer to the credentials binding plugin documentation on jenkins.io
A similar technique can be used with git repositories using the ssh protocol by using an sshagent step. Refer to the sshagent pipeline step documentation on jenkins.io