Use SSH Key from Jenkins Git Plugin to Run Git Commands During Build Use SSH Key from Jenkins Git Plugin to Run Git Commands During Build jenkins jenkins

Use SSH Key from Jenkins Git Plugin to Run Git Commands During Build


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.

  1. Add the key to the credentials section as kind "SSH Username with private key".

  2. 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:

    enter image description here

  3. 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/bashset +xSSH_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 variableecho "#!/bin/sh" >> $SSH_WRAPPER_SCRIPTecho "exec /usr/bin/ssh -i ${SSH_KEYFILE} \"\$@\"" >> $SSH_WRAPPER_SCRIPTchmod +x $SSH_WRAPPER_SCRIPT# set GIT_SSH env var to use wrapper scriptexport GIT_SSH=$SSH_WRAPPER_SCRIPT# now run your actual git commands heregit ls-remote -h git@someserver.com:some_repo.git HEAD


If running sharing credentials via git is essential, give the git client plugin a try but if you really want to just share/store credentials, consider using credentials plugin or something similar.

Note that you can also just run a shell script "after install" that can run whatever commands you need to execute on the machine.