Git HTTP Username and Password in Environment Variables
⚠️ This post was last updated in 2017, meaning its contents may be outdated.
Sometimes when automating the use of the git
command in scripts against GitHub or BitBucket, you may need to supply a username and password using environment variables.
One example is when using a Jenkinsfile
groovy script in a Jenkins pipeline build, where you'd like to use credentials from the Jenkins credentials store.
Fortunately this is possible using a custom git credential helper, in this case a simple bash script (however you can use whatever language you like).
Credential Helper Shell Script
The shell script simply needs to echo a username and password back to git. The below script takes the $GIT_USERNAME
and $GIT_PASSWORD
environment variables, and prints them in a format git understands.
#!/bin/bash
echo username=$GIT_USERNAME
echo password=$GIT_PASSWORD
Save this as credential-helper.sh
Telling Git to use the Script
To tell git to use the script, you need to configure it as a credential helper.
git config credential.helper "/bin/bash /full/path/to/credential-helper.sh"
You can then run any git command you like inside this repository, and when credentials are needed it will use the script.
Jenkinsfile Example
Here's a full Jenkins pipeline example using the custom credential helper above. It assumes you have checked in the credential-helper.sh
script alongside your Jenkinsfile
.
node('node-label') {
stage('Checkout') {
scm checkout
}
stage('Tag') {
sh 'git tag my-tag'
sh 'git config credential.helper "/bin/bash ' + env.WORKSPACE + '/credential-helper.sh"'
withCredentials([[
$class: 'UsernamePasswordMultiBinding',
credentialsId: 'my-git-credential-id',
usernameVariable: 'GIT_USERNAME',
passwordVariable: 'GIT_PASSWORD'
]]) {
sh 'git push origin my-tag'
}
}
}
🏷️ script git credential helper username password environment variable jenkins command pipeline custom shell http automate
Please click here to load comments.