zbx_usergroup.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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. # Disabling too-many-branches as we need the error checking and the if-statements
  29. # to determine the proper state
  30. # pylint: disable=too-many-branches
  31. # pylint: disable=import-error
  32. from openshift_tools.monitoring.zbxapi import ZabbixAPI, ZabbixConnection
  33. def exists(content, key='result'):
  34. ''' Check if key exists in content or the size of content[key] > 0
  35. '''
  36. if not content.has_key(key):
  37. return False
  38. if not content[key]:
  39. return False
  40. return True
  41. def get_rights(zapi, rights):
  42. '''Get rights
  43. '''
  44. if rights == None:
  45. return None
  46. perms = []
  47. for right in rights:
  48. hstgrp = right.keys()[0]
  49. perm = right.values()[0]
  50. content = zapi.get_content('hostgroup', 'get', {'search': {'name': hstgrp}})
  51. if content['result']:
  52. permission = 0
  53. if perm == 'ro':
  54. permission = 2
  55. elif perm == 'rw':
  56. permission = 3
  57. perms.append({'id': content['result'][0]['groupid'],
  58. 'permission': permission})
  59. return perms
  60. def get_gui_access(access):
  61. ''' Return the gui_access for a usergroup
  62. '''
  63. access = access.lower()
  64. if access == 'internal':
  65. return 1
  66. elif access == 'disabled':
  67. return 2
  68. return 0
  69. def get_debug_mode(mode):
  70. ''' Return the debug_mode for a usergroup
  71. '''
  72. mode = mode.lower()
  73. if mode == 'enabled':
  74. return 1
  75. return 0
  76. def get_user_status(status):
  77. ''' Return the user_status for a usergroup
  78. '''
  79. status = status.lower()
  80. if status == 'enabled':
  81. return 0
  82. return 1
  83. def get_userids(zapi, users):
  84. ''' Get userids from user aliases
  85. '''
  86. if not users:
  87. return None
  88. userids = []
  89. for alias in users:
  90. content = zapi.get_content('user', 'get', {'search': {'alias': alias}})
  91. if content['result']:
  92. userids.append(content['result'][0]['userid'])
  93. return userids
  94. def main():
  95. ''' Ansible module for usergroup
  96. '''
  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. #******#
  127. # GET
  128. #******#
  129. if state == 'list':
  130. module.exit_json(changed=False, results=content['result'], state="list")
  131. #******#
  132. # DELETE
  133. #******#
  134. if state == 'absent':
  135. if not exists(content):
  136. module.exit_json(changed=False, state="absent")
  137. if not uname:
  138. module.exit_json(failed=True, changed=False, results='Need to pass in a user.', state="error")
  139. content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0][idname]])
  140. module.exit_json(changed=True, results=content['result'], state="absent")
  141. # Create and Update
  142. if state == 'present':
  143. params = {'name': uname,
  144. 'rights': get_rights(zapi, module.params['rights']),
  145. 'users_status': get_user_status(module.params['status']),
  146. 'gui_access': get_gui_access(module.params['gui_access']),
  147. 'debug_mode': get_debug_mode(module.params['debug_mode']),
  148. 'userids': get_userids(zapi, module.params['users']),
  149. }
  150. # Remove any None valued params
  151. _ = [params.pop(key, None) for key in params.keys() if params[key] == None]
  152. #******#
  153. # CREATE
  154. #******#
  155. if not exists(content):
  156. # if we didn't find it, create it
  157. content = zapi.get_content(zbx_class_name, 'create', params)
  158. if content.has_key('error'):
  159. module.exit_json(failed=True, changed=True, results=content['error'], state="present")
  160. module.exit_json(changed=True, results=content['result'], state='present')
  161. ########
  162. # UPDATE
  163. ########
  164. differences = {}
  165. zab_results = content['result'][0]
  166. for key, value in params.items():
  167. if key == 'rights':
  168. differences['rights'] = value
  169. elif key == 'userids' and zab_results.has_key('users'):
  170. if zab_results['users'] != value:
  171. differences['userids'] = value
  172. elif zab_results[key] != value and zab_results[key] != str(value):
  173. differences[key] = value
  174. if not differences:
  175. module.exit_json(changed=False, results=zab_results, state="present")
  176. # We have differences and need to update
  177. differences[idname] = zab_results[idname]
  178. content = zapi.get_content(zbx_class_name, 'update', differences)
  179. module.exit_json(changed=True, results=content['result'], state="present")
  180. module.exit_json(failed=True,
  181. changed=False,
  182. results='Unknown state passed. %s' % state,
  183. state="unknown")
  184. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled
  185. # import module snippets. This are required
  186. from ansible.module_utils.basic import *
  187. main()