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:
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: