zbx_usergroup.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. #!/usr/bin/env python
  2. '''
  3. zabbix ansible module for usergroups
  4. '''
  5. # vim: expandtab:tabstop=4:shiftwidth=4
  6. #
  7. # Zabbix usergroup ansible module
  8. #
  9. #
  10. # Copyright 2015 Red Hat Inc.
  11. #
  12. # Licensed under the Apache License, Version 2.0 (the "License");
  13. # you may not use this file except in compliance with the License.
  14. # You may obtain a copy of the License at
  15. #
  16. # http://www.apache.org/licenses/LICENSE-2.0
  17. #
  18. # Unless required by applicable law or agreed to in writing, software
  19. # distributed under the License is distributed on an "AS IS" BASIS,
  20. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21. # See the License for the specific language governing permissions and
  22. # limitations under the License.
  23. #
  24. # This is in place because each module looks similar to each other.
  25. # These need duplicate code as their behavior is very similar
  26. # but different for each zabbix class.
  27. # pylint: disable=duplicate-code
  28. # pylint: disable=import-error
  29. from openshift_tools.monitoring.zbxapi import ZabbixAPI, ZabbixConnection
  30. def exists(content, key='result'):
  31. ''' Check if key exists in content or the size of content[key] > 0
  32. '''
  33. if not content.has_key(key):
  34. return False
  35. if not content[key]:
  36. return False
  37. return True
  38. def get_rights(zapi, rights):
  39. '''Get rights
  40. '''
  41. if rights == None:
  42. return None
  43. perms = []
  44. for right in rights:
  45. hstgrp = right.keys()[0]
  46. perm = right.values()[0]
  47. content = zapi.get_content('hostgroup', 'get', {'search': {'name': hstgrp}})
  48. if content['result']:
  49. permission = 0
  50. if perm == 'ro':
  51. permission = 2
  52. elif perm == 'rw':
  53. permission = 3
  54. perms.append({'id': content['result'][0]['groupid'],
  55. 'permission': permission})
  56. return perms
  57. def get_gui_access(access):
  58. ''' Return the gui_access for a usergroup
  59. '''
  60. access = access.lower()
  61. if access == 'internal':
  62. return 1
  63. elif access == 'disabled':
  64. return 2
  65. return 0
  66. def get_debug_mode(mode):
  67. ''' Return the debug_mode for a usergroup
  68. '''
  69. mode = mode.lower()
  70. if mode == 'enabled':
  71. return 1
  72. return 0
  73. def get_user_status(status):
  74. ''' Return the user_status for a usergroup
  75. '''
  76. status = status.lower()
  77. if status == 'enabled':
  78. return 0
  79. return 1
  80. #def get_userids(zapi, users):
  81. # ''' Get userids from user aliases
  82. # '''
  83. # if not users:
  84. # return None
  85. #
  86. # userids = []
  87. # for alias in users:
  88. # content = zapi.get_content('user', 'get', {'search': {'alias': alias}})
  89. # if content['result']:
  90. # userids.append(content['result'][0]['userid'])
  91. #
  92. # return userids
  93. def main():
  94. ''' Ansible module for usergroup
  95. '''
  96. ##def usergroup(self, name, rights=None, users=None, state='present', params=None):
  97. module = AnsibleModule(
  98. argument_spec=dict(
  99. zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'),
  100. zbx_user=dict(default=os.environ.get('ZABBIX_USER', None), type='str'),
  101. zbx_password=dict(default=os.environ.get('ZABBIX_PASSWORD', None), type='str'),
  102. zbx_debug=dict(default=False, type='bool'),
  103. debug_mode=dict(default='disabled', type='str'),
  104. gui_access=dict(default='default', type='str'),
  105. status=dict(default='enabled', type='str'),
  106. name=dict(default=None, type='str', required=True),
  107. rights=dict(default=None, type='list'),
  108. #users=dict(default=None, type='list'),
  109. state=dict(default='present', type='str'),
  110. ),
  111. #supports_check_mode=True
  112. )
  113. zapi = ZabbixAPI(ZabbixConnection(module.params['zbx_server'],
  114. module.params['zbx_user'],
  115. module.params['zbx_password'],
  116. module.params['zbx_debug']))
  117. zbx_class_name = 'usergroup'
  118. idname = "usrgrpid"
  119. uname = module.params['name']
  120. state = module.params['state']
  121. content = zapi.get_content(zbx_class_name,
  122. 'get',
  123. {'search': {'name': uname},
  124. 'selectUsers': 'userid',
  125. })
  126. if state == 'list':
  127. module.exit_json(changed=False, results=content['result'], state="list")
  128. if state == 'absent':
  129. if not exists(content):
  130. module.exit_json(changed=False, state="absent")
  131. if not uname:
  132. module.exit_json(failed=True, changed=False, results='Need to pass in a user.', state="error")
  133. content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0][idname]])
  134. module.exit_json(changed=True, results=content['result'], state="absent")
  135. if state == 'present':
  136. params = {'name': uname,
  137. 'rights': get_rights(zapi, module.params['rights']),
  138. 'users_status': get_user_status(module.params['status']),
  139. 'gui_access': get_gui_access(module.params['gui_access']),
  140. 'debug_mode': get_debug_mode(module.params['debug_mode']),
  141. #'userids': get_userids(zapi, module.params['users']),
  142. }
  143. _ = [params.pop(key, None) for key in params.keys() if params[key] == None]
  144. if not exists(content):
  145. # if we didn't find it, create it
  146. content = zapi.get_content(zbx_class_name, 'create', params)
  147. module.exit_json(changed=True, results=content['result'], state='present')
  148. # already exists, we need to update it
  149. # let's compare properties
  150. differences = {}
  151. zab_results = content['result'][0]
  152. for key, value in params.items():
  153. if key == 'rights':
  154. differences['rights'] = value
  155. #elif key == 'userids' and zab_results.has_key('users'):
  156. #if zab_results['users'] != value:
  157. #differences['userids'] = value
  158. elif zab_results[key] != value and zab_results[key] != str(value):
  159. differences[key] = value
  160. if not differences:
  161. module.exit_json(changed=False, results=zab_results, state="present")
  162. # We have differences and need to update
  163. differences[idname] = zab_results[idname]
  164. content = zapi.get_content(zbx_class_name, 'update', differences)
  165. module.exit_json(changed=True, results=content['result'], state="present")
  166. module.exit_json(failed=True,
  167. changed=False,
  168. results='Unknown state passed. %s' % state,
  169. state="unknown")
  170. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled
  171. # import module snippets. This are required
  172. from ansible.module_utils.basic import *
  173. main()