Git HTTP Username and Password in Environment Variables
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_PASSWORD environment variables, and prints them in a format git understands.
Save this as
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.
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
sh 'git tag my-tag'
sh 'git config credential.helper "/bin/bash ' + env.WORKSPACE + '/credential-helper.sh"'
sh 'git push origin my-tag'