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?
There is a parameter you can use to overwrite the content of designated file: writeYaml: Write a yaml from an object. ... overwrite (optional): Allow existing files to be overwritten. Defaults to false.
The @NonCPS annotation is useful when you have methods which use objects which aren't serializable. Normally, all objects that you create in your pipeline script must be serializable (the reason for this is that Jenkins must be able to serialize the state of the script so that it can be paused and stored on disk).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With