2

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/script.sh: line 1: sudo: not found

Rajat Seeddharth
  • 197
  • 1
  • 3
  • 19

2 Answers2

2

You are seeing "sudo not found" since sudo is not installed on your docker image. Check the default user's ID.
i.e. For Maven, it is the root user (ID: 0).

The user may be mapped to ID, and not name.
i.e. The user ID on host is 1000, which corresponds to the user node in the image.

sh “chown -R 1000 /mydir”  /* Replace 1000 with actual user ID> */

The above command will solve your issue if the user IDs match, or else it will set an unknown owner to your files.

Please try the following Jenkins script I wrote based on the Docker image you provided.

pipeline{
agent any
stages{
    stage('test'){
        steps{
            script{
                    def image = docker.image('mhart/alpine-node:8.11.3')
                    image.pull()
                    image.inside() {
                        sh 'id'
                        sh 'ls -lrt'
                        sh 'node yarn install'
                    }
              }
          }
      }
    }
}
Ram
  • 1,154
  • 6
  • 22
  • Whats the point if writing a JenkinsFile if it doesnt run everywhere? I will have to map user ID to hostID for every system.Is there any workaround? – Rajat Seeddharth Nov 08 '18 at 07:58
  • We use extensively docker in our Jenkins. Only workaround I found was either use docker images that runs with root user( not highly recommended by docker community) or use those images which has a matching user that of host. – Ram Nov 08 '18 at 08:02
  • It returned invalid spec `1001` when i did `sh “chown -R 1000 /mydir”`. – Rajat Seeddharth Nov 08 '18 at 08:20
  • Which docker image are you using? What’s the user ID of your Jenkins user ? – Ram Nov 08 '18 at 08:21
  • The docker image is `mhart/alpine-node:8.11.3` and the userID of the jenkins user is 1001. – Rajat Seeddharth Nov 08 '18 at 08:23
  • To some extent it did solve the problem but now new problem has creeped saying `node yarn build` not found. I think when i use it on my system i have to use `sudo yarn build` to build reactApp thats why it isnt working – Rajat Seeddharth Nov 13 '18 at 20:10
0

try to run such commands as 'jenkins' user instead:

stage('Install packages') {
  sh("docker run --user='jenkins' --rm -v `pwd`:/app -w /app node yarn install")
}
yorammi
  • 6,272
  • 1
  • 28
  • 34