zbx_user.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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.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_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_usertype(user_type):
  53. '''
  54. Determine zabbix user account type
  55. '''
  56. if not user_type:
  57. return None
  58. utype = 1
  59. if 'super' in user_type:
  60. utype = 3
  61. elif 'admin' in user_type or user_type == 'admin':
  62. utype = 2
  63. return utype
  64. def main():
  65. '''
  66. ansible zabbix module for users
  67. '''
  68. ##def user(self, name, state='present', params=None):
  69. module = AnsibleModule(
  70. argument_spec=dict(
  71. server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'),
  72. user=dict(default=None, type='str'),
  73. password=dict(default=None, type='str'),
  74. alias=dict(default=None, type='str'),
  75. name=dict(default=None, type='str'),
  76. surname=dict(default=None, type='str'),
  77. user_type=dict(default=None, type='str'),
  78. passwd=dict(default=None, type='str'),
  79. usergroups=dict(default=[], type='list'),
  80. debug=dict(default=False, type='bool'),
  81. state=dict(default='present', type='str'),
  82. ),
  83. #supports_check_mode=True
  84. )
  85. user = module.params.get('user', os.environ['ZABBIX_USER'])
  86. password = module.params.get('password', os.environ['ZABBIX_PASSWORD'])
  87. zapi = ZabbixAPI(ZabbixConnection(module.params['server'], user, password, module.params['debug']))
  88. ## before we can create a user media and users with media types we need media
  89. zbx_class_name = 'user'
  90. idname = "userid"
  91. alias = module.params['alias']
  92. state = module.params['state']
  93. content = zapi.get_content(zbx_class_name,
  94. 'get',
  95. {'output': 'extend',
  96. 'search': {'alias': alias},
  97. "selectUsrgrps": 'usergrpid',
  98. })
  99. if state == 'list':
  100. module.exit_json(changed=False, results=content['result'], state="list")
  101. if state == 'absent':
  102. if not exists(content):
  103. module.exit_json(changed=False, state="absent")
  104. content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0][idname]])
  105. module.exit_json(changed=True, results=content['result'], state="absent")
  106. if state == 'present':
  107. params = {'alias': alias,
  108. 'passwd': module.params['passwd'],
  109. 'usrgrps': get_usergroups(zapi, module.params['usergroups']),
  110. 'name': module.params['name'],
  111. 'surname': module.params['surname'],
  112. 'type': get_usertype(module.params['user_type']),
  113. }
  114. # Remove any None valued params
  115. _ = [params.pop(key, None) for key in params.keys() if params[key] is None]
  116. if not exists(content):
  117. # if we didn't find it, create it
  118. content = zapi.get_content(zbx_class_name, 'create', params)
  119. module.exit_json(changed=True, results=content['result'], state='present')
  120. # already exists, we need to update it
  121. # let's compare properties
  122. differences = {}
  123. zab_results = content['result'][0]
  124. for key, value in params.items():
  125. if key == 'passwd':
  126. differences[key] = value
  127. elif zab_results[key] != value and zab_results[key] != str(value):
  128. differences[key] = value
  129. if not differences:
  130. module.exit_json(changed=False, results=zab_results, state="present")
  131. # We have differences and need to update
  132. differences[idname] = zab_results[idname]
  133. content = zapi.get_content(zbx_class_name, 'update', differences)
  134. module.exit_json(changed=True, results=content['result'], state="present")
  135. module.exit_json(failed=True,
  136. changed=False,
  137. results='Unknown state passed. %s' % state,
  138. state="unknown")
  139. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled
  140. # import module snippets. This are required
  141. from ansible.module_utils.basic import *
  142. main()