Jenkins Groovy - using modified data from readYaml to write back into yml file

安稳与你 提交于 2020-02-02 04:23:06

问题


I am using Jenkins readYaml to read the data as follows:

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

I want to write this modified data back to test.yml in Jenkins. How can this be achieved?


回答1:


test.yml:

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

pipeline script:

@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



回答2:


There is a writeYaml nowadays, see pipeline-utility-steps-plugin

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


来源:https://stackoverflow.com/questions/45694656/jenkins-groovy-using-modified-data-from-readyaml-to-write-back-into-yml-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!