zbx_user.py 5.1 KB

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