Search code examples
pythonyamlpyyaml

python insert yaml in a yaml as inline or string


hi i'm trying to read a insert a item in a yaml file, which contains yaml in yaml as string following is the yaml

apiVersion: v1
kind: ConfigMap
metadata:
  name: conf
  labels:
    name: conf
  namespace: conf
data:
  blackbox.yml: |
    - labels:
        module: http_2xx_get
      targets:
      - https://xxx.asd.com/pa

i want to insert a new url in targets like this

apiVersion: v1
kind: ConfigMap
metadata:
  name: conf
  labels:
    name: conf
  namespace: conf
data:
  blackbox.yml: |
    - labels:
        module: http_2xx_get
      targets:
      - https://xxx.asd.com/pa
      - https://xxx1.asd.com/pa

following is my code to insert. it considers as string and doesn't work properly.

import yaml

probes = {"app": "/Users/asd/prometheus-configmap.yml"}

with open(probes['app'], 'r') as file:
    app_list = yaml.load(file, Loader=yaml.FullLoader)

    probes = yaml.safe_load(app_list['data']['blackbox.yml'])
    probes[0]['targets'].append("https://xxx1.asd.com/pa")
    with open("test.yml", "w") as yaml_file:
        yaml.dump(app_list, yaml_file)

output of the yaml file:

apiVersion: v1
data:
  blackbox-flights.yml: "- labels:\n    module: http_2xx_get\n  targets:\n  - https://xxx.asd.com/pa\n\
    \  - https://xxx1.asd.com/pa\n"
kind: ConfigMap
metadata:
  labels:
    name: conf
  name: conf
  namespace: conf


Solution

  • I've used the following solution from here and its working fine.

    Thanks to @Gary van der Merwe

    here's my code:

    class literal_unicode(str):
        pass
    
    
    def literal_unicode_representer(dumper, data):
        return dumper.represent_scalar(u'tag:yaml.org,2002:str', data, style='|')
    
    import yaml
    
    probes = {"app": "/Users/asd/prometheus-configmap.yml"}
    
    with open(probes['app'], 'r') as file:
        app_list = yaml.load(file, Loader=yaml.FullLoader)
    
        probes = yaml.safe_load(app_list['data']['blackbox.yml'])
        probes[0]['targets'].append("https://xxx1.asd.com/pa")
        yaml.add_representer(literal_unicode, literal_unicode_representer)
        data = {
            'blackbox.yml': literal_unicode(yaml.dump(probes))}
        app_list['data'] = data
        with open("test.yml", "w") as yaml_file:
            yaml.dump(app_list, yaml_file)