oo_resourceconfig.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. # vim: expandtab:tabstop=4:shiftwidth=4
  4. '''
  5. Filters for configuring resources in openshift-ansible
  6. '''
  7. from ansible import errors
  8. def get_attr(data, attribute=None):
  9. ''' This looks up dictionary attributes of the form a.b.c and returns
  10. the value.
  11. Ex: data = {'a': {'b': {'c': 5}}}
  12. attribute = "a.b.c"
  13. returns 5
  14. '''
  15. if not attribute:
  16. raise errors.AnsibleFilterError("|failed expects attribute to be set")
  17. ptr = data
  18. for attr in attribute.split('.'):
  19. ptr = ptr[attr]
  20. return ptr
  21. def set_attr(item, key, value, attr_key=None, attr_value=None):
  22. if attr_key and attr_value:
  23. actual_attr_value = get_attr(item, attr_key)
  24. if str(attr_value) != str(actual_attr_value):
  25. continue # We only want to set the values on hosts with defined attributes
  26. kvp = item
  27. for attr in key.split('.'):
  28. if attr == key.split('.')[len(key.split('.'))-1]:
  29. kvp[attr] = value
  30. continue
  31. if attr not in kvp:
  32. kvp[attr] = {}
  33. kvp = kvp[attr]
  34. return item
  35. def set_attrs(items, key, value, attr_key=None, attr_value=None):
  36. for item in items:
  37. create_update_key(item, key, value, attr_key, attr_value)
  38. return items
  39. def oo_set_node_label(arg, key, value, attr_key=None, attr_value=None):
  40. ''' This cycles through openshift node definitions
  41. (from "osc get nodes -o json"), and adds a label.
  42. If attr_key and attr_value are set, this will only set the label on
  43. nodes where the attribute matches the specified value.
  44. Ex:
  45. - shell: osc get nodes -o json
  46. register: output
  47. - set_fact:
  48. node_facts: "{{ output.stdout
  49. | from_json
  50. | oo_set_node_label('region', 'infra',
  51. 'metadata.name', '172.16.17.43') }}"
  52. '''
  53. arg['items'] = set_attrs(arg['items'], key, value, attr_key, attr_value)
  54. return arg
  55. def oo_set_resource_node(arg, value):
  56. arg = set_attr(arg, 'template.podTemplate.nodeSelector.region', value)
  57. return arg
  58. class FilterModule(object):
  59. ''' FilterModule '''
  60. def filters(self):
  61. ''' returns a mapping of filters to methods '''
  62. return {
  63. "oo_set_node_label": oo_set_node_label,
  64. "oo_set_resource_node": oo_set_resource_node
  65. }