Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- DOCUMENTATION:
- name: constructed_groups
- plugin_type: inventory
- version_added: "2.4"
- requires_whitelisting: True
- short_description: Uses Jinja2 expressions to construct groups.
- description:
- - Uses a YAML configuration file to identify group and the Jinja2 expressions that qualify a host for membership.
- - Only variables already in inventory are available for expressions (no facts).
- - Failed expressions will be ignored (assumes vars were missing).
- EXAMPLES:
- # inventory.config file in YAML format
- plugin: constructed_groups
- groups:
- # simple name matching
- webservers: inventory_hostname.startswith('web')
- # using ec2 'tags' (assumes aws inventory)
- development: "'devel' in (ec2_tags|list)"
- # using other host properties populated in inventory
- private_only: not (public_dns_name is defined or ip_address is defined)
- # complex group membership
- multi_group: (group_names|intersection(['alpha', 'beta', 'omega']))|length >= 2
- '''
- class InventoryModule(BaseInventoryPlugin):
- """ constructs groups using Jinaj2 template expressions """
- NAME = 'constructed_groups'
- NEEDS_WHITELISTING = True
- TYPE = 'generator'
- def __init__(self):
- super(InventoryModule, self).__init__()
- def verify_file(self, path):
- valid = False
- if super(InventoryModule, self).verify_file(path):
- file_name, ext = os.path.splitext(path)
- if not ext or ext == 'config':
- valid = True
- def parse(self, inventory, loader, path):
- ''' parses the inventory file '''
- super(InventoryModule, self).parse(inventory, loader, path)
- try:
- data = self.loader.load_from_file(path)
- except Exception as e:
- raise AnsibleParserError(e)
- if not data or data.get('plugin') != self.NAME:
- return False
- templar = Templar(loader=loader)
- # Go over hosts (less var copies)
- for hosts in inventory.hosts:
- templar.set_available_variables(host.get_vars())
- for group_name, expression in data.get('groups', {}):
- conditional = u"{%% if %s %%} True {%% else %%} False {%% endif %%}" % expression
- try:
- result = templar.template(conditional)
- if result and bool(result):
- # ensure group exists
- inventory.add_group(group_name)
- # add host to group
- inventory.add_child(group_name, host.name)
- except:
- #FIXME: warn/show on -vvvv/debug?
- pass
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement