zbx_usergroup.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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. perms = []
  42. for right in rights:
  43. hstgrp = right.keys()[0]
  44. perm = right.values()[0]
  45. content = zapi.get_content('hostgroup', 'get', {'search': {'name': hstgrp}})
  46. if content['result']:
  47. permission = 0
  48. if perm == 'ro':
  49. permission = 2
  50. elif perm == 'rw':
  51. permission = 3
  52. perms.append({'id': content['result'][0]['groupid'],
  53. 'permission': permission})
  54. return perms
  55. def get_userids(zapi, users):
  56. ''' Get userids from user aliases
  57. '''
  58. userids = []
  59. for alias in users:
  60. content = zapi.get_content('user', 'get', {'search': {'alias': alias}})
  61. if content['result']:
  62. userids.append(content['result'][0]['userid'])
  63. return userids
  64. def main():
  65. ''' Ansible module for usergroup
  66. '''
  67. ##def usergroup(self, name, rights=None, users=None, state='present', params=None):
  68. module = AnsibleModule(
  69. argument_spec=dict(
  70. server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'),
  71. user=dict(default=None, type='str'),
  72. password=dict(default=None, type='str'),
  73. name=dict(default=None, type='str'),
  74. rights=dict(default=[], type='list'),
  75. users=dict(default=[], type='list'),
  76. debug=dict(default=False, type='bool'),
  77. state=dict(default='present', type='str'),
  78. ),
  79. #supports_check_mode=True
  80. )
  81. user = module.params.get('user', os.environ['ZABBIX_USER'])
  82. passwd = module.params.get('password', os.environ['ZABBIX_PASSWORD'])
  83. zapi = ZabbixAPI(ZabbixConnection(module.params['server'], user, passwd, module.params['debug']))
  84. zbx_class_name = 'usergroup'
  85. idname = "usrgrpid"
  86. uname = module.params['name']
  87. state = module.params['state']
  88. content = zapi.get_content(zbx_class_name,
  89. 'get',
  90. {'search': {'name': uname},
  91. 'selectUsers': 'userid',
  92. })
  93. if state == 'list':
  94. module.exit_json(changed=False, results=content['result'], state="list")
  95. if state == 'absent':
  96. if not exists(content):
  97. module.exit_json(changed=False, state="absent")
  98. content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0][idname]])
  99. module.exit_json(changed=True, results=content['result'], state="absent")
  100. if state == 'present':
  101. params = {'name': uname,
  102. 'rights': get_rights(zapi, module.params['rights']),
  103. 'userids': get_userids(zapi, module.params['users']),
  104. }
  105. if not exists(content):
  106. # if we didn't find it, create it
  107. content = zapi.get_content(zbx_class_name, 'create', params)
  108. module.exit_json(changed=True, results=content['result'], state='present')
  109. # already exists, we need to update it
  110. # let's compare properties
  111. differences = {}
  112. zab_results = content['result'][0]
  113. for key, value in params.items():
  114. if key == 'rights':
  115. differences['rights'] = value
  116. elif key == 'userids' and zab_results.has_key('users'):
  117. if zab_results['users'] != value:
  118. differences['userids'] = value
  119. elif zab_results[key] != value and zab_results[key] != str(value):
  120. differences[key] = value
  121. if not differences:
  122. module.exit_json(changed=False, results=zab_results, state="present")
  123. # We have differences and need to update
  124. differences[idname] = zab_results[idname]
  125. content = zapi.get_content(zbx_class_name, 'update', differences)
  126. module.exit_json(changed=True, results=content['result'], state="present")
  127. module.exit_json(failed=True,
  128. changed=False,
  129. results='Unknown state passed. %s' % state,
  130. state="unknown")
  131. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled
  132. # import module snippets. This are required
  133. from ansible.module_utils.basic import *
  134. main()