zbx_user.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. #!/usr/bin/env python
  2. '''
  3. ansible module for zabbix users
  4. '''
  5. # vim: expandtab:tabstop=4:shiftwidth=4
  6. #
  7. # Zabbix user 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.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_usergroups(zapi, usergroups):
  39. ''' Get usergroups
  40. '''
  41. ugroups = []
  42. for ugr in usergroups:
  43. content = zapi.get_content('usergroup',
  44. 'get',
  45. {'search': {'name': ugr},
  46. #'selectUsers': 'userid',
  47. #'getRights': 'extend'
  48. })
  49. if content['result']:
  50. ugroups.append({'usrgrpid': content['result'][0]['usrgrpid']})
  51. return ugroups or None
  52. def get_passwd(passwd):
  53. '''Determine if password is set, if not, return 'zabbix'
  54. '''
  55. if passwd:
  56. return passwd
  57. return 'zabbix'
  58. def get_usertype(user_type):
  59. '''
  60. Determine zabbix user account type
  61. '''
  62. if not user_type:
  63. return None
  64. utype = 1
  65. if 'super' in user_type:
  66. utype = 3
  67. elif 'admin' in user_type or user_type == 'admin':
  68. utype = 2
  69. return utype
  70. def main():
  71. '''
  72. ansible zabbix module for users
  73. '''
  74. ##def user(self, name, state='present', params=None):
  75. module = AnsibleModule(
  76. argument_spec=dict(
  77. zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'),
  78. zbx_user=dict(default=os.environ.get('ZABBIX_USER', None), type='str'),
  79. zbx_password=dict(default=os.environ.get('ZABBIX_PASSWORD', None), type='str'),
  80. zbx_debug=dict(default=False, type='bool'),
  81. login=dict(default=None, type='str'),
  82. first_name=dict(default=None, type='str'),
  83. last_name=dict(default=None, type='str'),
  84. user_type=dict(default=None, type='str'),
  85. password=dict(default=None, type='str'),
  86. refresh=dict(default=None, type='int'),
  87. update_password=dict(default=False, type='bool'),
  88. user_groups=dict(default=[], type='list'),
  89. state=dict(default='present', type='str'),
  90. ),
  91. #supports_check_mode=True
  92. )
  93. zapi = ZabbixAPI(ZabbixConnection(module.params['zbx_server'],
  94. module.params['zbx_user'],
  95. module.params['zbx_password'],
  96. module.params['zbx_debug']))
  97. ## before we can create a user media and users with media types we need media
  98. zbx_class_name = 'user'
  99. idname = "userid"
  100. state = module.params['state']
  101. content = zapi.get_content(zbx_class_name,
  102. 'get',
  103. {'output': 'extend',
  104. 'search': {'alias': module.params['login']},
  105. "selectUsrgrps": 'usergrpid',
  106. })
  107. if state == 'list':
  108. module.exit_json(changed=False, results=content['result'], state="list")
  109. if state == 'absent':
  110. if not exists(content) or len(content['result']) == 0:
  111. module.exit_json(changed=False, state="absent")
  112. content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0][idname]])
  113. module.exit_json(changed=True, results=content['result'], state="absent")
  114. if state == 'present':
  115. params = {'alias': module.params['login'],
  116. 'passwd': get_passwd(module.params['password']),
  117. 'usrgrps': get_usergroups(zapi, module.params['user_groups']),
  118. 'name': module.params['first_name'],
  119. 'surname': module.params['last_name'],
  120. 'refresh': module.params['refresh'],
  121. 'type': get_usertype(module.params['user_type']),
  122. }
  123. # Remove any None valued params
  124. _ = [params.pop(key, None) for key in params.keys() if params[key] is None]
  125. if not exists(content):
  126. # if we didn't find it, create it
  127. content = zapi.get_content(zbx_class_name, 'create', params)
  128. if content.has_key('Error'):
  129. module.exit_json(failed=True, changed=False, results=content, state='present')
  130. module.exit_json(changed=True, results=content['result'], state='present')
  131. # already exists, we need to update it
  132. # let's compare properties
  133. differences = {}
  134. # Update password
  135. if not module.params['update_password']:
  136. params.pop('passwd', None)
  137. zab_results = content['result'][0]
  138. for key, value in params.items():
  139. if key == 'usrgrps':
  140. # this must be done as a list of ordered dictionaries fails comparison
  141. if not all([_ in value for _ in zab_results[key]]):
  142. differences[key] = value
  143. elif zab_results[key] != value and zab_results[key] != str(value):
  144. differences[key] = value
  145. if not differences:
  146. module.exit_json(changed=False, results=zab_results, state="present")
  147. # We have differences and need to update
  148. differences[idname] = zab_results[idname]
  149. content = zapi.get_content(zbx_class_name, 'update', differences)
  150. module.exit_json(changed=True, results=content['result'], state="present")
  151. module.exit_json(failed=True,
  152. changed=False,
  153. results='Unknown state passed. %s' % state,
  154. state="unknown")
  155. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled
  156. # import module snippets. This are required
  157. from ansible.module_utils.basic import *
  158. main()