Cher
Cher

Reputation: 2937

how to write to a file using DSL [Jenkins]?

I'm presently making a build flow using DSL.

After searching for I while I've been able to find how to read from a text file, but not how to write to one.

Is there a command for it in DSL?

And also I'd take the opportunity to ask where I can find a tutorial or command list for DSL?

Upvotes: 3

Views: 3493

Answers (3)

Jack Davidson
Jack Davidson

Reputation: 4933

This is the best I've been able to come up with, it uses writeFile:

def readEscape(String file) {
  return readFileFromWorkspace(file).replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n").replace("\r", "\\r").replace("\$", '\\$')
}
def Dockerfile = readEscape('./Dockerfile')
pipelineJob('sample-write-file') {
  definition {
    cps {
      script('''
        pipeline {
          agent any
          stages {
            stage("prep-files") {
              steps {
                writeFile file: './Dockerfile', text: "''' + Dockerfile + '''"
              }
            }
          }
        }
      ''')
    }
  }
}

The question is unclear about whether the file needs to be written during the processing of the job dsl or during the generated job's execution. Since I needed this for the job execution, that is what my example shows. The file will be read while creating the job and embedded in the created job definition.

Upvotes: 0

ocroquette
ocroquette

Reputation: 3259

By default, you cannot use new File(...).text for security reasons. You can use writefile instead:

writeFile file: "myfile.txt", text: "File content."

Upvotes: 1

Dchucks
Dchucks

Reputation: 1199

Since the DSL is Groovy based I guess you can write any Groovy code and it should work, refer http://grails.asia/groovy-file-examples to get an example of how to write to a file. The DSL commands are provided at https://jenkinsci.github.io/job-dsl-plugin/ and you can try them out at the playground at http://job-dsl.herokuapp.com/.

Upvotes: 1

Related Questions