Running a job which requires sudo

Hi,

I`m fairly new to Jenkins and how it all works and have a question.

How does Jenkins run jobs that require sudo access when a command like umount -l /dev/sda1 is in the script? We log into our nodes with a common ssh key and if we type in the umount command then it will ask for the password but running the job from Jenkins it doe not.

Thanks

James

Jenkins does not do any specific sudo magic. The sh "foo bar" calls from your pipeline basically translate into creating a file like

#!/bin/sh
# /jenkins/workspace/jobname@tmp/script.sh
foo bar

that then is run as sh -ex script.sh by the user configured in Jenkins agent settings (usually via credentials).
So if the pipeline is able to use sudo without a password, then the user is likely authorized to do so via /etc/sudoers or /etc/sudoers.d.

If you meant that you can write the umount command in the pipeline and it works without sudo – your Jenkins probably connects to that machine as a root, which would probably be a security concern.

If you want to run commands that require root permissions you need to include the sudo in your command eventually piping in a password
Assuming you have a credentials of type secret text with id sudo_pass that contains the password that allows to execute sudo for the user that runs the agent you can do the following:

withCredentials([string(credentialsId: 'sudo_pass', variable: 'SUDO_PW')]) {
    sh ''' 
echo $SUDO_PW | sudo -v -S
sudo umount -l /dev/sda1
''' 
}

After running sudo with password piped in, the information is cached for a while (usually a minute or so) and the follow up sudo doesn’t require a password.

Thanks @Artalus and @mawinter69 for the comments. This helps me understand what is going on.

Found out that the node i’ve been looking at has the jenkins user in the sudoers file which is why it doesn’t ask for a password.

1 Like