Using FilePath to access workspace on slave in Jenkins pipeline

依然范特西╮ 提交于 2019-11-28 08:40:26

Had the same problem, found this solution:

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()}";
    }
}

The important thing here is that createFilePath() ins't annotated with @NonCPS since it needs access to the env variable. Using @NonCPS removes access to the "Pipeline goodness", but on the other hand it doesn't require that all local variables are serializable. You should then be able to do the search for the file inside the listFiles() method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!