Jenkinsfile 脚本等待文件夹创建

48次阅读
没有评论

问题描述

在 Jenkinsfile 中使用以下代码,尝试测试 A/B 文件夹的创建,并测试 waitUntil 是否能够等待文件夹创建完成。他期望 waitUntil 在调用之前等待 0 秒,因为文件夹在 waitUntil 被调用之前已经创建。

stage('other job') {
    steps {
        script {
            timeout(10) {
                def folder = new File( 'A/B' )
                println "Waiting for " + folder
                println "fe==" + folder.exists()
                waitUntil {
                    if(folder.exists()) {
                        return(true)
                    }
                }
            }
        }
    }
}

但是他遇到了以下错误,不知道问题出在哪里。在工作空间中,文件夹没有被正确创建。

Timeout set to expire in 10 min
[Pipeline] {
[Pipeline] // stage
[Pipeline] }
[Pipeline] echoWaiting for A/B
[Pipeline] echofe==false
[Pipeline] waitUntil
[Pipeline] {
[Pipeline] }
[Pipeline] // waitUntil
[Pipeline] }
[Pipeline] // timeout
...
Failed in branch other job...
[Pipeline] End of Pipeline
java.lang.ClassCastException: body return value null is not boolean
    at org.jenkinsci.plugins.workflow.steps.WaitForConditionStep$Callback.onSuccess(WaitForConditionStep.java:167)
    at org.jenkinsci.plugins.workflow.cps.CpsBodyExecution$SuccessAdapter.receive(CpsBodyExecution.java:377)

解决方案

请注意以下操作注意版本差异及修改前做好备份。

方案1

你的代码块表达式在所有情况下都没有返回值。
尝试使用以下代码替代:

waitUntil { folder.exists() }

这样就可以正确判断文件夹是否存在了。

方案2

请注意以下操作注意版本差异及修改前做好备份。
你可以尝试使用以下代码来解决问题:

waitUntil {  
    def r = sh script: "[[ -d 'A/B' ]]", returnStatus: true
    return r == 0
}

这段代码使用了 sh 命令来执行一个 shell 脚本,判断文件夹是否存在。如果返回值为 0,则表示文件夹存在,waitUntil 将会继续执行。
请根据你的需求选择适合的解决方案。

正文完