Christopher
Christopher

Reputation: 1193

write yaml file in jenkins with groovy

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.

Upvotes: 23

Views: 42905

Answers (3)

Alexey Panchenko
Alexey Panchenko

Reputation: 111

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

Upvotes: 11

Randy
Randy

Reputation: 1558

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

Upvotes: 37

GlennV
GlennV

Reputation: 3670

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
}

Upvotes: 0

Related Questions