Git HTTP Username and Password in Environment Variables

🔖 cloud-software ⏲️ 1 minute to read

⚠️ 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.

echo username=$GIT_USERNAME
echo password=$GIT_PASSWORD

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

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 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 + '/"'

            $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

⬅️ Previous post: Capturing and Uploading Screenshots in UE4

➡️ Next post: Building and Deploying a React App Using AWS Lambda

🎲 Random post: Loki and Grafana for Logs


Please click here to load comments.