zbx_trigger.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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. {'filter': {'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. url=dict(default=None, type='str'),
  92. state=dict(default='present', type='str'),
  93. ),
  94. #supports_check_mode=True
  95. )
  96. zapi = ZabbixAPI(ZabbixConnection(module.params['zbx_server'],
  97. module.params['zbx_user'],
  98. module.params['zbx_password'],
  99. module.params['zbx_debug']))
  100. #Set the instance and the template for the rest of the calls
  101. zbx_class_name = 'trigger'
  102. idname = "triggerid"
  103. state = module.params['state']
  104. description = module.params['description']
  105. content = zapi.get_content(zbx_class_name,
  106. 'get',
  107. {'filter': {'description': description},
  108. 'expandExpression': True,
  109. 'selectDependencies': 'triggerid',
  110. })
  111. # Get
  112. if state == 'list':
  113. module.exit_json(changed=False, results=content['result'], state="list")
  114. # Delete
  115. if state == 'absent':
  116. if not exists(content):
  117. module.exit_json(changed=False, state="absent")
  118. content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0][idname]])
  119. module.exit_json(changed=True, results=content['result'], state="absent")
  120. # Create and Update
  121. if state == 'present':
  122. params = {'description': description,
  123. 'expression': module.params['expression'],
  124. 'dependencies': get_deps(zapi, module.params['dependencies']),
  125. 'priority': get_priority(module.params['priority']),
  126. 'url': module.params['url'],
  127. }
  128. # Remove any None valued params
  129. _ = [params.pop(key, None) for key in params.keys() if params[key] is None]
  130. #******#
  131. # CREATE
  132. #******#
  133. if not exists(content):
  134. # if we didn't find it, create it
  135. content = zapi.get_content(zbx_class_name, 'create', params)
  136. module.exit_json(changed=True, results=content['result'], state='present')
  137. ########
  138. # UPDATE
  139. ########
  140. differences = {}
  141. zab_results = content['result'][0]
  142. for key, value in params.items():
  143. if zab_results[key] != value and zab_results[key] != str(value):
  144. differences[key] = value
  145. if not differences:
  146. module.exit_json(changed=False, results=zab_results, state="present")
  147. # We have differences and need to update
  148. differences[idname] = zab_results[idname]
  149. content = zapi.get_content(zbx_class_name, 'update', differences)
  150. module.exit_json(changed=True, results=content['result'], state="present")
  151. module.exit_json(failed=True,
  152. changed=False,
  153. results='Unknown state passed. %s' % state,
  154. state="unknown")
  155. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled
  156. # import module snippets. This are required
  157. from ansible.module_utils.basic import *
  158. main()