繁体   English   中英

如何使用 Jenkins 管道 Groovy 脚本检索当前工作区?

[英]How to retrieve current workspace using Jenkins Pipeline Groovy script?

我正在尝试使用 Groovy 管道脚本获取我的 Jenkins 构建的当前工作区:

node('master') {
    // PULL IN ENVIRONMENT VARIABLES
    // Jenkins makes these variables available for each job it runs
    def buildNumber = env.BUILD_NUMBER
    def workspace = env.WORKSPACE
    def buildUrl = env.BUILD_URL

    // PRINT ENVIRONMENT TO JOB
    echo "workspace directory is ${workspace}"
    echo "build URL is ${env.BUILD_URL}"
}

它返回:

[Pipeline] Allocate node : Start
Running on master in /Users/Shared/Jenkins/Home/jobs/test/workspace
[Pipeline] node {
[Pipeline] echo
workspace directory is null
[Pipeline] echo
build URL is http://localhost:8080/job/test/5/
[Pipeline] } //node
[Pipeline] Allocate node : End
[Pipeline] End of Pipeline
Finished: SUCCESS

对我来说, ${workspace}甚至没有初始化变量“workspace”就可以工作。

还没有包含变量,所以你必须使用 shell-out-read-file 方法:

sh 'pwd > workspace'
workspace = readFile('workspace').trim()

或者(如果在主节点上运行):

workspace = pwd()

我认为您还可以在特定节点上执行 pwd() 函数:

node {
    def PWD = pwd();
    ...
}

我在Jenkinsfile中成功使用如下图所示:

steps {
  script {
    def reportPath = "${WORKSPACE}/target/report"
    ...
  }
}

给在工作中使用bat并需要访问 Workspace 的任何人的快速说明:

它不会工作

此处提到的$WORKSPACE https://issues.jenkins-ci.org/browse/JENKINS-33511仅适用于 PowerShell。 所以你的代码应该有powershell来执行

 stage('Verifying Workspace') {
  powershell label: '', script: 'dir $WORKSPACE'
}

这是您可以在job-dsl-plugin 代码中找到答案的地方。

基本上你可以做这样的事情:

readFileFromWorkspace('src/main/groovy/com/groovy/jenkins/scripts/enable_safehtml.groovy')

在 Jenkins 管道脚本中,我使用

targetDir = workspace

非常适合我。 无需使用 ${WORKSPACE}

关键是,如果在双引号而不是单引号内使用,这会起作用,下面是我的代码,它起作用了!

script {
    echo 'Entering Stage - Nexus Upload'
    def artefactPath = "${WORKSPACE}/build/deploy/identityiq.war"   
    echo "printing the path ${artefactPath}"
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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