zbx_host.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  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['results'][0]['templateid']})
  56. return template_ids
  57. def main():
  58. '''
  59. Ansible module for zabbix host
  60. '''
  61. module = AnsibleModule(
  62. argument_spec=dict(
  63. server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'),
  64. user=dict(default=None, type='str'),
  65. password=dict(default=None, type='str'),
  66. name=dict(default=None, type='str'),
  67. hostgroup_names=dict(default=[], type='list'),
  68. template_names=dict(default=[], type='list'),
  69. debug=dict(default=False, type='bool'),
  70. state=dict(default='present', type='str'),
  71. interfaces=dict(default=[], type='list'),
  72. ),
  73. #supports_check_mode=True
  74. )
  75. user = module.params.get('user', os.environ['ZABBIX_USER'])
  76. passwd = module.params.get('password', os.environ['ZABBIX_PASSWORD'])
  77. zapi = ZabbixAPI(ZabbixConnection(module.params['server'], user, passwd, module.params['debug']))
  78. #Set the instance and the template for the rest of the calls
  79. zbx_class_name = 'host'
  80. idname = "hostid"
  81. hname = module.params['name']
  82. state = module.params['state']
  83. # selectInterfaces doesn't appear to be working but is needed.
  84. content = zapi.get_content(zbx_class_name,
  85. 'get',
  86. {'search': {'host': hname},
  87. 'selectGroups': 'groupid',
  88. 'selectParentTemplates': 'templateid',
  89. 'selectInterfaces': 'interfaceid',
  90. })
  91. if state == 'list':
  92. module.exit_json(changed=False, results=content['result'], state="list")
  93. if state == 'absent':
  94. if not exists(content):
  95. module.exit_json(changed=False, state="absent")
  96. content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0][idname]])
  97. module.exit_json(changed=True, results=content['result'], state="absent")
  98. if state == 'present':
  99. params = {'host': hname,
  100. 'groups': get_group_ids(zapi, module.params('hostgroup_names')),
  101. 'templates': get_template_ids(zapi, module.params('template_names')),
  102. 'interfaces': module.params.get('interfaces', [{'type': 1, # interface type, 1 = agent
  103. 'main': 1, # default interface? 1 = true
  104. 'useip': 1, # default interface? 1 = true
  105. 'ip': '127.0.0.1', # default interface? 1 = true
  106. 'dns': '', # dns for host
  107. 'port': '10050', # port for interface? 10050
  108. }])
  109. }
  110. if not exists(content):
  111. # if we didn't find it, create it
  112. content = zapi.get_content(zbx_class_name, 'create', params)
  113. module.exit_json(changed=True, results=content['result'], state='present')
  114. # already exists, we need to update it
  115. # let's compare properties
  116. differences = {}
  117. zab_results = content['result'][0]
  118. for key, value in params.items():
  119. if key == 'templates' and zab_results.has_key('parentTemplates'):
  120. if zab_results['parentTemplates'] != value:
  121. differences[key] = value
  122. elif zab_results[key] != value and zab_results[key] != str(value):
  123. differences[key] = value
  124. if not differences:
  125. module.exit_json(changed=False, results=zab_results, state="present")
  126. # We have differences and need to update
  127. differences[idname] = zab_results[idname]
  128. content = zapi.get_content(zbx_class_name, 'update', differences)
  129. module.exit_json(changed=True, results=content['result'], state="present")
  130. module.exit_json(failed=True,
  131. changed=False,
  132. results='Unknown state passed. %s' % state,
  133. state="unknown")
  134. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled
  135. # import module snippets. This are required
  136. from ansible.module_utils.basic import *
  137. main()