21

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.

Christopher
  • 1,103
  • 1
  • 6
  • 18
  • Possible duplicate of [groovy load YAML file modify and write it in a file](http://stackoverflow.com/questions/34668930/groovy-load-yaml-file-modify-and-write-it-in-a-file) – Rao Mar 31 '17 at 13:48
  • IMHO it's not a duplicate since it's not the equivalent to the Jenkins plugin's readYaml method – dhpizza Jun 06 '17 at 12:12
  • 1
    the recent jenkins plugin named "Pipeline utility steps" contains both `readYaml` (which reads yaml file into an object), and `writeYaml`, which takes an object and writes it down as yaml file. – mvk_il Oct 31 '17 at 14:34

3 Answers3

37

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
mkobit
  • 43,979
  • 12
  • 156
  • 150
Randy
  • 1,498
  • 13
  • 8
8

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

0

If you just need to update a version in a yaml file, then you can just read the contents, do a String replace and write back to your file.

As an example, here's a unit test that demonstrates this:

Suppose src/test/resources contains a file version.yaml that looks like:

version: '0.0.1'

anotherProperty: 'value'

@Test
void replaceVersion() {
    File yaml = new File("src/test/resources/version.yaml")
    println yaml.text

    String newVersion = "2.0.0"
    yaml.text = yaml.text.replaceFirst(/version: '.*'/, "version: '${newVersion}'")
    println yaml.text
}
GlennV
  • 3,471
  • 4
  • 26
  • 39
  • Not if you don't know or don't care what version of the string you are going to replace. – C.J. Oct 04 '19 at 18:15