oo_filters.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 size of the argument
  12. Ex: "{{ hostvars | oo_size }}"
  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):
  28. ''' This takes a list of dict and collects all attributes specified into a list
  29. Ex: data = [ {'a':1,'b':5}, {'a':2}, {'a':3} ]
  30. attribute = 'a'
  31. returns [1, 2, 3]
  32. '''
  33. if not issubclass(type(data), list):
  34. raise errors.AnsibleFilterError("|failed expects to filter on a List")
  35. if not attribute:
  36. raise errors.AnsibleFilterError("|failed expects attribute to be set")
  37. retval = [get_attr(d, attribute) for d in data]
  38. return retval
  39. def oo_select_keys(data, keys):
  40. ''' This returns a list, which contains the value portions for the keys
  41. Ex: data = { 'a':1, 'b':2, 'c':3 }
  42. keys = ['a', 'c']
  43. returns [1, 3]
  44. '''
  45. if not issubclass(type(data), dict):
  46. raise errors.AnsibleFilterError("|failed expects to filter on a Dictionary")
  47. if not issubclass(type(keys), list):
  48. raise errors.AnsibleFilterError("|failed expects first param is a list")
  49. # Gather up the values for the list of keys passed in
  50. retval = [data[key] for key in keys]
  51. return retval
  52. class FilterModule (object):
  53. def filters(self):
  54. return {
  55. "oo_select_keys": oo_select_keys,
  56. "oo_collect": oo_collect,
  57. "oo_len": oo_len,
  58. "oo_pdb": oo_pdb
  59. }