Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

groovy - Using FilePath to access workspace on slave in Jenkins pipeline

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 
    } 
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...