简体   繁体   中英

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:

Help is appreciated.

Found at another thread :

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

But it requires to approve a lot of methods.

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

But that's not a clean solution obviously.

The simplest way is to put the Jenkinsfile at the root of your repository and get the value of the WORKSPACE environment variable set by Jenkins.

Given that Groovy is just basically Java, you can get the absolute path like so:

new File("{env.WORKSPACE}").absolutePath

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM