Issue
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?
Solution
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
Answered By - daggett
Answer Checked By - Marilyn (JavaFixing Volunteer)