Use git archive instead of clone with credentials in jenkins pipeline job

2.3k Views Asked by At

On my Jenkins pipeline job, I used to clone git repo at the begining of my job like that

cleanWs()
git branch: 'master', credentialsId: 'SSH_GIT', url: '[email protected]:myrepo'

Note that I need credentials.

In order to reduce time execution and data size downloaded, I would like to use git archive instead of git clone.

sh("git archive --format=tar --remote [email protected]:myrepo master |tar xf -")

The previous command works if I have proper ssh-key configuration done. It is not the case on my server, so I need to use credentials.

How can I archive instead of cloning repo, using Jenkins defined credentials ? Git is installed on a gitolite server

2

There are 2 best solutions below

1
On BEST ANSWER

The solution is to use sshagent function in Jenkins Pipeline

sshagent(['SSH_JENKINS_CREDENTIALS_FOR_GIT']) {
    sh("git archive --format=tar --remote [email protected]:myrepo master |tar xf -")
}
1
On

There is no easy way to use a username and password for ssh in an automated script. OpenSSH only prompts for username and password on a TTY, which you won't have in an automated script unless you use something like expect. Moreover, even if you could do this, most Git servers will only accept an SSH key for authentication over SSH.

You haven't said what Git server you're using, so I can't provide more helpful details, but your choices are essentially to use an SSH key or to use the credentials you have to access the HTTPS API interface of your Git server to fetch an archive for you to use. For example, if you use GitHub or GitHub Enterprise, there is an API URL to fetch tarballs.

Alternatively, you could try a shallow clone (e.g. git clone --depth 1). If you're hosting your own Git server instance, note though that shallow clones can be computationally intensive, so you may end up DoSing your instance if you use a large number of them.