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

ajr*_*oot 4 groovy yaml jenkins

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

data = readYaml file: "test.yml"
//modify
data.info = "b"
Run Code Online (Sandbox Code Playgroud)

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

Tho*_*iam 11

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

    mydata = readYaml file: "test.yml"
    //modify
    mydata.info = "b"
    writeYaml file: 'newtest.yaml', data: mydata
Run Code Online (Sandbox Code Playgroud)


dag*_*ett 7

test.yml:

data:
  info: change me
  aaa: bbb
  ddd: ccc
Run Code Online (Sandbox Code Playgroud)

管道脚本:

@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)
}
Run Code Online (Sandbox Code Playgroud)

final test.yml:

data:
  info: hello world!
  aaa: bbb
  ddd: ccc
Run Code Online (Sandbox Code Playgroud)