简体   繁体   English

用groovy在jenkins中写yaml文件

[英]write yaml file in jenkins with groovy

What is the best way to write/modify a *.yaml file in Groovy? 在Groovy中编写/修改* .yaml文件的最佳方法是什么?

I would like to modify the version maintained in a yaml file within my jenkins pipeline job. 我想在我的jenkins管道作业中修改yaml文件中维护的版本。 With readYaml I can get the content, but how can I write it back again? 使用readYaml我可以获取内容,但是如何将其重新写回来?

One way that comes to my mind would be to do a sed on the file. 我想到的一种方法是在文件上做一个sed But I think thats not very accurate. 但我认为那不是很准确。

The Pipeline Utility Steps plugin has the readYaml and writeYaml steps to interact with YAML files. Pipeline Utility Steps插件具有readYamlwriteYaml步骤以与YAML文件交互。 writeYaml will not overwrite your file by default so you have to remove it first. 默认情况下, writeYaml不会覆盖您的文件,因此您必须先将其删除。

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. 如果您只需要更新yaml文件中的版本,那么您只需读取内容,执行String替换并回写到您的文件。

As an example, here's a unit test that demonstrates this: 举个例子,这是一个单元测试,用于演示:

Suppose src/test/resources contains a file version.yaml that looks like: 假设src/test/resources包含一个文件version.yaml ,它看起来像:

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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