简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM