How to add contents to YAML file using ruamel.yaml?

Viewed 193

Here is the input.yml file

PRODUCT_HOME: /app
config: 
  active-profiles: mysql,oauth2
  driverClassName: com.mysql.cj.jdbc.Driver
  datasourceurl: jdbc:h2:file:./data
  datasourceuser: sa
server:
  error:
    path: /error
  whitelabel:
    enabled: false
  port: 8080

Output file should look like:

PRODUCT_HOME: /app
config: 
  active-profiles: mysql,oauth2
  driverClassName: com.mysql.cj.jdbc.Driver
  datasourceurl: jdbc:h2:file:./data
  datasourceuser: sa
server:
   error:
      path: /error
   whitelabel:
      enabled: false
   port: 8080
   servlet:
     session:
       cookie:
         secure: true

How can I achieve this using Python (ruamel.yaml) package?

1 Answers

You should create the correct data structure for the data you want to add and then add that datastructure to the mapping that is the value of server

import sys
import ruamel.yaml

from pathlib import Path

in_file = Path('input.yaml')
    
nd = dict(servlet=dict(session=dict(cookie=dict(secure=True))))

yaml = ruamel.yaml.YAML()
data = yaml.load(in_file)
data['server'].update(nd)

# print(data)
yaml.dump(data, sys.stdout)

which gives:

PRODUCT_HOME: /app
config:
  active-profiles: mysql,oauth2
  driverClassName: com.mysql.cj.jdbc.Driver
  datasourceurl: jdbc:h2:file:./data
  datasourceuser: sa
server:
  error:
    path: /error
  whitelabel:
    enabled: false
  port: 8080
  servlet:
    session:
      cookie:
        secure: true

Alternatively, if you have the data to add as YAML input you can load that and then update:

yaml_str = """
servlet:
  session:
    cookie:
      secure: true
"""

yaml = ruamel.yaml.YAML()
nd = yaml.load(yaml_str)
data = yaml.load(in_file)
data['server'].update(nd)

# print(data)
yaml.dump(data, sys.stdout)

which also gives:

PRODUCT_HOME: /app
config:
  active-profiles: mysql,oauth2
  driverClassName: com.mysql.cj.jdbc.Driver
  datasourceurl: jdbc:h2:file:./data
  datasourceuser: sa
server:
  error:
    path: /error
  whitelabel:
    enabled: false
  port: 8080
  servlet:
    session:
      cookie:
        secure: true
Related