zbx_host.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. #!/usr/bin/env python
  2. '''
  3. Zabbix host 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_group_ids(zapi, hostgroup_names):
  36. '''
  37. get hostgroups
  38. '''
  39. # Fetch groups by name
  40. group_ids = []
  41. for hgr in hostgroup_names:
  42. content = zapi.get_content('hostgroup', 'get', {'search': {'name': hgr}})
  43. if content.has_key('result'):
  44. group_ids.append({'groupid': content['result'][0]['groupid']})
  45. return group_ids
  46. def get_template_ids(zapi, template_names):
  47. '''
  48. get related templates
  49. '''
  50. template_ids = []
  51. # Fetch templates by name
  52. for template_name in template_names:
  53. content = zapi.get_content('template', 'get', {'search': {'host': template_name}})
  54. if content.has_key('result'):
  55. template_ids.append({'templateid': content['result'][0]['templateid']})
  56. return template_ids
  57. def interfaces_equal(zbx_interfaces, user_interfaces):
  58. '''
  59. compare interfaces from zabbix and interfaces from user
  60. '''
  61. for u_int in user_interfaces:
  62. for z_int in zbx_interfaces:
  63. for u_key, u_val in u_int.items():
  64. if str(z_int[u_key]) != str(u_val):
  65. return False
  66. return True
  67. def main():
  68. '''
  69. Ansible module for zabbix host
  70. '''
  71. module = AnsibleModule(
  72. argument_spec=dict(
  73. zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'),
  74. zbx_user=dict(default=os.environ.get('ZABBIX_USER', None), type='str'),
  75. zbx_password=dict(default=os.environ.get('ZABBIX_PASSWORD', None), type='str'),
  76. zbx_debug=dict(default=False, type='bool'),
  77. name=dict(default=None, type='str'),
  78. hostgroup_names=dict(default=[], type='list'),
  79. template_names=dict(default=[], type='list'),
  80. state=dict(default='present', type='str'),
  81. interfaces=dict(default=None, type='list'),
  82. ),
  83. #supports_check_mode=True
  84. )
  85. zapi = ZabbixAPI(ZabbixConnection(module.params['zbx_server'],
  86. module.params['zbx_user'],
  87. module.params['zbx_password'],
  88. module.params['zbx_debug']))
  89. #Set the instance and the template for the rest of the calls
  90. zbx_class_name = 'host'
  91. idname = "hostid"
  92. hname = module.params['name']
  93. state = module.params['state']
  94. # selectInterfaces doesn't appear to be working but is needed.
  95. content = zapi.get_content(zbx_class_name,
  96. 'get',
  97. {'search': {'host': hname},
  98. 'selectGroups': 'groupid',
  99. 'selectParentTemplates': 'templateid',
  100. 'selectInterfaces': 'interfaceid',
  101. })
  102. if state == 'list':
  103. module.exit_json(changed=False, results=content['result'], state="list")
  104. if state == 'absent':
  105. if not exists(content):
  106. module.exit_json(changed=False, state="absent")
  107. content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0][idname]])
  108. module.exit_json(changed=True, results=content['result'], state="absent")
  109. if state == 'present':
  110. ifs = module.params['interfaces'] or [{'type': 1, # interface type, 1 = agent
  111. 'main': 1, # default interface? 1 = true
  112. 'useip': 1, # default interface? 1 = true
  113. 'ip': '127.0.0.1', # default interface? 1 = true
  114. 'dns': '', # dns for host
  115. 'port': '10050', # port for interface? 10050
  116. }]
  117. hostgroup_names = list(set(module.params['hostgroup_names']))
  118. params = {'host': hname,
  119. 'groups': get_group_ids(zapi, hostgroup_names),
  120. 'templates': get_template_ids(zapi, module.params['template_names']),
  121. 'interfaces': ifs,
  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 key == 'templates' and zab_results.has_key('parentTemplates'):
  133. if zab_results['parentTemplates'] != value:
  134. differences[key] = value
  135. elif key == "interfaces":
  136. if not interfaces_equal(zab_results[key], value):
  137. differences[key] = value
  138. elif zab_results[key] != value and zab_results[key] != str(value):
  139. differences[key] = value
  140. if not differences:
  141. module.exit_json(changed=False, results=zab_results, state="present")
  142. # We have differences and need to update
  143. differences[idname] = zab_results[idname]
  144. content = zapi.get_content(zbx_class_name, 'update', differences)
  145. module.exit_json(changed=True, results=content['result'], state="present")
  146. module.exit_json(failed=True,
  147. changed=False,
  148. results='Unknown state passed. %s' % state,
  149. state="unknown")
  150. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled
  151. # import module snippets. This are required
  152. from ansible.module_utils.basic import *
  153. main()