zbx_application.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. #!/usr/bin/env python
  2. '''
  3. Ansible module for application
  4. '''
  5. # vim: expandtab:tabstop=4:shiftwidth=4
  6. #
  7. # Zabbix application 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_template_ids(zapi, template_name):
  39. '''
  40. get related templates
  41. '''
  42. template_ids = []
  43. # Fetch templates by name
  44. content = zapi.get_content('template',
  45. 'get',
  46. {'search': {'host': template_name}})
  47. if content.has_key('result'):
  48. template_ids.append(content['result'][0]['templateid'])
  49. return template_ids
  50. def main():
  51. ''' Ansible module for application
  52. '''
  53. module = AnsibleModule(
  54. argument_spec=dict(
  55. zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'),
  56. zbx_user=dict(default=os.environ.get('ZABBIX_USER', None), type='str'),
  57. zbx_password=dict(default=os.environ.get('ZABBIX_PASSWORD', None), type='str'),
  58. zbx_debug=dict(default=False, type='bool'),
  59. name=dict(default=None, type='str', required=True),
  60. template_name=dict(default=None, type='str'),
  61. state=dict(default='present', type='str'),
  62. ),
  63. #supports_check_mode=True
  64. )
  65. zapi = ZabbixAPI(ZabbixConnection(module.params['zbx_server'],
  66. module.params['zbx_user'],
  67. module.params['zbx_password'],
  68. module.params['zbx_debug']))
  69. #Set the instance and the application for the rest of the calls
  70. zbx_class_name = 'application'
  71. idname = 'applicationid'
  72. aname = module.params['name']
  73. state = module.params['state']
  74. # get a applicationid, see if it exists
  75. tids = get_template_ids(zapi, module.params['template_name'])
  76. content = zapi.get_content(zbx_class_name,
  77. 'get',
  78. {'search': {'name': aname},
  79. 'templateids': tids[0],
  80. })
  81. if state == 'list':
  82. module.exit_json(changed=False, results=content['result'], state="list")
  83. if state == 'absent':
  84. if not exists(content):
  85. module.exit_json(changed=False, state="absent")
  86. content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0][idname]])
  87. module.exit_json(changed=True, results=content['result'], state="absent")
  88. if state == 'present':
  89. params = {'hostid': tids[0],
  90. 'name': aname,
  91. }
  92. if not exists(content):
  93. # if we didn't find it, create it
  94. content = zapi.get_content(zbx_class_name, 'create', params)
  95. module.exit_json(changed=True, results=content['result'], state='present')
  96. # already exists, we need to update it
  97. # let's compare properties
  98. differences = {}
  99. zab_results = content['result'][0]
  100. for key, value in params.items():
  101. if key == 'templates' and zab_results.has_key('parentTemplates'):
  102. if zab_results['parentTemplates'] != value:
  103. differences[key] = value
  104. elif zab_results[key] != str(value) and zab_results[key] != value:
  105. differences[key] = value
  106. if not differences:
  107. module.exit_json(changed=False, results=content['result'], state="present")
  108. # We have differences and need to update
  109. differences[idname] = zab_results[idname]
  110. content = zapi.get_content(zbx_class_name, 'update', differences)
  111. if content.has_key('error'):
  112. module.exit_json(failed=True, changed=False, results=content['error'], state="present")
  113. module.exit_json(changed=True, results=content['result'], state="present")
  114. module.exit_json(failed=True,
  115. changed=False,
  116. results='Unknown state passed. %s' % state,
  117. state="unknown")
  118. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled
  119. # import module snippets. This are required
  120. from ansible.module_utils.basic import *
  121. main()