简体   繁体   English

如何使用 Groovy 在 Jenkins 中创建文本并将其写入文件

[英]How to create and then write text into a file in Jenkins using Groovy

I write a Jjenkins job, which can firstly create a CODEOWNER file direct in workspace and then write a text into this file.我写了一个 Jjenkins 作业,它可以首先在工作空间中直接创建一个 CODEOWNER 文件,然后将文本写入该文件。

I have tried:我努力了:

node {
    writeFile file: 'groovy1.txt', text: 'Working with files the Groovy way is easy.'
    sh 'ls -l groovy1.txt'
    sh 'cat groovy1.txt'
}

However, the above code was not working.但是,上面的代码不起作用。

While building, the job was stopping.在建造过程中,工作停止了。

I have read the documentation Groovy.我已阅读文档 Groovy。 There is a method called writeFile(file, text) , this writeFile method overwrites the text, if this method in a loop.有一个名为writeFile(file, text)的方法,如果此方法在循环中,则此writeFile方法会覆盖文本。 My goal is: insert text into the file but this text is a string.我的目标是:在文件中插入文本,但这个文本是一个字符串。 I am not sure it is right syntax for CODEOWNERS.我不确定 CODEOWNERS 的语法是否正确。

Any solution?有什么解决办法吗?

I'm new too using Jenkins and Groovy, and as I can see, scripts like yours seems to works inside the script{} statement.我也是使用 Jenkins 和 Groovy 的新手,正如我所见,像你这样的脚本似乎在 script{} 语句中工作。 It works for me in this way:它以这种方式对我有用:

stage('My Stage'){
  steps{
        ...
        script{
               writeFile file: 'groovy1.txt', text: 'Working with files the Groovy way is easy.'
               sh 'ls -l groovy1.txt'
               sh 'cat groovy1.txt' 
        }
   }

} }

Hope this can help you: :D希望这可以帮助你::D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM