Jenkins Git HTTP Authorization + .netrc

13 Mar

Recently I had to push in a Jenkins Pipeline to a git repository that was only accessible through https with username + password.

Attempts to provide the password in the url like https://user:p@s$ failed, as apparently the password contained already a @ character and thus messed up the url.

A good colleague pointed me to .netrc which apparently is used, as git itself is using curl under the covers. The only problem was, that – from what is publicly documented – the .netrc file has to be in the $HOME folder, which would mean, that all other jobs on the Jenkins instance could also use our credentials.. while in theory possible, its a NOGO in our situation.

In the end, I’ve ended up with this solution.

environment {
JENKINS_GIT = credentials('jenkins_svc-git.credentials')
stage('Deploy to TEST') {
when {
branch 'master'
expression {
input message: 'Deploy to test system?'
return true
options {
timeout(time: 10, unit: 'MINUTES')
steps {
script {
sh "git config –local 'Jenkins CI'"
sh "git config –local ''"
sh "git remote set-url origin"
sh 'echo "machine\nlogin ${JENKINS_GIT_USR}\npassword ${JENKINS_GIT_PSW}" > .netrc; chmod 600 ./.netrc; '
sh "HOME=`pwd` git push –tags"
view raw Jenkinsfile hosted with ❤ by GitHub

  1. retrieving the credentials to be used and store them in an environment variable
  2. create a local .netrc file in the project directory
  3. then, when using git, override the $HOME variable and set it to the current directory (pwd), thus making git treat the current directory as the users home and look here for the .netrc file instead of the real home, which could be accessed by other users.

Comment Form