YAML, yaml.safe_load & merging defaults, groups and hosts

Group settings in a YAML inventory

Lesson 4 of 20 · 14 min · Module 1: First steps with automation

Most devices share most settings. A YAML inventory keeps shared values once, in defaults and groups, so each host lists only what is different. Nornir and Ansible inventories work the same way.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Read YAML into Python data
  • Merge defaults, group and host settings
  • Remove keys that are not for Netmiko

The idea

YAML is a readable format for nested data: indentation makes dictionaries, and - item makes lists. yaml.safe_load(f) turns it into Python dictionaries and lists. Merge settings with {**defaults, **group, **host}: when a key appears more than once, the value unpacked last wins, so a host can override its group and a group can override the defaults. Use safe_load, never plain yaml.load, on files that other people can edit.

import yaml

with open("inventory.yaml") as f:
    data = yaml.safe_load(f)
print(data["defaults"])
print(data["hosts"]["sw3"])

01YAML becomes dictionaries

safe_load returns ordinary Python data. Numbers stay numbers: port is the integer 22, not the string "22".

import yaml

with open("inventory.yaml") as f:
    data = yaml.safe_load(f)
print(data["defaults"])
print(data["hosts"]["sw3"])
Output
{'username': 'netadmin', 'port': 22}
{'host': '10.0.0.13', 'group': 'huawei'}

02The last value wins

Unpacking two dictionaries into one keeps every key. For a key in both, the second value replaces the first.

print({**{"port": 22, "username": "netadmin"}, **{"port": 2222}})
Output
{'port': 2222, 'username': 'netadmin'}

03pop() removes a key and returns it

pop is handy for keys that only organise the inventory, such as group: you read the value and remove it in one step.

host = {"host": "10.0.0.13", "group": "huawei"}
print(host.pop("group"))
print(host)
Output
huawei
{'host': '10.0.0.13'}

Your turn

Load inventory.yaml and build inventory: a dictionary mapping each host name to its complete Netmiko dictionary. Merge the defaults, then the host's group, then the host itself; remove the group key and add the password from NET_PASSWORD. Then connect to sw5 and print its prompt.

What the checks look for

  • inventory has every host
  • sw5 merges defaults, its group and the host
  • Cisco hosts get the cisco_ios driver
  • No group key is left
  • Connected to sw5 and printed its prompt
Try it in the editor →

Take this with you

Store shared settings once and merge them in order: defaults, then group, then host.

Go a little further

Give sw5 its own port: 22 under hosts in a copy of the YAML text, and check that the host value wins over the defaults.

Learn Network Automation for free

20 short lessons with real code and instant checks.

See the whole course →