Our build job on Jenkins runs as part of a release build some git commands like git push and git pull, therefore requires a way to run authenticated git commands from the shell during the build.
Our jenkins slaves don't hold any credentials as they are disposable docker containers that are created per build.
The git plugin manages this with the Jenkins credentials and "somehow" sets GIT_SSH to pick up a private key that is configured via the credentials.
I checked the source code and tried to determine how I can get the variable configured so that I can run for example git pull as an SSH script as part of the build. Without success.
Is there a way to run a git command as part of the build steps using the Jenkins credentials?
My current solution is to copy the SSH key to the slave as part of the build environment setup but seems like duplicate work (plus potential security issue).
I couldn't figure this out for a while too. So although almost three years old I'll post my solution for using a private SSH Key. It may also be adaptable user/password combinations.
Add the key to the credentials section as kind "SSH Username with private key".
In the build project use the "Bindings" (You need to tick the "Use secret text(s) or file(s)" in the Build Environment to make it available) to store the credential information in environment variables:
Now comes the tricky part on how to use the key in the git call. I chose GIT_SSH environment variable since the is the most backward compatible way. In order to make that work you need to create a wrapper script that contains the ssh call using the path to the key file provided in SSH_KEYFILE
. One may find a better solution to create that script. For me the following shell commands worked:
#!/bin/bash
set +x
SSH_WRAPPER_SCRIPT=/tmp/ssh_wrapper
# delete pre-existing script
[[ -f $SSH_WRAPPER_SCRIPT ]] && rm $SSH_WRAPPER_SCRIPT
# create wrapper script with current keyfile path from bindings variable
echo "#!/bin/sh" >> $SSH_WRAPPER_SCRIPT
echo "exec /usr/bin/ssh -i ${SSH_KEYFILE} \"\$@\"" >> $SSH_WRAPPER_SCRIPT
chmod +x $SSH_WRAPPER_SCRIPT
# set GIT_SSH env var to use wrapper script
export GIT_SSH=$SSH_WRAPPER_SCRIPT
# now run your actual git commands here
git ls-remote -h [email protected]:some_repo.git HEAD
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With