我试图使用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}"
}
Run Code Online (Sandbox Code Playgroud)
它返回:
[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 : …Run Code Online (Sandbox Code Playgroud) 我们有一系列相同的Jenkinsfile脚本,除了每个脚本配置一个环境项以指向包含Jenkinsfile的SCM结账中的目录.它用于引用同一目录中的文件.SCM repo将所有这些Jenkinsfile脚本放在不同的目录中.如果我只能检索包含Jenkinsfile的目录的路径,我会看到一个简单的开头,使管道脚本在每种情况下都相同.
我试过几个不同的东西,比如包含的步骤
script {
println __FILE__
}
Run Code Online (Sandbox Code Playgroud)
和
script {
scriptDir = new File(getClass().protectionDomain.codeSource.location.path).parent
println scriptDir
}
Run Code Online (Sandbox Code Playgroud)
两者都没有运行(在__FILE__案例中给出了不存在的变量,在第二种情况下违反了权限).我试过"${__FILE__}"和其他变种.
我需要在step-sh块中使用该目录,所以我认为它需要在一个环境项中.
现在,Jenkins作业配置提供了Jenkins文件的路径,但我不想重复这一点以在该级别创建另一个环境变量.
已经咨询过:
感谢帮助.
我正在创建一个 jenkins 管道作业来使用 jenkins 作业 DSL 插件播种作业。如何获取 DSL 文件中的工作区路径?jenkins 管道代码如下:
#!groovy
node{
stage("build jobs"){
ws{
git poll: true, credentialsId: 'xxx', url: 'ssh://git@aaaaa.cc.xxx.com:/xxx/xxx.git'
checkout scm
jobDsl(removedJobAction: 'DISABLE', removedViewAction: 'DELETE', targets: 'jobs/*.groovy', unstableOnDeprecation: true)
}
}
}
Run Code Online (Sandbox Code Playgroud)
失败的 DSL 代码是:
hudson.FilePath workspace = hudson.model.Executor.currentExecutor().getCurrentWorkspace()
Run Code Online (Sandbox Code Playgroud)
随着错误:
Processing DSL script pipeline.groovy
java.lang.NullPointerException: Cannot invoke method getCurrentWorkspace() on null object
at org.codehaus.groovy.runtime.NullObject.invokeMethod(NullObject.java:91)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:48)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.NullCallSite.call(NullCallSite.java:35)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:117)
at pipeline.run(pipeline.groovy:1)
at pipeline$run.call(Unknown Source)
Run Code Online (Sandbox Code Playgroud)
在作业 DSL 步骤中无法访问在管道区域中创建的变量