Running a command as root in JenkinsFile

I have a command which requires root in JenkinsFile.But when i run it on my localhost it gives error that "sudo not found".The JenkinsFile is in the source code.

stage('Install packages') {
  sh("docker run --rm -v `pwd`:/app -w /app node yarn install")
  sh("sudo chown -R jenkins: ./node_modules")

I have already tried this. How to run a script as root in Jenkins? The temp sh script is created on each build. And the error is

/var/jenkins_home/workspace/boilerplate_master-2ESKZDF4PBIXGKODFFKIVAND5RN5VWF6QLEGRZ44LZGESCULVC4Q@tmp/durable-14d87eaa/ line 1: sudo: not found

1 answer

  • answered 2018-11-08 07:54 Ram Kamath

    ‘sudo’ is not available in every docker image. Try checking the ID of a default user. For example on maven image it’s root user( ID 0).

    Also, the user mapping is usually based on the user ID not by name. Example Jenkins user on host may have ID 1000. In the node image, it’s user node.

    sh “chown -R 1000 /mydir”

    Should work, provided Jenkins user on the host also has user ID 1000. Else you will end up with files that has unknown owner.

    I wrote an example Jenkins file with the Docker image that you mentioned. Please try this.

    agent any
                        def image = docker.image('mhart/alpine-node:8.11.3')
                        image.inside() {
                            sh 'id'
                            sh 'ls -lrt'
                            sh 'node yarn install'