Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make Jenkins 2.0 execute a sh command in the same directory as the checkout?

Here's my Jenkins 2.x pipeline:

node ('master'){     stage 'Checkout'     checkout scm     stage "Build Pex"     sh('build.sh') } 

When I run this pipeline the checkout puts the code into to the workspace as expected, however instead of expecting to find the script in workspace/ (it's really there!), it looks in an unrelated directory: workspace@tmp/durable-d812f509.

Entering stage Build Pex Proceeding [Pipeline] sh [workspace] Running shell script + build.sh /home/conmonsysdev/deployments/jenkins_ci_2016_interns/jenkins_home/jobs/pex/branches/master/workspace@tmp/durable-d812f509/script.sh: line 2: build.sh: command not found 

How do I modify this Jenkinsfile so that build.sh is executed in the exact same directory as where I checked out the project source code?

like image 973
Salim Fadhley Avatar asked Jul 01 '16 10:07

Salim Fadhley


People also ask

How do I change the working directory in Jenkins?

To change the Jenkins Home directory on Linux, create a new Home directory, copy the contents of the old Home directory to the new one and edit the Jenkins configuration file. In the example below, we are using Ubuntu 18.04.


2 Answers

You can enclose your actions in dir block.

checkout scm stage "Build Pex" dir ('<your new directory>') {      sh('./build.sh') } ... or .. checkout scm stage "Build Pex" sh(""" <path to your new directory>/build.sh""")  ... 

<your new directory> is place holder your actual directory. By default it is a relative path to workspace. You can define absolute path, if you are sure this is present on the agent.

like image 151
Jayan Avatar answered Oct 05 '22 02:10

Jayan


The reason that your script doesn't work is because build.sh is not in your PATH.

The Jenkinsfile is running a "sh" script, whose entire contents is the string build.sh. The parent script is in the "@tmp" directory and will always be there - the "@tmp" directory is where Jenkins keeps the Jenkinsfile, essentially, during a run.

To fix the problem, change your line to sh "./build.sh" or sh "bash build.sh", so that the sh block in the Jenkinsfile can correctly locate the build.sh script that you want to execute.

like image 39
Keith Mitchell Avatar answered Oct 05 '22 02:10

Keith Mitchell