无法在Jenkins管道作业的Jenkinsfile中通过Groovy代码(或Java代码)创建文件。

3
pipeline {
    agent any

    stages {
        stage('Build') {
            steps {
                echo 'Building..'
                echo "whoami".execute().text
                script {
                    File f = new File('/home/jenkins/test2.txt');
                    f.createNewFile();
                }
            }
        }
        stage('Test') {
            steps {
                echo 'Testing..'
            }
        }
        stage('Deploy') {
            steps {
                echo 'Deploying....'
            }
        }
    }
}

Jenkins控制台日志: (出现异常: 由用户Edgar Yu启动,运行在耐久性级别:MAX_SURVIVABILITY [Pipeline] node Running on Jenkins in /var/jenkins_home/workspace/test2 [Pipeline] { [Pipeline] stage [Pipeline] { (Build) [Pipeline] echo 正在构建.. [Pipeline] echo jenkins

[Pipeline] script [Pipeline] { [Pipeline] } [Pipeline] // script [Pipeline] } [Pipeline] // stage [Pipeline] stage [Pipeline] { (Test) 阶段“测试”由于之前的失败而跳过 [Pipeline] } [Pipeline] // stage [Pipeline] stage [Pipeline] { (Deploy) 阶段“部署”由于之前的失败而跳过 [Pipeline] } [Pipeline] // stage [Pipeline] } [Pipeline] // node [Pipeline] 流水线结束java.io.IOException: 权限不足 at java.io.UnixFileSystem.createFileExclusively(Native Method) at java.io.File.createNewFile(File.java:1012)


你的Jenkins用户是否对/home/jenkins目录具有写入权限?看起来好像没有... - Evgeny Smirnov
授予给定目录/文件的运行用户权限,例如,chmod 777 文件名(这将授予所有用户和组的所有权限)。 - Nitin Dhomse
请在此处阅读文档...https://www.computerhope.com/unix/uchmod.htm - Nitin Dhomse
你有什么问题? - Hendrik M Halkow
1
你完全不了解情况。 你不明白我在说什么。 - Edgar Yu
1个回答

12

这是由于Jenkins没有实现Groovy本身,而是采用了一个解释器(CPS) - https://github.com/cloudbees/groovy-cps

为了帮助应对引入的复杂性,实现了一些常见步骤以简化任务,例如创建文件。

要在Jenkins流水线中直接使用步骤,请使用writeFile: https://jenkins.io/doc/pipeline/steps/workflow-basic-steps/#code-writefile-code-write-file-to-workspace

writeFile([file: 'file.txt', text: filetxt])

如果你一定要自己编写,请将它拆分为共享库。请注意,这可能会导致需要批准的ScriptSecurity警报:

final class PipelineUtils implements Serializable {
    private script=null
    private static final PipelineUtils instance = new PipelineUtils()
    @NonCPS
    String saveFile(String filename, String text) {
        String PWD = script.pwd()
        String filePath = "${PWD}/${filename}"

        File file = new File(filePath)
        file.text = text
    }
}

有关@NonCPS和不可序列化对象的信息,请参见https://github.com/jenkinsci/pipeline-plugin/blob/master/TUTORIAL.md


如果您使用writeFile,您将如何将内容附加到同一文件中? - SSF
1
这个回答可能会有所帮助:https://dev59.com/6FgR5IYBdhLWcg3wAJBK#46941503,基本上是在Groovy中读取并追加,然后重新写入文件。 - metalisticpain

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接