diff --git a/lib/ansible/plugins/inventory/__init__.py b/lib/ansible/plugins/inventory/__init__.py index 1c3aebcb16..32cba841f3 100644 --- a/lib/ansible/plugins/inventory/__init__.py +++ b/lib/ansible/plugins/inventory/__init__.py @@ -429,7 +429,9 @@ class Constructable(object): self.inventory.add_child(parent_name, result_gname) else: - if strict: - raise AnsibleParserError("No key or key resulted empty, invalid entry") + # exclude case of empty list and dictionary, because these are valid constructions + # simply no groups need to be constructed, but are still falsy + if strict and key not in ([], {}): + raise AnsibleParserError("No key or key resulted empty for %s in host %s, invalid entry" % (keyed.get('key'), host)) else: raise AnsibleParserError("Invalid keyed group entry, it must be a dictionary: %s " % keyed) diff --git a/test/units/plugins/inventory/test_constructed.py b/test/units/plugins/inventory/test_constructed.py index ba09692bba..d298ffe00c 100644 --- a/test/units/plugins/inventory/test_constructed.py +++ b/test/units/plugins/inventory/test_constructed.py @@ -24,7 +24,7 @@ from ansible.inventory.data import InventoryData from ansible.template import Templar -@pytest.fixture(scope="module") +@pytest.fixture() def inventory_module(): r = InventoryModule() r.inventory = InventoryData() @@ -60,13 +60,11 @@ def test_keyed_group_separator(inventory_module): { 'prefix': 'farmer', 'separator': '_old_', - 'key': 'farmer', - 'unsafe': True + 'key': 'farmer' }, { 'separator': 'mmmmmmmmmm', - 'key': 'barn', - 'unsafe': True + 'key': 'barn' } ] inventory_module._add_host_to_keyed_groups( @@ -78,6 +76,22 @@ def test_keyed_group_separator(inventory_module): assert group.hosts == [host] +def test_keyed_group_empty_construction(inventory_module): + inventory_module.inventory.add_host('farm') + inventory_module.inventory.set_variable('farm', 'barn', {}) + host = inventory_module.inventory.get_host('farm') + keyed_groups = [ + { + 'separator': 'mmmmmmmmmm', + 'key': 'barn' + } + ] + inventory_module._add_host_to_keyed_groups( + keyed_groups, host.vars, host.name, strict=True + ) + assert host.groups == [] + + def test_keyed_parent_groups(inventory_module): inventory_module.inventory.add_host('web1') inventory_module.inventory.add_host('web2')