zbx_trigger.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. #!/usr/bin/env python
  2. '''
  3. ansible module for zabbix triggers
  4. '''
  5. # vim: expandtab:tabstop=4:shiftwidth=4
  6. #
  7. # Zabbix trigger 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_priority(priority):
  39. ''' determine priority
  40. '''
  41. prior = 0
  42. if 'info' in priority:
  43. prior = 1
  44. elif 'warn' in priority:
  45. prior = 2
  46. elif 'avg' == priority or 'ave' in priority:
  47. prior = 3
  48. elif 'high' in priority:
  49. prior = 4
  50. elif 'dis' in priority:
  51. prior = 5
  52. return prior
  53. def get_deps(zapi, deps):
  54. ''' get trigger dependencies
  55. '''
  56. results = []
  57. for desc in deps:
  58. content = zapi.get_content('trigger',
  59. 'get',
  60. {'search': {'description': desc},
  61. 'expandExpression': True,
  62. 'selectDependencies': 'triggerid',
  63. })
  64. if content.has_key('result'):
  65. results.append({'triggerid': content['result'][0]['triggerid']})
  66. return results
  67. def main():
  68. '''
  69. Create a trigger in zabbix
  70. Example:
  71. "params": {
  72. "description": "Processor load is too high on {HOST.NAME}",
  73. "expression": "{Linux server:system.cpu.load[percpu,avg1].last()}>5",
  74. "dependencies": [
  75. {
  76. "triggerid": "14062"
  77. }
  78. ]
  79. },
  80. '''
  81. module = AnsibleModule(
  82. argument_spec=dict(
  83. server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'),
  84. user=dict(default=None, type='str'),
  85. password=dict(default=None, type='str'),
  86. expression=dict(default=None, type='str'),
  87. description=dict(default=None, type='str'),
  88. dependencies=dict(default=[], type='list'),
  89. priority=dict(default='avg', type='str'),
  90. debug=dict(default=False, type='bool'),
  91. state=dict(default='present', type='str'),
  92. ),
  93. #supports_check_mode=True
  94. )
  95. user = module.params.get('user', os.environ['ZABBIX_USER'])
  96. passwd = module.params.get('password', os.environ['ZABBIX_PASSWORD'])
  97. zapi = ZabbixAPI(ZabbixConnection(module.params['server'], user, passwd, module.params['debug']))
  98. #Set the instance and the template for the rest of the calls
  99. zbx_class_name = 'trigger'
  100. idname = "triggerid"
  101. state = module.params['state']
  102. description = module.params['description']
  103. content = zapi.get_content(zbx_class_name,
  104. 'get',
  105. {'search': {'description': description},
  106. 'expandExpression': True,
  107. 'selectDependencies': 'triggerid',
  108. })
  109. if state == 'list':
  110. module.exit_json(changed=False, results=content['result'], state="list")
  111. if state == 'absent':
  112. if not exists(content):
  113. module.exit_json(changed=False, state="absent")
  114. content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0][idname]])
  115. module.exit_json(changed=True, results=content['result'], state="absent")
  116. if state == 'present':
  117. params = {'description': description,
  118. 'expression': module.params['expression'],
  119. 'dependencies': get_deps(zapi, module.params['dependencies']),
  120. 'priority': get_priority(module.params['priority']),
  121. }
  122. if not exists(content):
  123. # if we didn't find it, create it
  124. content = zapi.get_content(zbx_class_name, 'create', params)
  125. module.exit_json(changed=True, results=content['result'], state='present')
  126. # already exists, we need to update it
  127. # let's compare properties
  128. differences = {}
  129. zab_results = content['result'][0]
  130. for key, value in params.items():
  131. if zab_results[key] != value and zab_results[key] != str(value):
  132. differences[key] = value
  133. if not differences:
  134. module.exit_json(changed=False, results=zab_results, state="present")
  135. # We have differences and need to update
  136. differences[idname] = zab_results[idname]
  137. content = zapi.get_content(zbx_class_name, 'update', differences)
  138. module.exit_json(changed=True, results=content['result'], state="present")
  139. module.exit_json(failed=True,
  140. changed=False,
  141. results='Unknown state passed. %s' % state,
  142. state="unknown")
  143. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled
  144. # import module snippets. This are required
  145. from ansible.module_utils.basic import *
  146. main()