write yaml file in jenkins with groovy

2020-06-08 19:52发布

问题:

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.

回答1:

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


回答2:

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
}