-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsimpleDict.py
102 lines (73 loc) · 2.67 KB
/
simpleDict.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# Custom Inventory - Reads dicts as arguments to build inventory
# copied from
# https://github.com/nornir-automation/nornir/blob/develop/nornir/plugins/inventory/simple.py
# and modified for dict input
#
# Other custom inventory examples
# https://github.com/nornir-automation/nornir3_demo/blob/master/nornir3_demo/plugins/inventory/acme.py
#
#
"""
Usage:
from nornir import InitNornir
# Custom inventory - dict format
from nornir.core.plugins.inventory import InventoryPluginRegister
from simpleDict import SimpleInventoryDict
InventoryPluginRegister.register("simpleDict", SimpleInventoryDict)
# or use whatever plugin register method you like
hosts_dict = {}
groups_dict = {}
defaults_dict = {}
# build hosts,groups, and defaults dicts however you need
# then
nr = InitNornir(config_file='config.yaml',
inventory={
"plugin": "simpleDict",
"options": {
"hosts_dict" : hosts_dict,
"groups_dict": groups_dict,
"defaults_dict": defaults_dict,
},
})
print(len(nr.inventory.hosts))
"""
import logging
from nornir.plugins.inventory.simple import _get_defaults,_get_inventory_element
from nornir.core.inventory import (
Inventory,
Groups,
Hosts,
Defaults,
)
logger = logging.getLogger(__name__)
class SimpleInventoryDict:
def __init__(
self,
hosts_dict: dict = {},
groups_dict: dict = {},
defaults_dict: dict = {},
) -> None:
"""
SimpleInventoryDict is an inventory plugin that loads data from python dictionaries.
The dicts follow the same structure as the native objects
Args:
host_dict: dict with hosts definition
group_dict: dict with groups definition.
defaults_dict: dict with defaults definition.
"""
self.defaults_dict = defaults_dict
self.hosts_dict = hosts_dict
self.groups_dict = groups_dict
def load(self) -> Inventory:
defaults = _get_defaults(self.defaults_dict)
hosts = Hosts()
for n, h in self.hosts_dict.items():
hosts[n] = _get_inventory_element(Host, h, n, defaults)
groups = Groups()
for n, g in self.groups_dict.items():
groups[n] = _get_inventory_element(Group, g, n, defaults)
for h in hosts.values():
h.groups = ParentGroups([groups[g] for g in h.groups])
for g in groups.values():
g.groups = ParentGroups([groups[g] for g in g.groups])
return Inventory(hosts=hosts, groups=groups, defaults=defaults)