oo_filters.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. from ansible import errors, runner
  2. import json
  3. import pdb
  4. def oo_pdb(arg):
  5. ''' This pops you into a pdb instance where arg is the data passed in from the filter.
  6. Ex: "{{ hostvars | oo_pdb }}"
  7. '''
  8. pdb.set_trace()
  9. return arg
  10. def oo_len(arg):
  11. ''' This returns the length of the argument
  12. Ex: "{{ hostvars | oo_len }}"
  13. '''
  14. return len(arg)
  15. def get_attr(data, attribute=None):
  16. ''' This looks up dictionary attributes of the form a.b.c and returns the value.
  17. Ex: data = {'a': {'b': {'c': 5}}}
  18. attribute = "a.b.c"
  19. returns 5
  20. '''
  21. if not attribute:
  22. raise errors.AnsibleFilterError("|failed expects attribute to be set")
  23. ptr = data
  24. for attr in attribute.split('.'):
  25. ptr = ptr[attr]
  26. return ptr
  27. def oo_collect(data, attribute=None, filters={}):
  28. ''' This takes a list of dict and collects all attributes specified into a list
  29. If filter is specified then we will include all items that match _ALL_ of filters.
  30. Ex: data = [ {'a':1, 'b':5, 'z': 'z'}, # True, return
  31. {'a':2, 'z': 'z'}, # True, return
  32. {'a':3, 'z': 'z'}, # True, return
  33. {'a':4, 'z': 'b'}, # FAILED, obj['z'] != obj['z']
  34. ]
  35. attribute = 'a'
  36. filters = {'z': 'z'}
  37. returns [1, 2, 3]
  38. '''
  39. if not issubclass(type(data), list):
  40. raise errors.AnsibleFilterError("|failed expects to filter on a List")
  41. if not attribute:
  42. raise errors.AnsibleFilterError("|failed expects attribute to be set")
  43. if filters:
  44. retval = [get_attr(d, attribute) for d in data if all([ d[key] == filters[key] for key in filters ]) ]
  45. else:
  46. retval = [get_attr(d, attribute) for d in data]
  47. return retval
  48. def oo_select_keys(data, keys):
  49. ''' This returns a list, which contains the value portions for the keys
  50. Ex: data = { 'a':1, 'b':2, 'c':3 }
  51. keys = ['a', 'c']
  52. returns [1, 3]
  53. '''
  54. if not issubclass(type(data), dict):
  55. raise errors.AnsibleFilterError("|failed expects to filter on a Dictionary")
  56. if not issubclass(type(keys), list):
  57. raise errors.AnsibleFilterError("|failed expects first param is a list")
  58. # Gather up the values for the list of keys passed in
  59. retval = [data[key] for key in keys]
  60. return retval
  61. class FilterModule (object):
  62. def filters(self):
  63. return {
  64. "oo_select_keys": oo_select_keys,
  65. "oo_collect": oo_collect,
  66. "oo_len": oo_len,
  67. "oo_pdb": oo_pdb
  68. }