Setup ssh key pair for jenkins under windows

It is always tricky to setup jenkins properly when running under Windows. There are a few things you need to take care of. In this post I will assume you are using the bash shell delivered together with git.

  • Create a new user account for jenkins
  • Set a password for this user account
  • Add the HOME environment variable for Jenkins
  • Start a bask shell under the new user.
  • Generate the ssh key
  • Add you public key to your target server
  • Make a new ssh connection to your server to add it to the known hosts

ssh uses the HOME environment variable to locate the .ssh folder that contains the ssh keys. If this folder is not present it will default to C: which is not a good place to store your keys. So it is very important to add  this HOME variable for a stable functioning of jenkins. If you can not actually log in using the jenkins account you can still set the variable using the registry. The Windows runas command will be used to allow us to add the environment to the user jenkins even when we are not logged in as such.

runas /user:jenkins reg add KEY  /v HOME /t REG_SZ /d "C:\Documents and Settings\jenkins"

Next we start a bash shell to check the HOME var and create the ssh key.

runas /user:jenkins "C:\Program Files\Git\Bin\bash.exe"

This will open a new bash shell that is logged in as jenkins. In this bash shell you can now check the HOME variable, generate your ssh key and add the server to you known_hosts

$ echo $HOME
/c/Documents and Settings/jenkins
$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/c/Documents and Settings/jenkins/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /c/Documents and Settings/jenkins/.ssh/id_rsa.
Your public key has been saved in /c/Documents and Settings/jenkins/.ssh/
$ ssh -p 29418 gerrit ls-projects

Now the ssh has been setup properly you need to change the service user from the Local System account to log in as the user Jenkins.
Lastly, restart the service and Jenkins should be using the correct ssh credentials.

Join the conversation

1 Comment

  1. Thanks
    following command helped

    runas /user:jenkins “REG QUERY \”HKEY_CURRENT_USER\Volatile Environment\””
    runas /user:jenkins “reg add \”HKEY_CURRENT_USER\Volatile Environment\” /v USERPROFILE /t REG_SZ /d \”C:\jenkins\””

    runas /user:jenkins “REG ADD \”HKCU\Volatile Environment\” /v HOMEPATH /t REG_EXPAND_SZ /d \”c:\jenkins\””

    runas /user:jenkins “REG ADD \”HKCU\Volatile Environment\” /v HOMEDRIVE /t REG_EXPAND_SZ /d \”c:\””

Leave a comment

Leave a Reply to Virag Sharma Cancel reply

Your email address will not be published. Required fields are marked *