What is the best way to write/modify a *.yaml file in Groovy?
I would like to modify the version maintained in a yaml file within my jenkins pipeline job. With readYaml
I can get the content, but how can I write it back again?
One way that comes to my mind would be to do a sed
on the file. But I think thats not very accurate.
Even Jenkins project uses YAML definitions for jobs, e.g. in the essentialsTest() step. During GSoC 2018 we implemented a Simple Pull Request Job Plugin which allows defining Pipelines as YAML which is close to the Declarative Pipeline syntax-wise. See the alpha release announcement here.
To create Groovy-based project, add new free-style project and select "Execute Groovy script" in the Build section, select previously configured Groovy installation and then type your command, or specify your script file name. In the second case path taken is relatively from the project workspace directory.
The Jenkinsfile is written using the Groovy Domain-Specific Language and can be generated using a text editor or the Jenkins instance configuration tab. The Declarative Pipelines is a relatively new feature that supports the concept of code pipeline.
The Pipeline Utility Steps plugin has the readYaml
and writeYaml
steps to interact with YAML files. writeYaml
will not overwrite your file by default so you have to remove it first.
def filename = 'values.yaml'
def data = readYaml file: filename
// Change something in the file
data.image.tag = applicationVersion
sh "rm $filename"
writeYaml file: filename, data: data
You can use "writeYaml" with a flag "overwrite" set to true.
This will allow making updates to YAML file in place.
By default, it is set to false.
You can read more about that in Pipeline Utility Steps Documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With