Skip to content

Commit

Permalink
Merge pull request #146 from nornir-automation/serialize
Browse files Browse the repository at this point in the history
add to_dict function so the inventory is serializable
  • Loading branch information
dbarrosop committed Jun 8, 2018
2 parents afc1916 + 15a0631 commit 8c263ce
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
8 changes: 8 additions & 0 deletions nornir/core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ def reset_failed_hosts(self):
"""Reset failed hosts and make all hosts available for future tasks."""
self.failed_hosts = set()

def to_dict(self):
""" Return a dictionary representing the object. """
return self.__dict__


class Nornir(object):
"""
Expand Down Expand Up @@ -249,6 +253,10 @@ def run(
self.data.failed_hosts.update(result.failed_hosts.keys())
return result

def to_dict(self):
""" Return a dictionary representing the object. """
return {"data": self.data.to_dict(), "inventory": self.inventory.to_dict()}


def InitNornir(config_file="", dry_run=False, **kwargs):
"""
Expand Down
12 changes: 12 additions & 0 deletions nornir/core/inventory.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,10 @@ def items(self):
"""
return self._resolve_data().items()

def to_dict(self):
""" Return a dictionary representing the object. """
return self.data

def has_parent_group(self, group):
"""Retuns whether the object is a child of the :obj:`Group` ``group``"""
for g in self.groups:
Expand Down Expand Up @@ -363,3 +367,11 @@ def nornir(self, value):

for g in self.groups.values():
g.nornir = value

def to_dict(self):
""" Return a dictionary representing the object. """
groups = {k: v.to_dict() for k, v in self.groups.items()}
groups["defaults"] = self.defaults
return {
"hosts": {k: v.to_dict() for k, v in self.hosts.items()}, "groups": groups
}
33 changes: 33 additions & 0 deletions tests/core/test_inventory.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,3 +204,36 @@ def test_has_parents(self):
assert not inventory.hosts["dev1.group_1"].has_parent_group(
inventory.groups["group_2"]
)

def test_to_dict(self):
expected = {
"hosts": {
"dev1.group_1": {
"name": "dev1.group_1",
"groups": ["group_1"],
"my_var": "comes_from_dev1.group_1",
"www_server": "nginx",
"role": "www",
"nornir_ssh_port": 65001,
"nornir_nos": "eos",
},
"dev3.group_2": {
"name": "dev3.group_2",
"groups": ["group_2"],
"www_server": "apache",
"role": "www",
"nornir_ssh_port": 65003,
"nornir_network_api_port": 12443,
"nornir_os": "linux",
"nornir_nos": "mock",
},
},
"groups": {
"defaults": {},
"group_1": {
"name": "group_1", "my_var": "comes_from_group_1", "site": "site1"
},
"group_2": {"name": "group_2", "site": "site2"},
},
}
assert inventory.filter(role="www").to_dict() == expected

0 comments on commit 8c263ce

Please sign in to comment.