Advertisement
Guest User

Untitled

a guest
Mar 30th, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.63 KB | None | 0 0
  1. '''
  2. DOCUMENTATION:
  3. name: constructed_groups
  4. plugin_type: inventory
  5. version_added: "2.4"
  6. requires_whitelisting: True
  7. short_description: Uses Jinja2 expressions to construct groups.
  8. description:
  9. - Uses a YAML configuration file to identify group and the Jinja2 expressions that qualify a host for membership.
  10. - Only variables already in inventory are available for expressions (no facts).
  11. - Failed expressions will be ignored (assumes vars were missing).
  12. EXAMPLES:
  13. # inventory.config file in YAML format
  14. plugin: constructed_groups
  15. groups:
  16. # simple name matching
  17. webservers: inventory_hostname.startswith('web')
  18.  
  19. # using ec2 'tags' (assumes aws inventory)
  20. development: "'devel' in (ec2_tags|list)"
  21.  
  22. # using other host properties populated in inventory
  23. private_only: not (public_dns_name is defined or ip_address is defined)
  24.  
  25. # complex group membership
  26. multi_group: (group_names|intersection(['alpha', 'beta', 'omega']))|length >= 2
  27. '''
  28. class InventoryModule(BaseInventoryPlugin):
  29. """ constructs groups using Jinaj2 template expressions """
  30.  
  31. NAME = 'constructed_groups'
  32. NEEDS_WHITELISTING = True
  33. TYPE = 'generator'
  34.  
  35. def __init__(self):
  36.  
  37. super(InventoryModule, self).__init__()
  38.  
  39. def verify_file(self, path):
  40.  
  41. valid = False
  42. if super(InventoryModule, self).verify_file(path):
  43. file_name, ext = os.path.splitext(path)
  44.  
  45. if not ext or ext == 'config':
  46. valid = True
  47.  
  48. def parse(self, inventory, loader, path):
  49. ''' parses the inventory file '''
  50.  
  51. super(InventoryModule, self).parse(inventory, loader, path)
  52.  
  53. try:
  54. data = self.loader.load_from_file(path)
  55. except Exception as e:
  56. raise AnsibleParserError(e)
  57.  
  58. if not data or data.get('plugin') != self.NAME:
  59. return False
  60.  
  61. templar = Templar(loader=loader)
  62.  
  63. # Go over hosts (less var copies)
  64. for hosts in inventory.hosts:
  65. templar.set_available_variables(host.get_vars())
  66. for group_name, expression in data.get('groups', {}):
  67. conditional = u"{%% if %s %%} True {%% else %%} False {%% endif %%}" % expression
  68. try:
  69. result = templar.template(conditional)
  70. if result and bool(result):
  71. # ensure group exists
  72. inventory.add_group(group_name)
  73. # add host to group
  74. inventory.add_child(group_name, host.name)
  75. except:
  76. #FIXME: warn/show on -vvvv/debug?
  77. pass
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement