Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 303
ajroot Avatar asked Aug 15 '17 14:08

ajroot


People also ask

How do I update Yaml file in Jenkins pipeline?

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.

What is NonCPS Jenkinsfile?

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).


1 Answers

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
like image 191
daggett Avatar answered Oct 04 '22 01:10

daggett