简体   繁体   中英

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.

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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