Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkins Declarative Pipeline - how to get path to Jenkinsfile in use?

We have a series of Jenkinsfile scripts which are identical, except each configures an environment item to point to the directory in the SCM checkout that holds the Jenkinsfile. That is used to reference a file in the same directory. The SCM repo has all of these Jenkinsfile scripts in different directories. I see an easy opening to make the pipeline script identical in each case if I could only retrieve the path of the directory containing the Jenkinsfile.

I tried several different things like steps containing

script {
    println __FILE__
}

and

script { 
    scriptDir = new File(getClass().protectionDomain.codeSource.location.path).parent
    println scriptDir
}

Neither of which ran (gave non-existent variable in __FILE__ case and permission violation in the second case). I tried "${__FILE__}" and other variants.

I need to use the directory in a steps-sh block so I believe it needs to be in an environment item.

Now, the Jenkins job configuration gives the path to the Jenkins file, but I don't want to have to repeat that to create another environment variable at that level.

Already consulted:

  • Get absolute path of the script directory that is being processed by Job DSL
  • Get absolute path to workspace directory in Jenkins Pipeline plugin
  • How can I reference the Jenkinsfile directory, with Pipeline?
  • as well as many more Google hits and other sites.

Help is appreciated.

like image 321
Kevin Buchs Avatar asked Jul 16 '18 22:07

Kevin Buchs


People also ask

How do I get Jenkinsfile from Jenkins?

Copy one of the examples below into your repository and name it Jenkinsfile. Click the New Item menu within Jenkins. Provide a name for your new item (e.g. My-Pipeline) and select Multibranch Pipeline. Click the Add Source button, choose the type of repository you want to use and fill in the details.

Where do I put Jenkinsfile?

Default place where Jenkins is looking for a Jenkinsfile is the root of the project with Jenkinsfile as the filename. Jenkinsfile can be put in any directory and the filename can be whatever you want.


2 Answers

Found at another thread:

def currentScriptPath = new File(currentBuild.rawBuild.parent.definition.scriptPath).parent

But it requires to approve a lot of methods.

like image 114
MagMax Avatar answered Oct 17 '22 23:10

MagMax


If you really need this, you can fetch "${JOB_URL}config.xml" and parse scriptPath.

But that's not a clean solution and the request needs to be authenticated.

like image 1
Chadi Avatar answered Oct 17 '22 23:10

Chadi