zbx_item.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. #!/usr/bin/env python
  2. '''
  3. Ansible module for zabbix items
  4. '''
  5. # vim: expandtab:tabstop=4:shiftwidth=4
  6. #
  7. # Zabbix item 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_value_type(value_type):
  39. '''
  40. Possible values:
  41. 0 - numeric float;
  42. 1 - character;
  43. 2 - log;
  44. 3 - numeric unsigned;
  45. 4 - text
  46. '''
  47. vtype = 0
  48. if 'int' in value_type:
  49. vtype = 3
  50. elif 'char' in value_type:
  51. vtype = 1
  52. elif 'str' in value_type:
  53. vtype = 4
  54. return vtype
  55. def main():
  56. '''
  57. ansible zabbix module for zbx_item
  58. '''
  59. module = AnsibleModule(
  60. argument_spec=dict(
  61. server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'),
  62. user=dict(default=None, type='str'),
  63. password=dict(default=None, type='str'),
  64. name=dict(default=None, type='str'),
  65. key=dict(default=None, type='str'),
  66. template_name=dict(default=None, type='str'),
  67. zabbix_type=dict(default=2, type='int'),
  68. value_type=dict(default='int', type='str'),
  69. applications=dict(default=[], type='list'),
  70. debug=dict(default=False, type='bool'),
  71. state=dict(default='present', type='str'),
  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 = 'item'
  80. idname = "itemid"
  81. state = module.params['state']
  82. key = module.params['key']
  83. template_name = module.params['template_name']
  84. content = zapi.get_content('template', 'get', {'search': {'host': template_name}})
  85. templateid = None
  86. if content['result']:
  87. templateid = content['result'][0]['templateid']
  88. else:
  89. module.exit_json(changed=False,
  90. results='Error: Could find template with name %s for item.' % template_name,
  91. state="Unkown")
  92. content = zapi.get_content(zbx_class_name,
  93. 'get',
  94. {'search': {'key_': key},
  95. 'selectApplications': 'applicationid',
  96. })
  97. if state == 'list':
  98. module.exit_json(changed=False, results=content['result'], state="list")
  99. if state == 'absent':
  100. if not exists(content):
  101. module.exit_json(changed=False, state="absent")
  102. content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0][idname]])
  103. module.exit_json(changed=True, results=content['result'], state="absent")
  104. if state == 'present':
  105. params = {'name': module.params['name'],
  106. 'key_': key,
  107. 'hostid': templateid,
  108. 'type': module.params['zabbix_type'],
  109. 'value_type': get_value_type(module.params['value_type']),
  110. 'applications': module.params['applications'],
  111. }
  112. if not exists(content):
  113. # if we didn't find it, create it
  114. content = zapi.get_content(zbx_class_name, 'create', params)
  115. module.exit_json(changed=True, results=content['result'], state='present')
  116. # already exists, we need to update it
  117. # let's compare properties
  118. differences = {}
  119. zab_results = content['result'][0]
  120. for key, value in params.items():
  121. if zab_results[key] != value and zab_results[key] != str(value):
  122. differences[key] = value
  123. if not differences:
  124. module.exit_json(changed=False, results=zab_results, state="present")
  125. # We have differences and need to update
  126. differences[idname] = zab_results[idname]
  127. content = zapi.get_content(zbx_class_name, 'update', differences)
  128. module.exit_json(changed=True, results=content['result'], state="present")
  129. module.exit_json(failed=True,
  130. changed=False,
  131. results='Unknown state passed. %s' % state,
  132. state="unknown")
  133. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled
  134. # import module snippets. This are required
  135. from ansible.module_utils.basic import *
  136. main()