在 Jenkins 管道插件中获取工作区目录的绝对路径

我目前正在对 Jenkins 管道插件(以前称为 Workflow 插件)进行一些评估。 阅读文档时,我发现目前无法使用 返回文章页面

下列变量目前在工作流脚本中不可用:

节点 _ 标签

工作空间

特定于 SCM 的变量,如 SVN _ REVISION

有没有其他方法可以得到当前工作区的绝对路径?我需要这个运行一些测试,反过来得到一些参数(绝对路径的一些可执行文件)。 我已经尝试过在 @NonCPS部分中使用 new File("").absolutePath(),但是看起来非 CPS 的东西总是在主控上执行。

有没有人知道如何获得这个路径 没有运行一些批处理脚本,存储到一些文件的路径,稍后可以再次读入?

232097 次浏览

Note: this solution works only if the slaves have the same directory structure as the master. pwd() will return the workspace directory on the master due to JENKINS-33511.

I used to do it using pwd() functionality of pipeline plugin. So, if you need to get a workspace on slave, you may do smth like this:

node('label'){
//now you are on slave labeled with 'label'
def workspace = pwd()
//${workspace} will now contain an absolute path to job workspace on slave
}

Since version 2.5 of the Pipeline Nodes and Processes Plugin (a component of the Pipeline plugin, installed by default), the WORKSPACE environment variable is available again. This version was released on 2016-09-23, so it should be available on all up-to-date Jenkins instances.

Example

node('label'){
// now you are on slave labeled with 'label'
def workspace = WORKSPACE
// ${workspace} will now contain an absolute path to job workspace on slave


workspace = env.WORKSPACE
// ${workspace} will still contain an absolute path to job workspace on slave


// When using a GString at least later Jenkins versions could only handle the env.WORKSPACE variant:
echo "Current workspace is ${env.WORKSPACE}"


// the current Jenkins instances will support the short syntax, too:
echo "Current workspace is $WORKSPACE"


}

"WORKSPACE" environment variable works for the latest version of Jenkins Pipeline. You can use this in your Jenkins file: "${env.WORKSPACE}"

Sample use below:

def files = findFiles glob: '**/reports/*.json'
for (def i=0; i<files.length; i++) {
jsonFilePath = "${files[i].path}"
jsonPath = "${env.WORKSPACE}" + "/" + jsonFilePath
echo jsonPath

hope that helps!!

For me WORKSPACE was a valid property of the pipeline itself. So when I handed over this to a Groovy method as parameter context from the pipeline script itself, I was able to access the correct value using "... ${context.WORKSPACE} ..."

(on Jenkins 2.222.3, Build Pipeline Plugin 1.5.8, Pipeline: Nodes and Processes 2.35)