Executing a shell script as another user in JENKINS-CI

Recently i came accross a problem with jenkins to run a script as another user (you know because only some users can access/remove/create files)

Here is one, hopefully secured enough, solution, that i ran using ubuntu (should be very similar in other linux systems):

1. Create a custom password for jenkins user
sudo passwd jenkins

2. Add jenkins to sudoers list
sudo nano /etc/sudoer and add one line
jenkins ALL=(ALL) ALL

3. Create a file with the jenkins password inside and limit read access only to jenkins user
sudo su - jenkins
echo 'the_jenkins_password' > pwd
chmod 600 pwd
exit

4. Execute your script
In your custom build create a free form build and select “Execute Shell” in build steps and in the box do:
cat /var/lib/jenkins/pwd | sudo -S su - another_user_name -c "sh /path/to/your/script.sh"

Et voila, your script start as your user name!

About these ads

3 responses to this post.

  1. Posted by Bryan Stenson on 24-05-2012 at 21:51

    if you add “NOPASSWD” to your sudoers file, you don’t have to store the jenkins password…which is a really bad idea.

    Reply

  2. Posted by fortm on 29-01-2013 at 19:28

    after spending whole day how to do this,, finally a working solution ! thanks a lot..

    Reply

  3. Excellent writeup. But I do not understand why you put ‘-S’ in your sudo command.

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: