Jenkins pipeline script – become self aware – need directory of Jenkinsfile

Jenkins

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:

Help is appreciated.

Best Answer

There are lots of ways to do this. Here are two ways I can think of off the top of my head:

steps {
  println(WORKSPACE)
}

or

steps {
  def foo = sh(script: 'pwd', returnStdout: true)
  println(foo)
}
Related Topic