I am one short step away from being able to replace numerous customized Jenkinsfiles with one. All I need to get is the directory containing the Jenkinsfile under execution. I am using the Declarative pipeline syntax.
I looked at several ideas in groovy code, but could not find how to obtain this.
For those that need to see something specific, a Jenkinsfile looks like this at the top:
#!/usr/bin/env groovy
pipeline {
agent any
environment {
tf='/var/lib/jenkins/tools/terraform0108/terraform'
dir='clients/xyz/us-east-1/dev'
}
That variable dir is assigned to the location of that Jenkinsfile. dir is accessed later in the groovy code. I want to be able to omit that assignment and just pick up that directory from context of the executing script.
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.
There are lots of ways to do this. Here are two ways I can think of off the top of my head:
or
In my MultiBranchPipeline I've achieved the goal using this shared library code:
I do concede that this looks more like a hack…
You're asking about pipelines, not JobDSL, but hopefully this helps/applies:
In my DSL seed jobs I use:
in order to determine the path of the seed job that is currently being processed by JobDSL and then run some setup code.
My seed jobs do not sit in the root of the repo that gets cloned, but rather something like
/src/main/groovy/jobdsl/