zbx_discoveryrule.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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.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. zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'),
  80. zbx_user=dict(default=os.environ.get('ZABBIX_USER', None), type='str'),
  81. zbx_password=dict(default=os.environ.get('ZABBIX_PASSWORD', None), type='str'),
  82. zbx_debug=dict(default=False, type='bool'),
  83. name=dict(default=None, type='str'),
  84. key=dict(default=None, type='str'),
  85. description=dict(default=None, type='str'),
  86. interfaceid=dict(default=None, type='int'),
  87. ztype=dict(default='trapper', type='str'),
  88. delay=dict(default=60, type='int'),
  89. lifetime=dict(default=30, type='int'),
  90. template_name=dict(default=[], type='list'),
  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 = 'discoveryrule'
  101. idname = "itemid"
  102. dname = module.params['name']
  103. state = module.params['state']
  104. template = get_template(zapi, module.params['template_name'])
  105. # selectInterfaces doesn't appear to be working but is needed.
  106. content = zapi.get_content(zbx_class_name,
  107. 'get',
  108. {'search': {'name': dname},
  109. 'templateids': template['templateid'],
  110. #'selectDServices': 'extend',
  111. #'selectDChecks': 'extend',
  112. #'selectDhosts': 'dhostid',
  113. })
  114. #******#
  115. # GET
  116. #******#
  117. if state == 'list':
  118. module.exit_json(changed=False, results=content['result'], state="list")
  119. #******#
  120. # DELETE
  121. #******#
  122. if state == 'absent':
  123. if not exists(content):
  124. module.exit_json(changed=False, state="absent")
  125. content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0][idname]])
  126. module.exit_json(changed=True, results=content['result'], state="absent")
  127. # Create and Update
  128. if state == 'present':
  129. params = {'name': dname,
  130. 'key_': module.params['key'],
  131. 'hostid': template['templateid'],
  132. 'interfaceid': module.params['interfaceid'],
  133. 'lifetime': module.params['lifetime'],
  134. 'type': get_type(module.params['ztype']),
  135. 'description': module.params['description'],
  136. }
  137. if params['type'] in [2, 5, 7, 11]:
  138. params.pop('interfaceid')
  139. # Remove any None valued params
  140. _ = [params.pop(key, None) for key in params.keys() if params[key] is None]
  141. #******#
  142. # CREATE
  143. #******#
  144. if not exists(content):
  145. content = zapi.get_content(zbx_class_name, 'create', params)
  146. if content.has_key('error'):
  147. module.exit_json(failed=True, changed=True, results=content['error'], state="present")
  148. module.exit_json(changed=True, results=content['result'], state='present')
  149. ########
  150. # UPDATE
  151. ########
  152. differences = {}
  153. zab_results = content['result'][0]
  154. for key, value in params.items():
  155. if zab_results[key] != value and zab_results[key] != str(value):
  156. differences[key] = value
  157. if not differences:
  158. module.exit_json(changed=False, results=zab_results, state="present")
  159. # We have differences and need to update
  160. differences[idname] = zab_results[idname]
  161. content = zapi.get_content(zbx_class_name, 'update', differences)
  162. if content.has_key('error'):
  163. module.exit_json(failed=True, changed=False, results=content['error'], state="present")
  164. module.exit_json(changed=True, results=content['result'], state="present")
  165. module.exit_json(failed=True,
  166. changed=False,
  167. results='Unknown state passed. %s' % state,
  168. state="unknown")
  169. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled
  170. # import module snippets. This are required
  171. from ansible.module_utils.basic import *
  172. main()