can not create file via Groovy code(or java code) in jenkinsfile of a pipeline job on Jenkins

后端 未结 1 847
甜味超标
甜味超标 2021-01-14 06:17
pipeline {
    agent any

    stages {
        stage(\'Build\') {
            steps {
                echo \'Building..\'
                echo \"whoami\".execute().t         


        
1条回答
  •  鱼传尺愫
    2021-01-14 07:08

    This is due to Jenkins not implementing Groovy itself but an interpreter (CPS) - https://github.com/cloudbees/groovy-cps

    To help deal with the complexities introduced, there are some common Steps implemented to take the trouble out of tasks such as creating a file.

    To use Jenkins pipeline steps out of the box, use writeFile: https://jenkins.io/doc/pipeline/steps/workflow-basic-steps/#code-writefile-code-write-file-to-workspace

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

    If your deadset on writing your own, I suggest splitting it out into a Shared library, note this will probably cause ScriptSecurity alerts that will require approval:

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

    See https://github.com/jenkinsci/pipeline-plugin/blob/master/TUTORIAL.md for information regarding @NonCPS and nonserializable objects.

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