zbx_discoveryrule.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. #!/usr/bin/env python
  2. '''
  3. Zabbix discovery rule ansible module
  4. '''
  5. # vim: expandtab:tabstop=4:shiftwidth=4
  6. #
  7. # Copyright 2015 Red Hat Inc.
  8. #
  9. # Licensed under the Apache License, Version 2.0 (the "License");
  10. # you may not use this file except in compliance with the License.
  11. # You may obtain a copy of the License at
  12. #
  13. # http://www.apache.org/licenses/LICENSE-2.0
  14. #
  15. # Unless required by applicable law or agreed to in writing, software
  16. # distributed under the License is distributed on an "AS IS" BASIS,
  17. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. # See the License for the specific language governing permissions and
  19. # limitations under the License.
  20. #
  21. # This is in place because each module looks similar to each other.
  22. # These need duplicate code as their behavior is very similar
  23. # but different for each zabbix class.
  24. # pylint: disable=duplicate-code
  25. # pylint: disable=import-error
  26. from openshift_tools.monitoring.zbxapi import ZabbixAPI, ZabbixConnection
  27. def exists(content, key='result'):
  28. ''' Check if key exists in content or the size of content[key] > 0
  29. '''
  30. if not content.has_key(key):
  31. return False
  32. if not content[key]:
  33. return False
  34. return True
  35. def get_template(zapi, template_name):
  36. '''get a template by name
  37. '''
  38. content = zapi.get_content('template',
  39. 'get',
  40. {'search': {'host': template_name},
  41. 'output': 'extend',
  42. 'selectInterfaces': 'interfaceid',
  43. })
  44. if not content['result']:
  45. return None
  46. return content['result'][0]
  47. def get_type(vtype):
  48. '''
  49. Determine which type of discoverrule this is
  50. '''
  51. _types = {'agent': 0,
  52. 'SNMPv1': 1,
  53. 'trapper': 2,
  54. 'simple': 3,
  55. 'SNMPv2': 4,
  56. 'internal': 5,
  57. 'SNMPv3': 6,
  58. 'active': 7,
  59. 'external': 10,
  60. 'database monitor': 11,
  61. 'ipmi': 12,
  62. 'ssh': 13,
  63. 'telnet': 14,
  64. 'JMX': 16,
  65. }
  66. for typ in _types.keys():
  67. if vtype in typ or vtype == typ:
  68. _vtype = _types[typ]
  69. break
  70. else:
  71. _vtype = 2
  72. return _vtype
  73. def main():
  74. '''
  75. Ansible module for zabbix discovery rules
  76. '''
  77. module = AnsibleModule(
  78. argument_spec=dict(
  79. server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'),
  80. user=dict(default=os.environ['ZABBIX_USER'], type='str'),
  81. password=dict(default=os.environ['ZABBIX_PASSWORD'], type='str'),
  82. name=dict(default=None, type='str'),
  83. key=dict(default=None, type='str'),
  84. interfaceid=dict(default=None, type='int'),
  85. ztype=dict(default='trapper', type='str'),
  86. delay=dict(default=60, type='int'),
  87. lifetime=dict(default=30, type='int'),
  88. template_name=dict(default=[], type='list'),
  89. debug=dict(default=False, type='bool'),
  90. state=dict(default='present', type='str'),
  91. ),
  92. #supports_check_mode=True
  93. )
  94. user = module.params['user']
  95. passwd = module.params['password']
  96. zapi = ZabbixAPI(ZabbixConnection(module.params['server'], user, passwd, module.params['debug']))
  97. #Set the instance and the template for the rest of the calls
  98. zbx_class_name = 'discoveryrule'
  99. idname = "itemid"
  100. dname = module.params['name']
  101. state = module.params['state']
  102. # selectInterfaces doesn't appear to be working but is needed.
  103. content = zapi.get_content(zbx_class_name,
  104. 'get',
  105. {'search': {'name': dname},
  106. #'selectDServices': 'extend',
  107. #'selectDChecks': 'extend',
  108. #'selectDhosts': 'dhostid',
  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. template = get_template(zapi, module.params['template_name'])
  119. params = {'name': dname,
  120. 'key_': module.params['key'],
  121. 'hostid': template['templateid'],
  122. 'interfaceid': module.params['interfaceid'],
  123. 'lifetime': module.params['lifetime'],
  124. 'type': get_type(module.params['ztype']),
  125. }
  126. if params['type'] in [2, 5, 7, 11]:
  127. params.pop('interfaceid')
  128. if not exists(content):
  129. # if we didn't find it, create it
  130. content = zapi.get_content(zbx_class_name, 'create', params)
  131. module.exit_json(changed=True, results=content['result'], state='present')
  132. # already exists, we need to update it
  133. # let's compare properties
  134. differences = {}
  135. zab_results = content['result'][0]
  136. for key, value in params.items():
  137. if zab_results[key] != value and zab_results[key] != str(value):
  138. differences[key] = value
  139. if not differences:
  140. module.exit_json(changed=False, results=zab_results, state="present")
  141. # We have differences and need to update
  142. differences[idname] = zab_results[idname]
  143. content = zapi.get_content(zbx_class_name, 'update', differences)
  144. module.exit_json(changed=True, results=content['result'], state="present")
  145. module.exit_json(failed=True,
  146. changed=False,
  147. results='Unknown state passed. %s' % state,
  148. state="unknown")
  149. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled
  150. # import module snippets. This are required
  151. from ansible.module_utils.basic import *
  152. main()