使用FilePath访问Jenkins管道中的slave上的工作空间

Har*_*haB 9 groovy jenkins jenkins-pipeline

作为管道构建工作的一部分,我需要检查工作区中是否存在某个.exe文件.我尝试使用我的Jenkinsfile中的下面的Groovy脚本来做同样的事情.但我认为File类默认尝试在jenkins master上查找workspace目录并失败.

@com.cloudbees.groovy.cps.NonCPS
def checkJacoco(isJacocoEnabled) {

    new File(pwd()).eachFileRecurse(FILES) { it ->
    if (it.name == 'jacoco.exec' || it.name == 'Jacoco.exec') 
        isJacocoEnabled = true
    }
}
Run Code Online (Sandbox Code Playgroud)

如何在Jenkinsfile中使用Groovy访问slave上的文件系统?

我也试过下面的代码.但我收到了No such property: build for class: groovy.lang.Binding错误.我也尝试使用manager对象.但得到同样的错误.

@com.cloudbees.groovy.cps.NonCPS
def checkJacoco(isJacocoEnabled) {

    channel = build.workspace.channel 
    rootDirRemote = new FilePath(channel, pwd()) 
    println "rootDirRemote::$rootDirRemote" 
    rootDirRemote.eachFileRecurse(FILES) { it -> 
        if (it.name == 'jacoco.exec' || it.name == 'Jacoco.exec') { 
            println "Jacoco Exists:: ${it.path}" 
            isJacocoEnabled = true 
    } 
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*n S 17

有同样的问题,找到了这个解决方案:

import hudson.FilePath;
import jenkins.model.Jenkins;

node("aSlave") {
    writeFile file: 'a.txt', text: 'Hello World!';
    listFiles(createFilePath(pwd()));
}

def createFilePath(path) {
    if (env['NODE_NAME'] == null) {
        error "envvar NODE_NAME is not set, probably not inside an node {} or running an older version of Jenkins!";
    } else if (env['NODE_NAME'].equals("master")) {
        return new FilePath(path);
    } else {
        return new FilePath(Jenkins.getInstance().getComputer(env['NODE_NAME']).getChannel(), path);
    }
}
@NonCPS
def listFiles(rootPath) {
    print "Files in ${rootPath}:";
    for (subPath in rootPath.list()) {
        echo "  ${subPath.getName()}";
    }
}
Run Code Online (Sandbox Code Playgroud)

这里重要的是createFilePath()没有注释,@NonCPS因为它需要访问env变量.使用@NonCPS删除对"管道良好"的访问,但另一方面,它不要求所有局部变量都是可序列化的.然后,您应该能够在listFiles()方法内搜索文件.

  • 救了我的命:)谢谢!! (2认同)