Using FilePath to access workspace on slave in Jenkins pipeline

爱⌒轻易说出口 提交于 2019-11-27 02:27:34

问题


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 the same. But I think the File class by default tries to look for the workspace directory on jenkins master and fails.

@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
    }
}

How to access the file system on slave using Groovy from inside the Jenkinsfile?

I also tried the below code. But I am getting No such property: build for class: groovy.lang.Binding error. I also tried to use the manager object instead. But get the same error.

@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 
    } 
}

回答1:


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.



来源:https://stackoverflow.com/questions/41250567/using-filepath-to-access-workspace-on-slave-in-jenkins-pipeline

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