Jenkins Groovy - 使用readYaml中的修改数据写回yml文件

时间:2017-08-15 14:12:05

标签: jenkins groovy yaml

我正在使用Jenkins readYaml来读取数据如下:

data = readYaml file: "test.yml"
//modify
data.info = "b"

我想把这个修改过的数据写回Jenkins的test.yml。怎么能实现这一目标?

2 个答案:

答案 0 :(得分:6)

test.yml:

data:
  info: change me
  aaa: bbb
  ddd: ccc

管道脚本:

@Grab('org.yaml:snakeyaml:1.17')
import org.yaml.snakeyaml.Yaml
import org.yaml.snakeyaml.DumperOptions
import static org.yaml.snakeyaml.DumperOptions.FlowStyle.BLOCK

node {
    def yaml = readYaml file: "test.yml"
    yaml.data.info = 'hello world!'
    writeFile file:"test.yml", text:yamlToString(yaml)
}

@NonCPS
String yamlToString(Object data){
    def opts = new DumperOptions()
    opts.setDefaultFlowStyle(BLOCK)
    return new Yaml(opts).dump(data)
}

final test.yml:

data:
  info: hello world!
  aaa: bbb
  ddd: ccc

答案 1 :(得分:3)

现在有一个writeYaml,请参阅pipeline-utility-steps-plugin

    mydata = readYaml file: "test.yml"
    //modify
    mydata.info = "b"
    writeYaml file: 'newtest.yaml', data: mydata