How to run a script as root in Jenkins?

ShellHudsonJenkinsRoot

Shell Problem Overview


I need to run a shell script in Jenkins as root instead of the default user. What do I need to change?

My sudoers file is like this:

# User privilege specification
root    ALL=(ALL) ALL
igx     ALL=(ALL) ALL
%wheel  ALL=(ALL) ALL

# Allow members of group sudo to execute any command
# (Note that later entries override this, so you might need to move
%sudo   ALL=(ALL) ALL
#
#includedir /etc/sudoers.d

# Members of the admin group may gain root privileges
%admin  ALL=(ALL) NOPASSWD:ALL
root    ALL=(ALL) ALL
jenkins ALL=NOPASSWD: /var/lib/jenkins/workspace/ing00112/trunk/source/
jenkins ALL=(ALL) NOPASSWD:ALL
#Defaults:jenkins !requiretty

Shell Solutions


Solution 1 - Shell

You must run the script using sudo:

sudo /path/to/script

But before you must allow jenkins to run the script in /etc/sudoers.

jenkins    ALL = NOPASSWD: /path/to/script

Solution 2 - Shell

@Igor Chubin's answer is 100% correct, but never open sudoer file with a normal editor. always use visudo

just type

sudo visudo

this will take you to /etc/sudoers and upon saving it will make sure that there is no error in formatting.

if you make an error in sudoer file, you will lose sudo access, so always use visudo

Solution 3 - Shell

I do realise I'm late to the party on this question, but for reference sake I thought I'd throw my 2c in here: I use the SSH plugin for Jenkins to accomplish this (simply configure a localhost target). In this way, I can contain the script directly within Jenkins (like a normal "Execute shell" step), instead of using sudo to invoke an external script.

Solution 4 - Shell

Try adding jenkins user to sudo group

sudo su -
usermod -a -G sudo jenkins

Solution 5 - Shell

Easy way to do it
enter image description here

$ sudo visudo
## Now add the below lines in your sudoers file :
jenkins ALL=(ALL) NOPASSWD: ALL

$service jenkins start

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMaheshView Question on Stackoverflow
Solution 1 - ShellIgor ChubinView Answer on Stackoverflow
Solution 2 - ShellLav PatelView Answer on Stackoverflow
Solution 3 - ShellNathan CrauseView Answer on Stackoverflow
Solution 4 - Shelluser13749276View Answer on Stackoverflow
Solution 5 - ShellWillie ChengView Answer on Stackoverflow