Saturday, February 15, 2014

Execute SSH command as root from a Jenkins build without using keys

Here is an easy way to execute SSH commands on a Linux server from a Jenkins job without having to generate cumbersome keys. While this method may not be as secure as public key cryptography, if you are working in a securely firewalled private network (not the DMZ) that should be less of an issue.

Two plug-ins are used to make this work:
The EnvInject Plugin allows a job to setup environment variables, one of which can be used for masked passwords. I prefer this plugin to mask passwords as they do not show up in the build log or build environment variable saved information.
Assigning a masked password to the "sudopass" environment variable.

The Publish Over SSH plugins allows one to send files or execute commands over SSH as a build step. As you will see below there are three "Advanced" buttons, which are all open, you can select to see more options for this plugin. In the setup below it was necessary to check the "Exec in pty" box in order for the SSH command to run. (The SSH Server setup in the top part of the plugin must be done from the Jenkins Master configuration page.)

Exec command as root using SSH.

Here is SSH sudo command typed out:

echo $sudopass | sudo -S /local/apps/javahost/scripts/stopServer.sh || true