Using FilePath to access workspace on slave in Jenkins pipeline

前端 未结 1 1743
清酒与你
清酒与你 2020-12-08 17:30

I need to check for the existence of a certain .exe file in my workspace as part of my pipeline build job. I tried to use the below Groovy script from my Jenkinsfile to do t

相关标签:
1条回答
  • 2020-12-08 18:32

    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.

    0 讨论(0)
提交回复
热议问题