Add keyed_groups feature (#52045)

This implements:
- Allow creating keyed group parents
This commit is contained in:
Alan Rominger 2019-03-05 13:34:34 -05:00 committed by Sloane Hertel
commit 56e3597856
4 changed files with 132 additions and 10 deletions

View file

@ -335,7 +335,6 @@ class Constructable(object):
def _add_host_to_keyed_groups(self, keys, variables, host, strict=False):
''' helper to create groups for plugins based on variable values and add the corresponding hosts to it'''
if keys and isinstance(keys, list):
groups = []
for keyed in keys:
if keyed and isinstance(keyed, dict):
@ -349,26 +348,33 @@ class Constructable(object):
if key:
prefix = keyed.get('prefix', '')
sep = keyed.get('separator', '_')
raw_parent_name = keyed.get('parent_group', None)
new_raw_group_names = []
if isinstance(key, string_types):
groups.append('%s%s%s' % (prefix, sep, key))
new_raw_group_names.append(key)
elif isinstance(key, list):
for name in key:
groups.append('%s%s%s' % (prefix, sep, name))
new_raw_group_names.append(name)
elif isinstance(key, Mapping):
for (gname, gval) in key.items():
name = '%s%s%s' % (gname, sep, gval)
groups.append('%s%s%s' % (prefix, sep, name))
new_raw_group_names.append(name)
else:
raise AnsibleParserError("Invalid group name format, expected a string or a list of them or dictionary, got: %s" % type(key))
for bare_name in new_raw_group_names:
gname = to_safe_group_name('%s%s%s' % (prefix, sep, bare_name))
self.inventory.add_group(gname)
self.inventory.add_child(gname, host)
if raw_parent_name:
parent_name = to_safe_group_name(raw_parent_name)
self.inventory.add_group(parent_name)
self.inventory.add_child(parent_name, gname)
else:
if strict:
raise AnsibleParserError("No key or key resulted empty, invalid entry")
else:
raise AnsibleParserError("Invalid keyed group entry, it must be a dictionary: %s " % keyed)
# now actually add any groups
for group_name in groups:
gname = to_safe_group_name(group_name)
self.inventory.add_group(gname)
self.inventory.add_child(gname, host)

View file

@ -53,9 +53,19 @@ EXAMPLES = r'''
- prefix: distro
key: ansible_distribution
# the following examples assume the first inventory is from contrib/inventory/ec2.py
# this creates a group per ec2 architecture and assign hosts to the matching ones (arch_x86_64, arch_sparc, etc)
- prefix: arch
key: ec2_architecture
# this creates a group per ec2 region like "us_west_1"
- prefix: ""
separator: ""
key: ec2_region
# this creates a common parent group for all ec2 availability zones
- key: ec2_placement
parent_group: all_ec2_zones
'''
import os