[python] convert dictionary to yaml and vice versa

Nornir framework comes with the pyyaml module installed, hence I do not need to install pyyaml.

Convert dictionary to yaml

The purpose is to accept json data from the api gateway and convert this into yaml in the backend to be sent over to ansible through nornir. The below is a test on convert dictionary to yaml.

import yaml

# sample json structure send by user.
data = {
    "fw01":
        {
            "platform": "cisco_asa",
            "hostname": "192.168.100.20",
            "port": "22",
            "group": ["cisco_asa", "cisco", "firewall"],
            "username": "placeholder",
            "password": "placeholder",
        },
    "fw02":
        {
            "platform": "cisco_asa",
            "hostname": "192.168.100.30",
            "port": "22",
            "username": "placeholder",
            "password": "placeholder"
        }
}

# translate dictionary into yaml format.
y = yaml.dump(data)
print(y)

The yaml structure will be like this:
nor7

Convert from yaml to dictionary

The below code shows how to convert yaml to dictionary.

import yaml
from pprint import pprint

# example yaml 
y = """
fw01:
  group:
  - cisco_asa
  - cisco
  - firewall
  hostname: 192.168.100.20
  password: placeholder
  platform: cisco_asa
  port: '22'
  username: placeholder
fw02:
  hostname: 192.168.100.30
  password: placeholder
  platform: cisco_asa
  port: '22'
  username: placeholder
  """

# translate yaml to dictionary
dic = yaml.safe_load(y)
pprint(dic)

The dictionary output:
nor8

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s