簡體   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