zbx_trigger.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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. zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'),
  84. zbx_user=dict(default=os.environ.get('ZABBIX_USER', None), type='str'),
  85. zbx_password=dict(default=os.environ.get('ZABBIX_PASSWORD', None), type='str'),
  86. zbx_debug=dict(default=False, type='bool'),
  87. expression=dict(default=None, type='str'),
  88. description=dict(default=None, type='str'),
  89. dependencies=dict(default=[], type='list'),
  90. priority=dict(default='avg', type='str'),
  91. state=dict(default='present', type='str'),
  92. ),
  93. #supports_check_mode=True
  94. )
  95. zapi = ZabbixAPI(ZabbixConnection(module.params['zbx_server'],
  96. module.params['zbx_user'],
  97. module.params['zbx_password'],
  98. module.params['zbx_debug']))
  99. #Set the instance and the template for the rest of the calls
  100. zbx_class_name = 'trigger'
  101. idname = "triggerid"
  102. state = module.params['state']
  103. description = module.params['description']
  104. content = zapi.get_content(zbx_class_name,
  105. 'get',
  106. {'search': {'description': description},
  107. 'expandExpression': True,
  108. 'selectDependencies': 'triggerid',
  109. })
  110. if state == 'list':
  111. module.exit_json(changed=False, results=content['result'], state="list")
  112. if state == 'absent':
  113. if not exists(content):
  114. module.exit_json(changed=False, state="absent")
  115. content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0][idname]])
  116. module.exit_json(changed=True, results=content['result'], state="absent")
  117. if state == 'present':
  118. params = {'description': description,
  119. 'expression': module.params['expression'],
  120. 'dependencies': get_deps(zapi, module.params['dependencies']),
  121. 'priority': get_priority(module.params['priority']),
  122. }
  123. if not exists(content):
  124. # if we didn't find it, create it
  125. content = zapi.get_content(zbx_class_name, 'create', params)
  126. module.exit_json(changed=True, results=content['result'], state='present')
  127. # already exists, we need to update it
  128. # let's compare properties
  129. differences = {}
  130. zab_results = content['result'][0]
  131. for key, value in params.items():
  132. if zab_results[key] != value and zab_results[key] != str(value):
  133. differences[key] = value
  134. if not differences:
  135. module.exit_json(changed=False, results=zab_results, state="present")
  136. # We have differences and need to update
  137. differences[idname] = zab_results[idname]
  138. content = zapi.get_content(zbx_class_name, 'update', differences)
  139. module.exit_json(changed=True, results=content['result'], state="present")
  140. module.exit_json(failed=True,
  141. changed=False,
  142. results='Unknown state passed. %s' % state,
  143. state="unknown")
  144. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled
  145. # import module snippets. This are required
  146. from ansible.module_utils.basic import *
  147. main()