Search code examples
pythonyamlopenstack

write parameter and value to yaml using python


I have the following YAML file:

heat_template_version: 2015-10-15
parameters:

  image:
    type: string
    label: Image name or ID
    default: CirrOS
  private_network_id:
    type: string
    label: Private network name or ID
  floating_ip:
    type: string

I want to add key-> default to private_network_id and floating_ip (if default doesn't exist) and to the default key I want to add the value (which I get from user)

How can I achieve this in python?

The resulting YAML should look like:

heat_template_version: 2015-10-15
parameters:

  image:
    type: string
    label: Image name or ID
    default: CirrOS
  private_network_id:
    type: string
    label: Private network name or ID
    default: <private_network_id>
  floating_ip:
    type: string
    default: <floating_ip>

Solution

  • For this kind of round-tripping you should do use ruamel.yaml (disclaimer: I am the author of the package).

    Assuming your input is in a file input.yaml and the following program:

    from ruamel.yaml import YAML
    from pathlib import Path
    
    yaml = YAML()
    path = Path('input.yaml')
    
    data = yaml.load(path)
    parameters = data['parameters']
    # replace assigned values with user input
    parameters['private_network_id']['default'] = '<private_network_id>'
    parameters['floating_ip']['default'] = '<floating_ip>'
    yaml.dump(data, path)
    

    After that your file will exact match the output you requested.

    Please note that comments in the YAML file, as well as the key ordering are automatically preserved (not guaranteed by the YAML specification).

    If you are still using Python2 (which has no pathlib in the standard library) use from ruamel.std.pathlib import Path or rewrite the .load() and .dump() lines with appropriately opened, old style, file objects. E.g.

    with open('input.yaml', 'w') as fp:
        yaml.dump(data, fp)