Rajat Seeddharth
Rajat Seeddharth

Reputation: 307

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

Upvotes: 2

Views: 11846

Answers (2)

Ram
Ram

Reputation: 1224

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'
                    }
              }
          }
      }
    }
}

Upvotes: 2

yorammi
yorammi

Reputation: 6458

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")
}

Upvotes: 0

Related Questions