Search code examples
jenkinsgroovyjenkins-pipelinepipelinejenkins-groovy

How to append the new tag to the list of existing tag in the yaml file using groovy/pipeline script


I have a yaml file(config.yaml) with tags/structure similar to what is mentioned below. I need to add a new tenant(tenant3) to the list of the existing tenants. How do I achieve it using the pipeline/groovy script? Any help/lead would be appreciated.

consumer_services:
- security
- token
id: 10000
tenants:
  tenant_1:
    state: all
    web_token: true
    cluster_pairs:
    - cluster1
    datacenter: local
    client: CLIENT_TEST
  tenant_2:
    state: all
    web_token: true
    cluster_pairs:
    - cluster2
    datacenter: local
    client: CLIENT_TEST
base_network:
    subnets:
    - 10.160.10.10
    - 10.179.1.09

Solution

  • I think you need to do something like that:

    @Grab('org.yaml:snakeyaml:1.17')
    
    import org.yaml.snakeyaml.DumperOptions
    import org.yaml.snakeyaml.Yaml
    
    def options = new DumperOptions()
    options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK)
    
    Yaml yaml = new Yaml(options)
    
    // load existing structure
    def structure = yaml.load(new File("original.yml").text)
    
    // modify the structure
    structure.tenants.tenant_3 =
        [
            state        : 'all',
            web_token    : true,
            cluster_pairs: ['cluster3'],
            datacenter   : 'local',
            client       : 'CLIENT_TEST'
        ]
    
    // save to the new file
    new File("modified.yml").write(yaml.dump(structure))
    

    So the steps are:

    1. load the data from file into the memory
    2. modify the structure in a way you like
    3. store the modified structure to the file

    I hope it will help.