Clone Git repository with credentials in Jenkins Pipeline from HTTP url.

Here is explained how to use your (Git) credentials to clone or checkout from a repository that is only accessible by http (i.e. not by ssh or https) in a Jenkins Pipeline script. Using a username, password and http is a simple way of doing this. Think about configuring your system to use https or ssh.

Jenkins Requirements

Install the “Credentials Plugin”

GitHub requirements:

Know your username, the password and the http url to access the repository.

Add your credentials to the Credentials plugins of Jenkins

Jenkins menu -> Credentials -> Select the store -> Select Global credentials

In menu at left, select add Credentials

In the form, enter the following information

Kind : choose “username and password”

Scope: global

Username: git user name

Password: git password

!NOTE! Is your password contains special characters like @, #, // or anything that can corrupt a command line or url, than it is easier to change your password into only letters and numbers.

ID: leave blank as it will be generated by the Jenkins plugin (in this example we imagine the ID generated is xyz)

Description: My GitHub credentials

Press OK.

The generated ID will be used in the Jenkins pipeline, you can copy/past the ID.

Pipeline script

  1. Define the credentials in the environment
pipeline {
   agent any
   environment 
   { 
       // replace xyz with the copy pasted iD
       GitHubUser = credentials('xyz')  
   }
   ...

This will generate variable that can be used in your script. The names start with the name of the variable ‘GitHubUser’ and postfix _USR and _PSW are added. So the two resulting variables we are going to use are:

GitHubUser_USR
GitHubUser_PSW

2. Create a pipeline stage to checkout the repository. In this example, we clone into an empty directory, but you can use the git checkout command as well.

stage('Checkout'){
   steps   {        bat "git clone http://$GitHubUser_USR:$GitHubUser_PSW@example.com/project.git"   }
}

3. Run the script

The actual username and password are NOT DISPLAYED in the logging.

They will appear like ****:

C:\Jenkins\\Dev>git clone http://****@example.com/project.git
Cloning into 'project'...


2 responses to “Clone Git repository with credentials in Jenkins Pipeline from HTTP url.

Leave a comment