From 693be4802c2b3886b82681c5c1666b9f13d9ca36 Mon Sep 17 00:00:00 2001 From: Kenny Woodson Date: Fri, 21 Aug 2015 17:44:30 -0400 Subject: Updates for zbx ans module --- roles/lib_zabbix/README.md | 38 ++++ roles/lib_zabbix/library/__init__.py | 3 + roles/lib_zabbix/library/zbx_application.py | 139 +++++++++++++++ roles/lib_zabbix/library/zbx_discoveryrule.py | 177 +++++++++++++++++++ roles/lib_zabbix/library/zbx_host.py | 163 +++++++++++++++++ roles/lib_zabbix/library/zbx_hostgroup.py | 116 ++++++++++++ roles/lib_zabbix/library/zbx_item.py | 178 +++++++++++++++++++ roles/lib_zabbix/library/zbx_itemprototype.py | 241 +++++++++++++++++++++++++ roles/lib_zabbix/library/zbx_mediatype.py | 168 ++++++++++++++++++ roles/lib_zabbix/library/zbx_template.py | 132 ++++++++++++++ roles/lib_zabbix/library/zbx_trigger.py | 173 ++++++++++++++++++ roles/lib_zabbix/library/zbx_user.py | 190 ++++++++++++++++++++ roles/lib_zabbix/library/zbx_user_media.py | 245 ++++++++++++++++++++++++++ roles/lib_zabbix/library/zbx_usergroup.py | 208 ++++++++++++++++++++++ roles/lib_zabbix/tasks/create_template.yml | 61 +++++++ roles/lib_zabbix/tasks/create_user.yml | 11 ++ 16 files changed, 2243 insertions(+) create mode 100644 roles/lib_zabbix/README.md create mode 100644 roles/lib_zabbix/library/__init__.py create mode 100644 roles/lib_zabbix/library/zbx_application.py create mode 100644 roles/lib_zabbix/library/zbx_discoveryrule.py create mode 100644 roles/lib_zabbix/library/zbx_host.py create mode 100644 roles/lib_zabbix/library/zbx_hostgroup.py create mode 100644 roles/lib_zabbix/library/zbx_item.py create mode 100644 roles/lib_zabbix/library/zbx_itemprototype.py create mode 100644 roles/lib_zabbix/library/zbx_mediatype.py create mode 100644 roles/lib_zabbix/library/zbx_template.py create mode 100644 roles/lib_zabbix/library/zbx_trigger.py create mode 100644 roles/lib_zabbix/library/zbx_user.py create mode 100644 roles/lib_zabbix/library/zbx_user_media.py create mode 100644 roles/lib_zabbix/library/zbx_usergroup.py create mode 100644 roles/lib_zabbix/tasks/create_template.yml create mode 100644 roles/lib_zabbix/tasks/create_user.yml (limited to 'roles/lib_zabbix') diff --git a/roles/lib_zabbix/README.md b/roles/lib_zabbix/README.md new file mode 100644 index 000000000..69debc698 --- /dev/null +++ b/roles/lib_zabbix/README.md @@ -0,0 +1,38 @@ +zabbix +========= + +Automate zabbix tasks. + +Requirements +------------ + +This requires the openshift_tools rpm be installed for the zbxapi.py library. It can be found here: https://github.com/openshift/openshift-tools under openshift_tools/monitoring/zbxapi.py for now. + +Role Variables +-------------- + +None + +Dependencies +------------ + +This depeonds on the zbxapi.py library located here: https://github.com/openshift/openshift-tools under openshift_tools/monitoring/zbxapi.py for now. + +Example Playbook +---------------- + + - zbx_host: + server: zab_server + user: zab_user + password: zab_password + name: 'myhost' + +License +------- + +ASL 2.0 + +Author Information +------------------ + +OpenShift operations, Red Hat, Inc diff --git a/roles/lib_zabbix/library/__init__.py b/roles/lib_zabbix/library/__init__.py new file mode 100644 index 000000000..0c7e19e41 --- /dev/null +++ b/roles/lib_zabbix/library/__init__.py @@ -0,0 +1,3 @@ +''' +ZabbixAPI ansible module +''' diff --git a/roles/lib_zabbix/library/zbx_application.py b/roles/lib_zabbix/library/zbx_application.py new file mode 100644 index 000000000..ffa00e052 --- /dev/null +++ b/roles/lib_zabbix/library/zbx_application.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python +''' +Ansible module for application +''' +# vim: expandtab:tabstop=4:shiftwidth=4 +# +# Zabbix application ansible module +# +# +# Copyright 2015 Red Hat Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# This is in place because each module looks similar to each other. +# These need duplicate code as their behavior is very similar +# but different for each zabbix class. +# pylint: disable=duplicate-code + +# pylint: disable=import-error +from openshift_tools.monitoring.zbxapi import ZabbixAPI, ZabbixConnection + +def exists(content, key='result'): + ''' Check if key exists in content or the size of content[key] > 0 + ''' + if not content.has_key(key): + return False + + if not content[key]: + return False + + return True + +def get_template_ids(zapi, template_names): + ''' + get related templates + ''' + template_ids = [] + # Fetch templates by name + for template_name in template_names: + content = zapi.get_content('template', 'get', {'search': {'host': template_name}}) + if content.has_key('result'): + template_ids.append(content['result'][0]['templateid']) + return template_ids + +def main(): + ''' Ansible module for application + ''' + + module = AnsibleModule( + argument_spec=dict( + zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'), + zbx_user=dict(default=os.environ['ZABBIX_USER'], type='str'), + zbx_password=dict(default=os.environ['ZABBIX_PASSWORD'], type='str'), + zbx_debug=dict(default=False, type='bool'), + name=dict(default=None, type='str'), + template_name=dict(default=None, type='list'), + state=dict(default='present', type='str'), + ), + #supports_check_mode=True + ) + + zapi = ZabbixAPI(ZabbixConnection(module.params['zbx_server'], + module.params['zbx_user'], + module.params['zbx_password'], + module.params['zbx_debug'])) + + #Set the instance and the application for the rest of the calls + zbx_class_name = 'application' + idname = 'applicationid' + aname = module.params['name'] + state = module.params['state'] + # get a applicationid, see if it exists + content = zapi.get_content(zbx_class_name, + 'get', + {'search': {'name': aname}, + 'selectHost': 'hostid', + }) + if state == 'list': + module.exit_json(changed=False, results=content['result'], state="list") + + if state == 'absent': + if not exists(content): + module.exit_json(changed=False, state="absent") + + content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0][idname]]) + module.exit_json(changed=True, results=content['result'], state="absent") + + if state == 'present': + params = {'hostid': get_template_ids(zapi, module.params['template_name'])[0], + 'name': aname, + } + if not exists(content): + # if we didn't find it, create it + content = zapi.get_content(zbx_class_name, 'create', params) + module.exit_json(changed=True, results=content['result'], state='present') + # already exists, we need to update it + # let's compare properties + differences = {} + zab_results = content['result'][0] + for key, value in params.items(): + if key == 'templates' and zab_results.has_key('parentTemplates'): + if zab_results['parentTemplates'] != value: + differences[key] = value + elif zab_results[key] != str(value) and zab_results[key] != value: + differences[key] = value + + if not differences: + module.exit_json(changed=False, results=content['result'], state="present") + + # We have differences and need to update + differences[idname] = zab_results[idname] + content = zapi.get_content(zbx_class_name, 'update', differences) + + if content.has_key('error'): + module.exit_json(failed=True, changed=False, results=content['error'], state="present") + + module.exit_json(changed=True, results=content['result'], state="present") + + module.exit_json(failed=True, + changed=False, + results='Unknown state passed. %s' % state, + state="unknown") + +# pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled +# import module snippets. This are required +from ansible.module_utils.basic import * + +main() diff --git a/roles/lib_zabbix/library/zbx_discoveryrule.py b/roles/lib_zabbix/library/zbx_discoveryrule.py new file mode 100644 index 000000000..79ee91180 --- /dev/null +++ b/roles/lib_zabbix/library/zbx_discoveryrule.py @@ -0,0 +1,177 @@ +#!/usr/bin/env python +''' +Zabbix discovery rule ansible module +''' +# vim: expandtab:tabstop=4:shiftwidth=4 +# +# Copyright 2015 Red Hat Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# This is in place because each module looks similar to each other. +# These need duplicate code as their behavior is very similar +# but different for each zabbix class. +# pylint: disable=duplicate-code + +# pylint: disable=import-error +from openshift_tools.monitoring.zbxapi import ZabbixAPI, ZabbixConnection + +def exists(content, key='result'): + ''' Check if key exists in content or the size of content[key] > 0 + ''' + if not content.has_key(key): + return False + + if not content[key]: + return False + + return True + +def get_template(zapi, template_name): + '''get a template by name + ''' + content = zapi.get_content('template', + 'get', + {'search': {'host': template_name}, + 'output': 'extend', + 'selectInterfaces': 'interfaceid', + }) + if not content['result']: + return None + return content['result'][0] + +def get_type(vtype): + ''' + Determine which type of discoverrule this is + ''' + _types = {'agent': 0, + 'SNMPv1': 1, + 'trapper': 2, + 'simple': 3, + 'SNMPv2': 4, + 'internal': 5, + 'SNMPv3': 6, + 'active': 7, + 'external': 10, + 'database monitor': 11, + 'ipmi': 12, + 'ssh': 13, + 'telnet': 14, + 'JMX': 16, + } + + for typ in _types.keys(): + if vtype in typ or vtype == typ: + _vtype = _types[typ] + break + else: + _vtype = 2 + + return _vtype + +def main(): + ''' + Ansible module for zabbix discovery rules + ''' + + module = AnsibleModule( + argument_spec=dict( + zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'), + zbx_user=dict(default=os.environ['ZABBIX_USER'], type='str'), + zbx_password=dict(default=os.environ['ZABBIX_PASSWORD'], type='str'), + zbx_debug=dict(default=False, type='bool'), + name=dict(default=None, type='str'), + key=dict(default=None, type='str'), + interfaceid=dict(default=None, type='int'), + ztype=dict(default='trapper', type='str'), + delay=dict(default=60, type='int'), + lifetime=dict(default=30, type='int'), + template_name=dict(default=[], type='list'), + state=dict(default='present', type='str'), + ), + #supports_check_mode=True + ) + + zapi = ZabbixAPI(ZabbixConnection(module.params['zbx_server'], + module.params['zbx_user'], + module.params['zbx_password'], + module.params['zbx_debug'])) + + #Set the instance and the template for the rest of the calls + zbx_class_name = 'discoveryrule' + idname = "itemid" + dname = module.params['name'] + state = module.params['state'] + + # selectInterfaces doesn't appear to be working but is needed. + content = zapi.get_content(zbx_class_name, + 'get', + {'search': {'name': dname}, + #'selectDServices': 'extend', + #'selectDChecks': 'extend', + #'selectDhosts': 'dhostid', + }) + if state == 'list': + module.exit_json(changed=False, results=content['result'], state="list") + + if state == 'absent': + if not exists(content): + module.exit_json(changed=False, state="absent") + + content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0][idname]]) + module.exit_json(changed=True, results=content['result'], state="absent") + + if state == 'present': + template = get_template(zapi, module.params['template_name']) + params = {'name': dname, + 'key_': module.params['key'], + 'hostid': template['templateid'], + 'interfaceid': module.params['interfaceid'], + 'lifetime': module.params['lifetime'], + 'type': get_type(module.params['ztype']), + } + if params['type'] in [2, 5, 7, 11]: + params.pop('interfaceid') + + if not exists(content): + # if we didn't find it, create it + content = zapi.get_content(zbx_class_name, 'create', params) + module.exit_json(changed=True, results=content['result'], state='present') + # already exists, we need to update it + # let's compare properties + differences = {} + zab_results = content['result'][0] + for key, value in params.items(): + + if zab_results[key] != value and zab_results[key] != str(value): + differences[key] = value + + if not differences: + module.exit_json(changed=False, results=zab_results, state="present") + + # We have differences and need to update + differences[idname] = zab_results[idname] + content = zapi.get_content(zbx_class_name, 'update', differences) + module.exit_json(changed=True, results=content['result'], state="present") + + module.exit_json(failed=True, + changed=False, + results='Unknown state passed. %s' % state, + state="unknown") + +# pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled +# import module snippets. This are required +from ansible.module_utils.basic import * + +main() diff --git a/roles/lib_zabbix/library/zbx_host.py b/roles/lib_zabbix/library/zbx_host.py new file mode 100644 index 000000000..7be03653e --- /dev/null +++ b/roles/lib_zabbix/library/zbx_host.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python +''' +Zabbix host ansible module +''' +# vim: expandtab:tabstop=4:shiftwidth=4 +# +# Copyright 2015 Red Hat Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# This is in place because each module looks similar to each other. +# These need duplicate code as their behavior is very similar +# but different for each zabbix class. +# pylint: disable=duplicate-code + +# pylint: disable=import-error +from openshift_tools.monitoring.zbxapi import ZabbixAPI, ZabbixConnection + +def exists(content, key='result'): + ''' Check if key exists in content or the size of content[key] > 0 + ''' + if not content.has_key(key): + return False + + if not content[key]: + return False + + return True + +def get_group_ids(zapi, hostgroup_names): + ''' + get hostgroups + ''' + # Fetch groups by name + group_ids = [] + for hgr in hostgroup_names: + content = zapi.get_content('hostgroup', 'get', {'search': {'name': hgr}}) + if content.has_key('result'): + group_ids.append({'groupid': content['result'][0]['groupid']}) + + return group_ids + +def get_template_ids(zapi, template_names): + ''' + get related templates + ''' + template_ids = [] + # Fetch templates by name + for template_name in template_names: + content = zapi.get_content('template', 'get', {'search': {'host': template_name}}) + if content.has_key('result'): + template_ids.append({'templateid': content['result'][0]['templateid']}) + return template_ids + +def main(): + ''' + Ansible module for zabbix host + ''' + + module = AnsibleModule( + argument_spec=dict( + zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'), + zbx_user=dict(default=os.environ['ZABBIX_USER'], type='str'), + zbx_password=dict(default=os.environ['ZABBIX_PASSWORD'], type='str'), + zbx_debug=dict(default=False, type='bool'), + name=dict(default=None, type='str'), + hostgroup_names=dict(default=[], type='list'), + template_names=dict(default=[], type='list'), + state=dict(default='present', type='str'), + interfaces=dict(default=None, type='list'), + ), + #supports_check_mode=True + ) + + zapi = ZabbixAPI(ZabbixConnection(module.params['zbx_server'], + module.params['zbx_user'], + module.params['zbx_password'], + module.params['zbx_debug'])) + + #Set the instance and the template for the rest of the calls + zbx_class_name = 'host' + idname = "hostid" + hname = module.params['name'] + state = module.params['state'] + + # selectInterfaces doesn't appear to be working but is needed. + content = zapi.get_content(zbx_class_name, + 'get', + {'search': {'host': hname}, + 'selectGroups': 'groupid', + 'selectParentTemplates': 'templateid', + 'selectInterfaces': 'interfaceid', + }) + if state == 'list': + module.exit_json(changed=False, results=content['result'], state="list") + + if state == 'absent': + if not exists(content): + module.exit_json(changed=False, state="absent") + + content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0][idname]]) + module.exit_json(changed=True, results=content['result'], state="absent") + + if state == 'present': + ifs = module.params['interfaces'] or [{'type': 1, # interface type, 1 = agent + 'main': 1, # default interface? 1 = true + 'useip': 1, # default interface? 1 = true + 'ip': '127.0.0.1', # default interface? 1 = true + 'dns': '', # dns for host + 'port': '10050', # port for interface? 10050 + }] + params = {'host': hname, + 'groups': get_group_ids(zapi, module.params['hostgroup_names']), + 'templates': get_template_ids(zapi, module.params['template_names']), + 'interfaces': ifs, + } + + if not exists(content): + # if we didn't find it, create it + content = zapi.get_content(zbx_class_name, 'create', params) + module.exit_json(changed=True, results=content['result'], state='present') + # already exists, we need to update it + # let's compare properties + differences = {} + zab_results = content['result'][0] + for key, value in params.items(): + + if key == 'templates' and zab_results.has_key('parentTemplates'): + if zab_results['parentTemplates'] != value: + differences[key] = value + + elif zab_results[key] != value and zab_results[key] != str(value): + differences[key] = value + + if not differences: + module.exit_json(changed=False, results=zab_results, state="present") + + # We have differences and need to update + differences[idname] = zab_results[idname] + content = zapi.get_content(zbx_class_name, 'update', differences) + module.exit_json(changed=True, results=content['result'], state="present") + + module.exit_json(failed=True, + changed=False, + results='Unknown state passed. %s' % state, + state="unknown") + +# pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled +# import module snippets. This are required +from ansible.module_utils.basic import * + +main() diff --git a/roles/lib_zabbix/library/zbx_hostgroup.py b/roles/lib_zabbix/library/zbx_hostgroup.py new file mode 100644 index 000000000..f161d3d9f --- /dev/null +++ b/roles/lib_zabbix/library/zbx_hostgroup.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python +''' Ansible module for hostgroup +''' +# vim: expandtab:tabstop=4:shiftwidth=4 +# +# Zabbix hostgroup ansible module +# +# +# Copyright 2015 Red Hat Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# This is in place because each module looks similar to each other. +# These need duplicate code as their behavior is very similar +# but different for each zabbix class. +# pylint: disable=duplicate-code + +# pylint: disable=import-error +from openshift_tools.monitoring.zbxapi import ZabbixAPI, ZabbixConnection + +def exists(content, key='result'): + ''' Check if key exists in content or the size of content[key] > 0 + ''' + if not content.has_key(key): + return False + + if not content[key]: + return False + + return True + +def main(): + ''' ansible module for hostgroup + ''' + + module = AnsibleModule( + argument_spec=dict( + zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'), + zbx_user=dict(default=os.environ['ZABBIX_USER'], type='str'), + zbx_password=dict(default=os.environ['ZABBIX_PASSWORD'], type='str'), + zbx_debug=dict(default=False, type='bool'), + name=dict(default=None, type='str'), + state=dict(default='present', type='str'), + ), + #supports_check_mode=True + ) + + zapi = ZabbixAPI(ZabbixConnection(module.params['zbx_server'], + module.params['zbx_user'], + module.params['zbx_password'], + module.params['zbx_debug'])) + + #Set the instance and the template for the rest of the calls + zbx_class_name = 'hostgroup' + idname = "groupid" + hname = module.params['name'] + state = module.params['state'] + + content = zapi.get_content(zbx_class_name, + 'get', + {'search': {'name': hname}, + }) + if state == 'list': + module.exit_json(changed=False, results=content['result'], state="list") + + if state == 'absent': + if not exists(content): + module.exit_json(changed=False, state="absent") + + content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0][idname]]) + module.exit_json(changed=True, results=content['result'], state="absent") + + if state == 'present': + params = {'name': hname} + + if not exists(content): + # if we didn't find it, create it + content = zapi.get_content(zbx_class_name, 'create', params) + module.exit_json(changed=True, results=content['result'], state='present') + # already exists, we need to update it + # let's compare properties + differences = {} + zab_results = content['result'][0] + for key, value in params.items(): + if zab_results[key] != value and zab_results[key] != str(value): + differences[key] = value + + if not differences: + module.exit_json(changed=False, results=zab_results, state="present") + + # We have differences and need to update + differences[idname] = zab_results[idname] + content = zapi.get_content(zbx_class_name, 'update', differences) + module.exit_json(changed=True, results=content['result'], state="present") + + module.exit_json(failed=True, + changed=False, + results='Unknown state passed. %s' % state, + state="unknown") + +# pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled +# import module snippets. This are required +from ansible.module_utils.basic import * + +main() diff --git a/roles/lib_zabbix/library/zbx_item.py b/roles/lib_zabbix/library/zbx_item.py new file mode 100644 index 000000000..60da243fe --- /dev/null +++ b/roles/lib_zabbix/library/zbx_item.py @@ -0,0 +1,178 @@ +#!/usr/bin/env python +''' + Ansible module for zabbix items +''' +# vim: expandtab:tabstop=4:shiftwidth=4 +# +# Zabbix item ansible module +# +# +# Copyright 2015 Red Hat Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# This is in place because each module looks similar to each other. +# These need duplicate code as their behavior is very similar +# but different for each zabbix class. +# pylint: disable=duplicate-code + +# pylint: disable=import-error +from openshift_tools.monitoring.zbxapi import ZabbixAPI, ZabbixConnection + +def exists(content, key='result'): + ''' Check if key exists in content or the size of content[key] > 0 + ''' + if not content.has_key(key): + return False + + if not content[key]: + return False + + return True + +def get_value_type(value_type): + ''' + Possible values: + 0 - numeric float; + 1 - character; + 2 - log; + 3 - numeric unsigned; + 4 - text + ''' + vtype = 0 + if 'int' in value_type: + vtype = 3 + elif 'char' in value_type: + vtype = 1 + elif 'str' in value_type: + vtype = 4 + + return vtype + +def get_app_ids(zapi, application_names): + ''' get application ids from names + ''' + if isinstance(application_names, str): + application_names = [application_names] + app_ids = [] + for app_name in application_names: + content = zapi.get_content('application', 'get', {'search': {'name': app_name}}) + if content.has_key('result'): + app_ids.append(content['result'][0]['applicationid']) + return app_ids + +def main(): + ''' + ansible zabbix module for zbx_item + ''' + + module = AnsibleModule( + argument_spec=dict( + zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'), + zbx_user=dict(default=os.environ['ZABBIX_USER'], type='str'), + zbx_password=dict(default=os.environ['ZABBIX_PASSWORD'], type='str'), + zbx_debug=dict(default=False, type='bool'), + name=dict(default=None, type='str'), + key=dict(default=None, type='str'), + template_name=dict(default=None, type='str'), + zabbix_type=dict(default=2, type='int'), + value_type=dict(default='int', type='str'), + applications=dict(default=[], type='list'), + state=dict(default='present', type='str'), + ), + #supports_check_mode=True + ) + + zapi = ZabbixAPI(ZabbixConnection(module.params['zbx_server'], + module.params['zbx_user'], + module.params['zbx_password'], + module.params['zbx_debug'])) + + #Set the instance and the template for the rest of the calls + zbx_class_name = 'item' + idname = "itemid" + state = module.params['state'] + key = module.params['key'] + template_name = module.params['template_name'] + + content = zapi.get_content('template', 'get', {'search': {'host': template_name}}) + templateid = None + if content['result']: + templateid = content['result'][0]['templateid'] + else: + module.exit_json(changed=False, + results='Error: Could find template with name %s for item.' % template_name, + state="Unkown") + + content = zapi.get_content(zbx_class_name, + 'get', + {'search': {'key_': key}, + 'selectApplications': 'applicationid', + }) + + if state == 'list': + module.exit_json(changed=False, results=content['result'], state="list") + + if state == 'absent': + if not exists(content): + module.exit_json(changed=False, state="absent") + + content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0][idname]]) + module.exit_json(changed=True, results=content['result'], state="absent") + + if state == 'present': + params = {'name': module.params.get('name', module.params['key']), + 'key_': key, + 'hostid': templateid, + 'type': module.params['zabbix_type'], + 'value_type': get_value_type(module.params['value_type']), + 'applications': get_app_ids(zapi, module.params['applications']), + } + + if not exists(content): + # if we didn't find it, create it + content = zapi.get_content(zbx_class_name, 'create', params) + module.exit_json(changed=True, results=content['result'], state='present') + # already exists, we need to update it + # let's compare properties + differences = {} + zab_results = content['result'][0] + for key, value in params.items(): + + if key == 'applications': + zab_apps = set([item['applicationid'] for item in zab_results[key]]) + if zab_apps != set(value): + differences[key] = zab_apps + + elif zab_results[key] != value and zab_results[key] != str(value): + differences[key] = value + + if not differences: + module.exit_json(changed=False, results=zab_results, state="present") + + # We have differences and need to update + differences[idname] = zab_results[idname] + content = zapi.get_content(zbx_class_name, 'update', differences) + module.exit_json(changed=True, results=content['result'], state="present") + + module.exit_json(failed=True, + changed=False, + results='Unknown state passed. %s' % state, + state="unknown") + +# pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled +# import module snippets. This are required +from ansible.module_utils.basic import * + +main() diff --git a/roles/lib_zabbix/library/zbx_itemprototype.py b/roles/lib_zabbix/library/zbx_itemprototype.py new file mode 100644 index 000000000..47100f613 --- /dev/null +++ b/roles/lib_zabbix/library/zbx_itemprototype.py @@ -0,0 +1,241 @@ +#!/usr/bin/env python +''' +Zabbix discovery rule ansible module +''' +# vim: expandtab:tabstop=4:shiftwidth=4 +# +# Copyright 2015 Red Hat Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# This is in place because each module looks similar to each other. +# These need duplicate code as their behavior is very similar +# but different for each zabbix class. +# pylint: disable=duplicate-code + +# pylint: disable=import-error +from openshift_tools.monitoring.zbxapi import ZabbixAPI, ZabbixConnection + +def exists(content, key='result'): + ''' Check if key exists in content or the size of content[key] > 0 + ''' + if not content.has_key(key): + return False + + if not content[key]: + return False + + return True + +def get_rule_id(zapi, discoveryrule_name): + '''get a discoveryrule by name + ''' + content = zapi.get_content('discoveryrule', + 'get', + {'search': {'name': discoveryrule_name}, + 'output': 'extend', + }) + if not content['result']: + return None + return content['result'][0]['itemid'] + +def get_template(zapi, template_name): + '''get a template by name + ''' + content = zapi.get_content('template', + 'get', + {'search': {'host': template_name}, + 'output': 'extend', + 'selectInterfaces': 'interfaceid', + }) + if not content['result']: + return None + return content['result'][0] + +def get_type(ztype): + ''' + Determine which type of discoverrule this is + ''' + _types = {'agent': 0, + 'SNMPv1': 1, + 'trapper': 2, + 'simple': 3, + 'SNMPv2': 4, + 'internal': 5, + 'SNMPv3': 6, + 'active': 7, + 'aggregate': 8, + 'external': 10, + 'database monitor': 11, + 'ipmi': 12, + 'ssh': 13, + 'telnet': 14, + 'calculated': 15, + 'JMX': 16, + } + + for typ in _types.keys(): + if ztype in typ or ztype == typ: + _vtype = _types[typ] + break + else: + _vtype = 2 + + return _vtype + +def get_value_type(value_type): + ''' + Possible values: + 0 - numeric float; + 1 - character; + 2 - log; + 3 - numeric unsigned; + 4 - text + ''' + vtype = 0 + if 'int' in value_type: + vtype = 3 + elif 'char' in value_type: + vtype = 1 + elif 'str' in value_type: + vtype = 4 + + return vtype + +def get_status(status): + ''' Determine status + ''' + _status = 0 + if status == 'disabled': + _status = 1 + elif status == 'unsupported': + _status = 3 + + return _status + +def get_app_ids(zapi, application_names): + ''' get application ids from names + ''' + app_ids = [] + for app_name in application_names: + content = zapi.get_content('application', 'get', {'search': {'name': app_name}}) + if content.has_key('result'): + app_ids.append(content['result'][0]['applicationid']) + return app_ids + +def main(): + ''' + Ansible module for zabbix discovery rules + ''' + + module = AnsibleModule( + argument_spec=dict( + zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'), + zbx_user=dict(default=os.environ['ZABBIX_USER'], type='str'), + zbx_password=dict(default=os.environ['ZABBIX_PASSWORD'], type='str'), + zbx_debug=dict(default=False, type='bool'), + name=dict(default=None, type='str'), + key=dict(default=None, type='str'), + interfaceid=dict(default=None, type='int'), + ztype=dict(default='trapper', type='str'), + value_type=dict(default='float', type='str'), + delay=dict(default=60, type='int'), + lifetime=dict(default=30, type='int'), + template_name=dict(default=[], type='list'), + state=dict(default='present', type='str'), + status=dict(default='enabled', type='str'), + discoveryrule_name=dict(default=None, type='str'), + applications=dict(default=[], type='list'), + ), + #supports_check_mode=True + ) + + zapi = ZabbixAPI(ZabbixConnection(module.params['zbx_server'], + module.params['zbx_user'], + module.params['zbx_password'], + module.params['zbx_debug'])) + + #Set the instance and the template for the rest of the calls + zbx_class_name = 'itemprototype' + idname = "itemid" + dname = module.params['name'] + state = module.params['state'] + + # selectInterfaces doesn't appear to be working but is needed. + content = zapi.get_content(zbx_class_name, + 'get', + {'search': {'name': dname}, + 'selectApplications': 'applicationid', + 'selectDiscoveryRule': 'itemid', + #'selectDhosts': 'dhostid', + }) + if state == 'list': + module.exit_json(changed=False, results=content['result'], state="list") + + if state == 'absent': + if not exists(content): + module.exit_json(changed=False, state="absent") + + content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0][idname]]) + module.exit_json(changed=True, results=content['result'], state="absent") + + if state == 'present': + template = get_template(zapi, module.params['template_name']) + params = {'name': dname, + 'key_': module.params['key'], + 'hostid': template['templateid'], + 'interfaceid': module.params['interfaceid'], + 'ruleid': get_rule_id(zapi, module.params['discoveryrule_name']), + 'type': get_type(module.params['ztype']), + 'value_type': get_value_type(module.params['value_type']), + 'applications': get_app_ids(zapi, module.params['applications']), + } + if params['type'] in [2, 5, 7, 8, 11, 15]: + params.pop('interfaceid') + + if not exists(content): + # if we didn't find it, create it + content = zapi.get_content(zbx_class_name, 'create', params) + module.exit_json(changed=True, results=content['result'], state='present') + # already exists, we need to update it + # let's compare properties + differences = {} + zab_results = content['result'][0] + for key, value in params.items(): + + if key == 'ruleid': + if value != zab_results['discoveryRule']['itemid']: + differences[key] = value + + elif zab_results[key] != value and zab_results[key] != str(value): + differences[key] = value + + if not differences: + module.exit_json(changed=False, results=zab_results, state="present") + + # We have differences and need to update + differences[idname] = zab_results[idname] + content = zapi.get_content(zbx_class_name, 'update', differences) + module.exit_json(changed=True, results=content['result'], state="present") + + module.exit_json(failed=True, + changed=False, + results='Unknown state passed. %s' % state, + state="unknown") + +# pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled +# import module snippets. This are required +from ansible.module_utils.basic import * + +main() diff --git a/roles/lib_zabbix/library/zbx_mediatype.py b/roles/lib_zabbix/library/zbx_mediatype.py new file mode 100644 index 000000000..cc72cc9a8 --- /dev/null +++ b/roles/lib_zabbix/library/zbx_mediatype.py @@ -0,0 +1,168 @@ +#!/usr/bin/env python +''' + Ansible module for mediatype +''' +# vim: expandtab:tabstop=4:shiftwidth=4 +# +# Zabbix mediatype ansible module +# +# +# Copyright 2015 Red Hat Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# This is in place because each module looks similar to each other. +# These need duplicate code as their behavior is very similar +# but different for each zabbix class. +# pylint: disable=duplicate-code + +# pylint: disable=import-error +from openshift_tools.monitoring.zbxapi import ZabbixAPI, ZabbixConnection + +def exists(content, key='result'): + ''' Check if key exists in content or the size of content[key] > 0 + ''' + if not content.has_key(key): + return False + + if not content[key]: + return False + + return True + +def get_mtype(mtype): + ''' + Transport used by the media type. + Possible values: + 0 - email; + 1 - script; + 2 - SMS; + 3 - Jabber; + 100 - Ez Texting. + ''' + mtype = mtype.lower() + media_type = None + if mtype == 'script': + media_type = 1 + elif mtype == 'sms': + media_type = 2 + elif mtype == 'jabber': + media_type = 3 + elif mtype == 'script': + media_type = 100 + else: + media_type = 0 + + return media_type + +def main(): + ''' + Ansible zabbix module for mediatype + ''' + + module = AnsibleModule( + argument_spec=dict( + zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'), + zbx_user=dict(default=os.environ['ZABBIX_USER'], type='str'), + zbx_password=dict(default=os.environ['ZABBIX_PASSWORD'], type='str'), + zbx_debug=dict(default=False, type='bool'), + description=dict(default=None, type='str'), + mtype=dict(default=None, type='str'), + smtp_server=dict(default=None, type='str'), + smtp_helo=dict(default=None, type='str'), + smtp_email=dict(default=None, type='str'), + passwd=dict(default=None, type='str'), + path=dict(default=None, type='str'), + username=dict(default=None, type='str'), + status=dict(default='enabled', type='str'), + state=dict(default='present', type='str'), + ), + #supports_check_mode=True + ) + + zapi = ZabbixAPI(ZabbixConnection(module.params['zbx_server'], + module.params['zbx_user'], + module.params['zbx_password'], + module.params['zbx_debug'])) + + #Set the instance and the template for the rest of the calls + zbx_class_name = 'mediatype' + idname = "mediatypeid" + description = module.params['description'] + state = module.params['state'] + + content = zapi.get_content(zbx_class_name, 'get', {'search': {'description': description}}) + if state == 'list': + module.exit_json(changed=False, results=content['result'], state="list") + + if state == 'absent': + if not exists(content): + module.exit_json(changed=False, state="absent") + + content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0][idname]]) + module.exit_json(changed=True, results=content['result'], state="absent") + + if state == 'present': + status = 1 + if module.params['status']: + status = 0 + params = {'description': description, + 'type': get_mtype(module.params['mtype']), + 'smtp_server': module.params['smtp_server'], + 'smtp_helo': module.params['smtp_helo'], + 'smtp_email': module.params['smtp_email'], + 'passwd': module.params['passwd'], + 'exec_path': module.params['path'], + 'username': module.params['username'], + 'status': status, + } + + # Remove any None valued params + _ = [params.pop(key, None) for key in params.keys() if params[key] is None] + + if not exists(content): + # if we didn't find it, create it + content = zapi.get_content(zbx_class_name, 'create', params) + + if content.has_key('error'): + module.exit_json(failed=True, changed=False, results=content['error'], state="present") + + module.exit_json(changed=True, results=content['result'], state='present') + # already exists, we need to update it + # let's compare properties + differences = {} + zab_results = content['result'][0] + for key, value in params.items(): + if zab_results[key] != value and \ + zab_results[key] != str(value): + differences[key] = value + + if not differences: + module.exit_json(changed=False, results=zab_results, state="present") + + # We have differences and need to update + differences[idname] = zab_results[idname] + content = zapi.get_content(zbx_class_name, 'update', differences) + module.exit_json(changed=True, results=content['result'], state="present") + + module.exit_json(failed=True, + changed=False, + results='Unknown state passed. %s' % state, + state="unknown") + +# pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled +# import module snippets. This are required +from ansible.module_utils.basic import * + +main() diff --git a/roles/lib_zabbix/library/zbx_template.py b/roles/lib_zabbix/library/zbx_template.py new file mode 100644 index 000000000..1592fa268 --- /dev/null +++ b/roles/lib_zabbix/library/zbx_template.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python +''' +Ansible module for template +''' +# vim: expandtab:tabstop=4:shiftwidth=4 +# +# Zabbix template ansible module +# +# +# Copyright 2015 Red Hat Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# This is in place because each module looks similar to each other. +# These need duplicate code as their behavior is very similar +# but different for each zabbix class. +# pylint: disable=duplicate-code + +# pylint: disable=import-error +from openshift_tools.monitoring.zbxapi import ZabbixAPI, ZabbixConnection + +def exists(content, key='result'): + ''' Check if key exists in content or the size of content[key] > 0 + ''' + if not content.has_key(key): + return False + + if not content[key]: + return False + + return True + +def main(): + ''' Ansible module for template + ''' + + module = AnsibleModule( + argument_spec=dict( + zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'), + zbx_user=dict(default=os.environ['ZABBIX_USER'], type='str'), + zbx_password=dict(default=os.environ['ZABBIX_PASSWORD'], type='str'), + zbx_debug=dict(default=False, type='bool'), + name=dict(default=None, type='str'), + state=dict(default='present', type='str'), + ), + #supports_check_mode=True + ) + + zapi = ZabbixAPI(ZabbixConnection(module.params['zbx_server'], + module.params['zbx_user'], + module.params['zbx_password'], + module.params['zbx_debug'])) + + #Set the instance and the template for the rest of the calls + zbx_class_name = 'template' + idname = 'templateid' + tname = module.params['name'] + state = module.params['state'] + # get a template, see if it exists + content = zapi.get_content(zbx_class_name, + 'get', + {'search': {'host': tname}, + 'selectParentTemplates': 'templateid', + 'selectGroups': 'groupid', + 'selectApplications': 'applicationid', + 'selectDiscoveries': 'extend', + }) + if state == 'list': + module.exit_json(changed=False, results=content['result'], state="list") + + if state == 'absent': + if not exists(content): + module.exit_json(changed=False, state="absent") + + if not tname: + module.exit_json(failed=True, + changed=False, + results='Must specifiy a template name.', + state="absent") + + content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0][idname]]) + module.exit_json(changed=True, results=content['result'], state="absent") + + if state == 'present': + params = {'groups': module.params.get('groups', [{'groupid': '1'}]), + 'host': tname, + } + + if not exists(content): + # if we didn't find it, create it + content = zapi.get_content(zbx_class_name, 'create', params) + module.exit_json(changed=True, results=content['result'], state='present') + # already exists, we need to update it + # let's compare properties + differences = {} + zab_results = content['result'][0] + for key, value in params.items(): + if key == 'templates' and zab_results.has_key('parentTemplates'): + if zab_results['parentTemplates'] != value: + differences[key] = value + elif zab_results[key] != str(value) and zab_results[key] != value: + differences[key] = value + + if not differences: + module.exit_json(changed=False, results=content['result'], state="present") + + # We have differences and need to update + differences[idname] = zab_results[idname] + content = zapi.get_content(zbx_class_name, 'update', differences) + module.exit_json(changed=True, results=content['result'], state="present") + + module.exit_json(failed=True, + changed=False, + results='Unknown state passed. %s' % state, + state="unknown") + +# pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled +# import module snippets. This are required +from ansible.module_utils.basic import * + +main() diff --git a/roles/lib_zabbix/library/zbx_trigger.py b/roles/lib_zabbix/library/zbx_trigger.py new file mode 100644 index 000000000..ffad5b40a --- /dev/null +++ b/roles/lib_zabbix/library/zbx_trigger.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python +''' +ansible module for zabbix triggers +''' +# vim: expandtab:tabstop=4:shiftwidth=4 +# +# Zabbix trigger ansible module +# +# +# Copyright 2015 Red Hat Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# This is in place because each module looks similar to each other. +# These need duplicate code as their behavior is very similar +# but different for each zabbix class. +# pylint: disable=duplicate-code + +# pylint: disable=import-error +from openshift_tools.monitoring.zbxapi import ZabbixAPI, ZabbixConnection + +def exists(content, key='result'): + ''' Check if key exists in content or the size of content[key] > 0 + ''' + if not content.has_key(key): + return False + + if not content[key]: + return False + + return True + +def get_priority(priority): + ''' determine priority + ''' + prior = 0 + if 'info' in priority: + prior = 1 + elif 'warn' in priority: + prior = 2 + elif 'avg' == priority or 'ave' in priority: + prior = 3 + elif 'high' in priority: + prior = 4 + elif 'dis' in priority: + prior = 5 + + return prior + +def get_deps(zapi, deps): + ''' get trigger dependencies + ''' + results = [] + for desc in deps: + content = zapi.get_content('trigger', + 'get', + {'search': {'description': desc}, + 'expandExpression': True, + 'selectDependencies': 'triggerid', + }) + if content.has_key('result'): + results.append({'triggerid': content['result'][0]['triggerid']}) + + return results + +def main(): + ''' + Create a trigger in zabbix + + Example: + "params": { + "description": "Processor load is too high on {HOST.NAME}", + "expression": "{Linux server:system.cpu.load[percpu,avg1].last()}>5", + "dependencies": [ + { + "triggerid": "14062" + } + ] + }, + + ''' + + module = AnsibleModule( + argument_spec=dict( + zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'), + zbx_user=dict(default=os.environ['ZABBIX_USER'], type='str'), + zbx_password=dict(default=os.environ['ZABBIX_PASSWORD'], type='str'), + zbx_debug=dict(default=False, type='bool'), + expression=dict(default=None, type='str'), + description=dict(default=None, type='str'), + dependencies=dict(default=[], type='list'), + priority=dict(default='avg', type='str'), + state=dict(default='present', type='str'), + ), + #supports_check_mode=True + ) + + zapi = ZabbixAPI(ZabbixConnection(module.params['zbx_server'], + module.params['zbx_user'], + module.params['zbx_password'], + module.params['zbx_debug'])) + + #Set the instance and the template for the rest of the calls + zbx_class_name = 'trigger' + idname = "triggerid" + state = module.params['state'] + description = module.params['description'] + + content = zapi.get_content(zbx_class_name, + 'get', + {'search': {'description': description}, + 'expandExpression': True, + 'selectDependencies': 'triggerid', + }) + if state == 'list': + module.exit_json(changed=False, results=content['result'], state="list") + + if state == 'absent': + if not exists(content): + module.exit_json(changed=False, state="absent") + content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0][idname]]) + module.exit_json(changed=True, results=content['result'], state="absent") + + if state == 'present': + params = {'description': description, + 'expression': module.params['expression'], + 'dependencies': get_deps(zapi, module.params['dependencies']), + 'priority': get_priority(module.params['priority']), + } + + if not exists(content): + # if we didn't find it, create it + content = zapi.get_content(zbx_class_name, 'create', params) + module.exit_json(changed=True, results=content['result'], state='present') + # already exists, we need to update it + # let's compare properties + differences = {} + zab_results = content['result'][0] + for key, value in params.items(): + + if zab_results[key] != value and zab_results[key] != str(value): + differences[key] = value + + if not differences: + module.exit_json(changed=False, results=zab_results, state="present") + + # We have differences and need to update + differences[idname] = zab_results[idname] + content = zapi.get_content(zbx_class_name, 'update', differences) + module.exit_json(changed=True, results=content['result'], state="present") + + + module.exit_json(failed=True, + changed=False, + results='Unknown state passed. %s' % state, + state="unknown") + +# pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled +# import module snippets. This are required +from ansible.module_utils.basic import * + +main() diff --git a/roles/lib_zabbix/library/zbx_user.py b/roles/lib_zabbix/library/zbx_user.py new file mode 100644 index 000000000..a9906d773 --- /dev/null +++ b/roles/lib_zabbix/library/zbx_user.py @@ -0,0 +1,190 @@ +#!/usr/bin/env python +''' +ansible module for zabbix users +''' +# vim: expandtab:tabstop=4:shiftwidth=4 +# +# Zabbix user ansible module +# +# +# Copyright 2015 Red Hat Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# This is in place because each module looks similar to each other. +# These need duplicate code as their behavior is very similar +# but different for each zabbix class. +# pylint: disable=duplicate-code + +# pylint: disable=import-error +from openshift_tools.monitoring.zbxapi import ZabbixAPI, ZabbixConnection + +def exists(content, key='result'): + ''' Check if key exists in content or the size of content[key] > 0 + ''' + if not content.has_key(key): + return False + + if not content[key]: + return False + + return True + +def get_usergroups(zapi, usergroups): + ''' Get usergroups + ''' + ugroups = [] + for ugr in usergroups: + content = zapi.get_content('usergroup', + 'get', + {'search': {'name': ugr}, + #'selectUsers': 'userid', + #'getRights': 'extend' + }) + if content['result']: + ugroups.append({'usrgrpid': content['result'][0]['usrgrpid']}) + + return ugroups or None + +def get_passwd(passwd): + '''Determine if password is set, if not, return 'zabbix' + ''' + if passwd: + return passwd + + return 'zabbix' + +def get_usertype(user_type): + ''' + Determine zabbix user account type + ''' + if not user_type: + return None + + utype = 1 + if 'super' in user_type: + utype = 3 + elif 'admin' in user_type or user_type == 'admin': + utype = 2 + + return utype + +def main(): + ''' + ansible zabbix module for users + ''' + + ##def user(self, name, state='present', params=None): + + module = AnsibleModule( + argument_spec=dict( + zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'), + zbx_user=dict(default=os.environ['ZABBIX_USER'], type='str'), + zbx_password=dict(default=os.environ['ZABBIX_PASSWORD'], type='str'), + zbx_debug=dict(default=False, type='bool'), + login=dict(default=None, type='str'), + first_name=dict(default=None, type='str'), + last_name=dict(default=None, type='str'), + user_type=dict(default=None, type='str'), + password=dict(default=None, type='str'), + update_password=dict(default=False, type='bool'), + user_groups=dict(default=[], type='list'), + state=dict(default='present', type='str'), + ), + #supports_check_mode=True + ) + + zapi = ZabbixAPI(ZabbixConnection(module.params['zbx_server'], + module.params['zbx_user'], + module.params['zbx_password'], + module.params['zbx_debug'])) + + ## before we can create a user media and users with media types we need media + zbx_class_name = 'user' + idname = "userid" + state = module.params['state'] + + content = zapi.get_content(zbx_class_name, + 'get', + {'output': 'extend', + 'search': {'alias': module.params['login']}, + "selectUsrgrps": 'usergrpid', + }) + if state == 'list': + module.exit_json(changed=False, results=content['result'], state="list") + + if state == 'absent': + if not exists(content) or len(content['result']) == 0: + module.exit_json(changed=False, state="absent") + + content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0][idname]]) + module.exit_json(changed=True, results=content['result'], state="absent") + + if state == 'present': + + params = {'alias': module.params['login'], + 'passwd': get_passwd(module.params['password']), + 'usrgrps': get_usergroups(zapi, module.params['user_groups']), + 'name': module.params['first_name'], + 'surname': module.params['last_name'], + 'type': get_usertype(module.params['user_type']), + } + + # Remove any None valued params + _ = [params.pop(key, None) for key in params.keys() if params[key] is None] + + if not exists(content): + # if we didn't find it, create it + content = zapi.get_content(zbx_class_name, 'create', params) + + if content.has_key('Error'): + module.exit_json(failed=True, changed=False, results=content, state='present') + + module.exit_json(changed=True, results=content['result'], state='present') + # already exists, we need to update it + # let's compare properties + differences = {} + + # Update password + if not module.params['update_password']: + params.pop('passwd', None) + + zab_results = content['result'][0] + for key, value in params.items(): + + if key == 'usrgrps': + # this must be done as a list of ordered dictionaries fails comparison + if not all([True for _ in zab_results[key][0] if _ in value[0]]): + differences[key] = value + + elif zab_results[key] != value and zab_results[key] != str(value): + differences[key] = value + + if not differences: + module.exit_json(changed=False, results=zab_results, state="present") + + # We have differences and need to update + differences[idname] = zab_results[idname] + content = zapi.get_content(zbx_class_name, 'update', differences) + module.exit_json(changed=True, results=content['result'], state="present") + + module.exit_json(failed=True, + changed=False, + results='Unknown state passed. %s' % state, + state="unknown") + +# pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled +# import module snippets. This are required +from ansible.module_utils.basic import * + +main() diff --git a/roles/lib_zabbix/library/zbx_user_media.py b/roles/lib_zabbix/library/zbx_user_media.py new file mode 100644 index 000000000..aad3554dd --- /dev/null +++ b/roles/lib_zabbix/library/zbx_user_media.py @@ -0,0 +1,245 @@ +#!/usr/bin/env python +''' + Ansible module for user media +''' +# vim: expandtab:tabstop=4:shiftwidth=4 +# +# Zabbix user media ansible module +# +# +# Copyright 2015 Red Hat Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# This is in place because each module looks similar to each other. +# These need duplicate code as their behavior is very similar +# but different for each zabbix class. +# pylint: disable=duplicate-code + +# pylint: disable=import-error +from openshift_tools.monitoring.zbxapi import ZabbixAPI, ZabbixConnection + +def exists(content, key='result'): + ''' Check if key exists in content or the size of content[key] > 0 + ''' + if not content.has_key(key): + return False + + if not content[key]: + return False + + return True + +def get_mtype(zapi, mtype): + '''Get mediatype + + If passed an int, return it as the mediatypeid + if its a string, then try to fetch through a description + ''' + if isinstance(mtype, int): + return mtype + try: + return int(mtype) + except ValueError: + pass + + content = zapi.get_content('mediatype', 'get', {'search': {'description': mtype}}) + if content.has_key['result'] and content['result']: + return content['result'][0]['mediatypeid'] + + return None + +def get_user(zapi, user): + ''' Get userids from user aliases + ''' + content = zapi.get_content('user', 'get', {'search': {'alias': user}}) + if content['result']: + return content['result'][0] + + return None + +def get_severity(severity): + ''' determine severity + ''' + if isinstance(severity, int) or \ + isinstance(severity, str): + return severity + + val = 0 + sev_map = { + 'not': 2**0, + 'inf': 2**1, + 'war': 2**2, + 'ave': 2**3, + 'avg': 2**3, + 'hig': 2**4, + 'dis': 2**5, + } + for level in severity: + val |= sev_map[level[:3].lower()] + return val + +def get_zbx_user_query_data(zapi, user_name): + ''' If name exists, retrieve it, and build query params. + ''' + query = {} + if user_name: + zbx_user = get_user(zapi, user_name) + query = {'userid': zbx_user['userid']} + + return query + +def find_media(medias, user_media): + ''' Find the user media in the list of medias + ''' + for media in medias: + if all([media[key] == user_media[key] for key in user_media.keys()]): + return media + return None + +def get_active(in_active): + '''Determine active value + ''' + active = 1 + if in_active: + active = 0 + + return active + +def get_mediatype(zapi, mediatype, mediatype_desc): + ''' Determine mediatypeid + ''' + mtypeid = None + if mediatype: + mtypeid = get_mtype(zapi, mediatype) + elif mediatype_desc: + mtypeid = get_mtype(zapi, mediatype_desc) + + return mtypeid + +def main(): + ''' + Ansible zabbix module for mediatype + ''' + + module = AnsibleModule( + argument_spec=dict( + zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'), + zbx_user=dict(default=os.environ['ZABBIX_USER'], type='str'), + zbx_password=dict(default=os.environ['ZABBIX_PASSWORD'], type='str'), + zbx_debug=dict(default=False, type='bool'), + login=dict(default=None, type='str'), + active=dict(default=False, type='bool'), + medias=dict(default=None, type='list'), + mediaid=dict(default=None, type='int'), + mediatype=dict(default=None, type='str'), + mediatype_desc=dict(default=None, type='str'), + #d-d,hh:mm-hh:mm;d-d,hh:mm-hh:mm... + period=dict(default=None, type='str'), + sendto=dict(default=None, type='str'), + severity=dict(default=None, type='str'), + state=dict(default='present', type='str'), + ), + #supports_check_mode=True + ) + + zapi = ZabbixAPI(ZabbixConnection(module.params['zbx_server'], + module.params['zbx_user'], + module.params['zbx_password'], + module.params['zbx_debug'])) + + #Set the instance and the template for the rest of the calls + zbx_class_name = 'user' + idname = "mediaid" + state = module.params['state'] + + # User media is fetched through the usermedia.get + zbx_user_query = get_zbx_user_query_data(zapi, module.params['login']) + content = zapi.get_content('usermedia', 'get', zbx_user_query) + + if state == 'list': + module.exit_json(changed=False, results=content['result'], state="list") + + if state == 'absent': + if not exists(content) or len(content['result']) == 0: + module.exit_json(changed=False, state="absent") + + if not module.params['login']: + module.exit_json(failed=True, changed=False, results='Must specifiy a user login.', state="absent") + + content = zapi.get_content(zbx_class_name, 'deletemedia', [content['result'][0][idname]]) + + if content.has_key('error'): + module.exit_json(changed=False, results=content['error'], state="absent") + + module.exit_json(changed=True, results=content['result'], state="absent") + + if state == 'present': + active = get_active(module.params['active']) + mtypeid = get_mediatype(zapi, module.params['mediatype'], module.params['mediatype_desc']) + + medias = module.params['medias'] + if medias == None: + medias = [{'mediatypeid': mtypeid, + 'sendto': module.params['sendto'], + 'active': active, + 'severity': int(get_severity(module.params['severity'])), + 'period': module.params['period'], + }] + + params = {'users': [zbx_user_query], + 'medias': medias, + 'output': 'extend', + } + + if not exists(content): + # if we didn't find it, create it + content = zapi.get_content(zbx_class_name, 'addmedia', params) + + if content.has_key('error'): + module.exit_json(failed=True, changed=False, results=content['error'], state="present") + + module.exit_json(changed=True, results=content['result'], state='present') + + # mediaid signifies an update + # If user params exists, check to see if they already exist in zabbix + # if they exist, then return as no update + # elif they do not exist, then take user params only + diff = {'medias': [], 'users': {}} + _ = [diff['medias'].append(media) for media in params['medias'] if not find_media(content['result'], media)] + + if not diff['medias']: + module.exit_json(changed=False, results=content['result'], state="present") + + for user in params['users']: + diff['users']['userid'] = user['userid'] + + # We have differences and need to update + content = zapi.get_content(zbx_class_name, 'updatemedia', diff) + + if content.has_key('error'): + module.exit_json(failed=True, changed=False, results=content['error'], state="present") + + module.exit_json(changed=True, results=content['result'], state="present") + + module.exit_json(failed=True, + changed=False, + results='Unknown state passed. %s' % state, + state="unknown") + +# pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled +# import module snippets. This are required +from ansible.module_utils.basic import * + +main() diff --git a/roles/lib_zabbix/library/zbx_usergroup.py b/roles/lib_zabbix/library/zbx_usergroup.py new file mode 100644 index 000000000..297d8ef91 --- /dev/null +++ b/roles/lib_zabbix/library/zbx_usergroup.py @@ -0,0 +1,208 @@ +#!/usr/bin/env python +''' +zabbix ansible module for usergroups +''' +# vim: expandtab:tabstop=4:shiftwidth=4 +# +# Zabbix usergroup ansible module +# +# +# Copyright 2015 Red Hat Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# This is in place because each module looks similar to each other. +# These need duplicate code as their behavior is very similar +# but different for each zabbix class. +# pylint: disable=duplicate-code + +# pylint: disable=import-error +from openshift_tools.monitoring.zbxapi import ZabbixAPI, ZabbixConnection + +def exists(content, key='result'): + ''' Check if key exists in content or the size of content[key] > 0 + ''' + if not content.has_key(key): + return False + + if not content[key]: + return False + + return True + +def get_rights(zapi, rights): + '''Get rights + ''' + if rights == None: + return None + + perms = [] + for right in rights: + hstgrp = right.keys()[0] + perm = right.values()[0] + content = zapi.get_content('hostgroup', 'get', {'search': {'name': hstgrp}}) + if content['result']: + permission = 0 + if perm == 'ro': + permission = 2 + elif perm == 'rw': + permission = 3 + perms.append({'id': content['result'][0]['groupid'], + 'permission': permission}) + return perms + +def get_gui_access(access): + ''' Return the gui_access for a usergroup + ''' + access = access.lower() + if access == 'internal': + return 1 + elif access == 'disabled': + return 2 + + return 0 + +def get_debug_mode(mode): + ''' Return the debug_mode for a usergroup + ''' + mode = mode.lower() + if mode == 'enabled': + return 1 + + return 0 + +def get_user_status(status): + ''' Return the user_status for a usergroup + ''' + status = status.lower() + if status == 'enabled': + return 0 + + return 1 + + +#def get_userids(zapi, users): +# ''' Get userids from user aliases +# ''' +# if not users: +# return None +# +# userids = [] +# for alias in users: +# content = zapi.get_content('user', 'get', {'search': {'alias': alias}}) +# if content['result']: +# userids.append(content['result'][0]['userid']) +# +# return userids + +def main(): + ''' Ansible module for usergroup + ''' + + ##def usergroup(self, name, rights=None, users=None, state='present', params=None): + + module = AnsibleModule( + argument_spec=dict( + zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'), + zbx_user=dict(default=os.environ.get('ZABBIX_USER', None), type='str'), + zbx_password=dict(default=os.environ.get('ZABBIX_PASSWORD', None), type='str'), + zbx_debug=dict(default=False, type='bool'), + debug_mode=dict(default='disabled', type='str'), + gui_access=dict(default='default', type='str'), + status=dict(default='enabled', type='str'), + name=dict(default=None, type='str', required=True), + rights=dict(default=None, type='list'), + #users=dict(default=None, type='list'), + state=dict(default='present', type='str'), + ), + #supports_check_mode=True + ) + + zapi = ZabbixAPI(ZabbixConnection(module.params['zbx_server'], + module.params['zbx_user'], + module.params['zbx_password'], + module.params['zbx_debug'])) + + zbx_class_name = 'usergroup' + idname = "usrgrpid" + uname = module.params['name'] + state = module.params['state'] + + content = zapi.get_content(zbx_class_name, + 'get', + {'search': {'name': uname}, + 'selectUsers': 'userid', + }) + if state == 'list': + module.exit_json(changed=False, results=content['result'], state="list") + + if state == 'absent': + if not exists(content): + module.exit_json(changed=False, state="absent") + + if not uname: + module.exit_json(failed=True, changed=False, results='Need to pass in a user.', state="error") + + content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0][idname]]) + module.exit_json(changed=True, results=content['result'], state="absent") + + if state == 'present': + + params = {'name': uname, + 'rights': get_rights(zapi, module.params['rights']), + 'users_status': get_user_status(module.params['status']), + 'gui_access': get_gui_access(module.params['gui_access']), + 'debug_mode': get_debug_mode(module.params['debug_mode']), + #'userids': get_userids(zapi, module.params['users']), + } + + _ = [params.pop(key, None) for key in params.keys() if params[key] == None] + + if not exists(content): + # if we didn't find it, create it + content = zapi.get_content(zbx_class_name, 'create', params) + module.exit_json(changed=True, results=content['result'], state='present') + # already exists, we need to update it + # let's compare properties + differences = {} + zab_results = content['result'][0] + for key, value in params.items(): + if key == 'rights': + differences['rights'] = value + + #elif key == 'userids' and zab_results.has_key('users'): + #if zab_results['users'] != value: + #differences['userids'] = value + + elif zab_results[key] != value and zab_results[key] != str(value): + differences[key] = value + + if not differences: + module.exit_json(changed=False, results=zab_results, state="present") + + # We have differences and need to update + differences[idname] = zab_results[idname] + content = zapi.get_content(zbx_class_name, 'update', differences) + module.exit_json(changed=True, results=content['result'], state="present") + + module.exit_json(failed=True, + changed=False, + results='Unknown state passed. %s' % state, + state="unknown") + +# pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled +# import module snippets. This are required +from ansible.module_utils.basic import * + +main() diff --git a/roles/lib_zabbix/tasks/create_template.yml b/roles/lib_zabbix/tasks/create_template.yml new file mode 100644 index 000000000..022ca52f2 --- /dev/null +++ b/roles/lib_zabbix/tasks/create_template.yml @@ -0,0 +1,61 @@ +--- +- debug: var=template + +- name: Template Create Template + zbx_template: + zbx_server: "{{ server }}" + zbx_user: "{{ user }}" + zbx_password: "{{ password }}" + name: "{{ template.name }}" + register: created_template + +- debug: var=created_template + +- set_fact: + lzbx_applications: "{{ template.zitems | oo_select_keys_from_list(['applications']) | oo_flatten | unique }}" + +- debug: var=lzbx_applications + +- name: Create Application + zbx_application: + zbx_server: "{{ server }}" + zbx_user: "{{ user }}" + zbx_password: "{{ password }}" + name: "{{ item }}" + template_name: "{{ template.name }}" + with_items: lzbx_applications + register: created_application + when: template.zitems is defined + +- debug: var=created_application + +- name: Create Items + zbx_item: + zbx_server: "{{ server }}" + zbx_user: "{{ user }}" + zbx_password: "{{ password }}" + key: "{{ item.key }}" + name: "{{ item.name | default(item.key, true) }}" + value_type: "{{ item.value_type | default('int') }}" + template_name: "{{ template.name }}" + applications: "{{ item.applications }}" + with_items: template.zitems + register: created_items + when: template.zitems is defined + +#- debug: var=ctp_created_items + +- name: Create Triggers + zbx_trigger: + zbx_server: "{{ server }}" + zbx_user: "{{ user }}" + zbx_password: "{{ password }}" + description: "{{ item.description }}" + expression: "{{ item.expression }}" + priority: "{{ item.priority }}" + with_items: template.ztriggers + when: template.ztriggers is defined + +#- debug: var=ctp_created_triggers + + diff --git a/roles/lib_zabbix/tasks/create_user.yml b/roles/lib_zabbix/tasks/create_user.yml new file mode 100644 index 000000000..1f752a9e1 --- /dev/null +++ b/roles/lib_zabbix/tasks/create_user.yml @@ -0,0 +1,11 @@ +--- +- name: Update zabbix credentialss for a user + zbx_user: + server: "{{ ozb_server }}" + user: "{{ ozb_user }}" + password: "{{ ozb_password }}" + alias: "{{ ozb_username }}" + passwd: "{{ ozb_new_password | default(ozb_password, true) }}" + register: user + +- debug: var=user.results -- cgit v1.2.3 From e8d71b6ed7421644a765564c85ca3ee32182fed2 Mon Sep 17 00:00:00 2001 From: Kenny Woodson Date: Thu, 27 Aug 2015 17:02:34 -0400 Subject: Fixed env var defaults. --- roles/lib_zabbix/library/zbx_application.py | 4 ++-- roles/lib_zabbix/library/zbx_discoveryrule.py | 4 ++-- roles/lib_zabbix/library/zbx_host.py | 4 ++-- roles/lib_zabbix/library/zbx_hostgroup.py | 4 ++-- roles/lib_zabbix/library/zbx_item.py | 4 ++-- roles/lib_zabbix/library/zbx_itemprototype.py | 4 ++-- roles/lib_zabbix/library/zbx_mediatype.py | 4 ++-- roles/lib_zabbix/library/zbx_template.py | 4 ++-- roles/lib_zabbix/library/zbx_trigger.py | 4 ++-- roles/lib_zabbix/library/zbx_user.py | 4 ++-- roles/lib_zabbix/library/zbx_user_media.py | 4 ++-- 11 files changed, 22 insertions(+), 22 deletions(-) (limited to 'roles/lib_zabbix') diff --git a/roles/lib_zabbix/library/zbx_application.py b/roles/lib_zabbix/library/zbx_application.py index ffa00e052..d3d08c9dd 100644 --- a/roles/lib_zabbix/library/zbx_application.py +++ b/roles/lib_zabbix/library/zbx_application.py @@ -60,8 +60,8 @@ def main(): module = AnsibleModule( argument_spec=dict( zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'), - zbx_user=dict(default=os.environ['ZABBIX_USER'], type='str'), - zbx_password=dict(default=os.environ['ZABBIX_PASSWORD'], type='str'), + zbx_user=dict(default=os.environ.get('ZABBIX_USER', None), type='str'), + zbx_password=dict(default=os.environ.get('ZABBIX_PASSWORD', None), type='str'), zbx_debug=dict(default=False, type='bool'), name=dict(default=None, type='str'), template_name=dict(default=None, type='list'), diff --git a/roles/lib_zabbix/library/zbx_discoveryrule.py b/roles/lib_zabbix/library/zbx_discoveryrule.py index 79ee91180..71a0580c2 100644 --- a/roles/lib_zabbix/library/zbx_discoveryrule.py +++ b/roles/lib_zabbix/library/zbx_discoveryrule.py @@ -88,8 +88,8 @@ def main(): module = AnsibleModule( argument_spec=dict( zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'), - zbx_user=dict(default=os.environ['ZABBIX_USER'], type='str'), - zbx_password=dict(default=os.environ['ZABBIX_PASSWORD'], type='str'), + zbx_user=dict(default=os.environ.get('ZABBIX_USER', None), type='str'), + zbx_password=dict(default=os.environ.get('ZABBIX_PASSWORD', None), type='str'), zbx_debug=dict(default=False, type='bool'), name=dict(default=None, type='str'), key=dict(default=None, type='str'), diff --git a/roles/lib_zabbix/library/zbx_host.py b/roles/lib_zabbix/library/zbx_host.py index 7be03653e..e26c9caf3 100644 --- a/roles/lib_zabbix/library/zbx_host.py +++ b/roles/lib_zabbix/library/zbx_host.py @@ -71,8 +71,8 @@ def main(): module = AnsibleModule( argument_spec=dict( zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'), - zbx_user=dict(default=os.environ['ZABBIX_USER'], type='str'), - zbx_password=dict(default=os.environ['ZABBIX_PASSWORD'], type='str'), + zbx_user=dict(default=os.environ.get('ZABBIX_USER', None), type='str'), + zbx_password=dict(default=os.environ.get('ZABBIX_PASSWORD', None), type='str'), zbx_debug=dict(default=False, type='bool'), name=dict(default=None, type='str'), hostgroup_names=dict(default=[], type='list'), diff --git a/roles/lib_zabbix/library/zbx_hostgroup.py b/roles/lib_zabbix/library/zbx_hostgroup.py index f161d3d9f..7f080af24 100644 --- a/roles/lib_zabbix/library/zbx_hostgroup.py +++ b/roles/lib_zabbix/library/zbx_hostgroup.py @@ -47,8 +47,8 @@ def main(): module = AnsibleModule( argument_spec=dict( zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'), - zbx_user=dict(default=os.environ['ZABBIX_USER'], type='str'), - zbx_password=dict(default=os.environ['ZABBIX_PASSWORD'], type='str'), + zbx_user=dict(default=os.environ.get('ZABBIX_USER', None), type='str'), + zbx_password=dict(default=os.environ.get('ZABBIX_PASSWORD', None), type='str'), zbx_debug=dict(default=False, type='bool'), name=dict(default=None, type='str'), state=dict(default='present', type='str'), diff --git a/roles/lib_zabbix/library/zbx_item.py b/roles/lib_zabbix/library/zbx_item.py index 60da243fe..bcd389e47 100644 --- a/roles/lib_zabbix/library/zbx_item.py +++ b/roles/lib_zabbix/library/zbx_item.py @@ -80,8 +80,8 @@ def main(): module = AnsibleModule( argument_spec=dict( zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'), - zbx_user=dict(default=os.environ['ZABBIX_USER'], type='str'), - zbx_password=dict(default=os.environ['ZABBIX_PASSWORD'], type='str'), + zbx_user=dict(default=os.environ.get('ZABBIX_USER', None), type='str'), + zbx_password=dict(default=os.environ.get('ZABBIX_PASSWORD', None), type='str'), zbx_debug=dict(default=False, type='bool'), name=dict(default=None, type='str'), key=dict(default=None, type='str'), diff --git a/roles/lib_zabbix/library/zbx_itemprototype.py b/roles/lib_zabbix/library/zbx_itemprototype.py index 47100f613..24f85710d 100644 --- a/roles/lib_zabbix/library/zbx_itemprototype.py +++ b/roles/lib_zabbix/library/zbx_itemprototype.py @@ -142,8 +142,8 @@ def main(): module = AnsibleModule( argument_spec=dict( zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'), - zbx_user=dict(default=os.environ['ZABBIX_USER'], type='str'), - zbx_password=dict(default=os.environ['ZABBIX_PASSWORD'], type='str'), + zbx_user=dict(default=os.environ.get('ZABBIX_USER', None), type='str'), + zbx_password=dict(default=os.environ.get('ZABBIX_PASSWORD', None), type='str'), zbx_debug=dict(default=False, type='bool'), name=dict(default=None, type='str'), key=dict(default=None, type='str'), diff --git a/roles/lib_zabbix/library/zbx_mediatype.py b/roles/lib_zabbix/library/zbx_mediatype.py index cc72cc9a8..3be232ecf 100644 --- a/roles/lib_zabbix/library/zbx_mediatype.py +++ b/roles/lib_zabbix/library/zbx_mediatype.py @@ -74,8 +74,8 @@ def main(): module = AnsibleModule( argument_spec=dict( zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'), - zbx_user=dict(default=os.environ['ZABBIX_USER'], type='str'), - zbx_password=dict(default=os.environ['ZABBIX_PASSWORD'], type='str'), + zbx_user=dict(default=os.environ.get('ZABBIX_USER', None), type='str'), + zbx_password=dict(default=os.environ.get('ZABBIX_PASSWORD', None), type='str'), zbx_debug=dict(default=False, type='bool'), description=dict(default=None, type='str'), mtype=dict(default=None, type='str'), diff --git a/roles/lib_zabbix/library/zbx_template.py b/roles/lib_zabbix/library/zbx_template.py index 1592fa268..ff5714bdc 100644 --- a/roles/lib_zabbix/library/zbx_template.py +++ b/roles/lib_zabbix/library/zbx_template.py @@ -48,8 +48,8 @@ def main(): module = AnsibleModule( argument_spec=dict( zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'), - zbx_user=dict(default=os.environ['ZABBIX_USER'], type='str'), - zbx_password=dict(default=os.environ['ZABBIX_PASSWORD'], type='str'), + zbx_user=dict(default=os.environ.get('ZABBIX_USER', None), type='str'), + zbx_password=dict(default=os.environ.get('ZABBIX_PASSWORD', None), type='str'), zbx_debug=dict(default=False, type='bool'), name=dict(default=None, type='str'), state=dict(default='present', type='str'), diff --git a/roles/lib_zabbix/library/zbx_trigger.py b/roles/lib_zabbix/library/zbx_trigger.py index ffad5b40a..43f3d2677 100644 --- a/roles/lib_zabbix/library/zbx_trigger.py +++ b/roles/lib_zabbix/library/zbx_trigger.py @@ -94,8 +94,8 @@ def main(): module = AnsibleModule( argument_spec=dict( zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'), - zbx_user=dict(default=os.environ['ZABBIX_USER'], type='str'), - zbx_password=dict(default=os.environ['ZABBIX_PASSWORD'], type='str'), + zbx_user=dict(default=os.environ.get('ZABBIX_USER', None), type='str'), + zbx_password=dict(default=os.environ.get('ZABBIX_PASSWORD', None), type='str'), zbx_debug=dict(default=False, type='bool'), expression=dict(default=None, type='str'), description=dict(default=None, type='str'), diff --git a/roles/lib_zabbix/library/zbx_user.py b/roles/lib_zabbix/library/zbx_user.py index a9906d773..c916fa96a 100644 --- a/roles/lib_zabbix/library/zbx_user.py +++ b/roles/lib_zabbix/library/zbx_user.py @@ -89,8 +89,8 @@ def main(): module = AnsibleModule( argument_spec=dict( zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'), - zbx_user=dict(default=os.environ['ZABBIX_USER'], type='str'), - zbx_password=dict(default=os.environ['ZABBIX_PASSWORD'], type='str'), + zbx_user=dict(default=os.environ.get('ZABBIX_USER', None), type='str'), + zbx_password=dict(default=os.environ.get('ZABBIX_PASSWORD', None), type='str'), zbx_debug=dict(default=False, type='bool'), login=dict(default=None, type='str'), first_name=dict(default=None, type='str'), diff --git a/roles/lib_zabbix/library/zbx_user_media.py b/roles/lib_zabbix/library/zbx_user_media.py index aad3554dd..3f7760475 100644 --- a/roles/lib_zabbix/library/zbx_user_media.py +++ b/roles/lib_zabbix/library/zbx_user_media.py @@ -136,8 +136,8 @@ def main(): module = AnsibleModule( argument_spec=dict( zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'), - zbx_user=dict(default=os.environ['ZABBIX_USER'], type='str'), - zbx_password=dict(default=os.environ['ZABBIX_PASSWORD'], type='str'), + zbx_user=dict(default=os.environ.get('ZABBIX_USER', None), type='str'), + zbx_password=dict(default=os.environ.get('ZABBIX_PASSWORD', None), type='str'), zbx_debug=dict(default=False, type='bool'), login=dict(default=None, type='str'), active=dict(default=False, type='bool'), -- cgit v1.2.3 From 1f52ea8c4e2f8cfce51e98cb3614c61f0d78ec3e Mon Sep 17 00:00:00 2001 From: Thomas Wiest Date: Fri, 28 Aug 2015 18:03:59 -0400 Subject: added docker zabbix template, removed unused / old templates so they don't confuse other people. --- roles/lib_zabbix/library/zbx_trigger.py | 4 ++-- roles/lib_zabbix/tasks/create_template.yml | 36 ++++++++++++++---------------- 2 files changed, 19 insertions(+), 21 deletions(-) (limited to 'roles/lib_zabbix') diff --git a/roles/lib_zabbix/library/zbx_trigger.py b/roles/lib_zabbix/library/zbx_trigger.py index 43f3d2677..c707a2f64 100644 --- a/roles/lib_zabbix/library/zbx_trigger.py +++ b/roles/lib_zabbix/library/zbx_trigger.py @@ -65,7 +65,7 @@ def get_deps(zapi, deps): for desc in deps: content = zapi.get_content('trigger', 'get', - {'search': {'description': desc}, + {'filter': {'description': desc}, 'expandExpression': True, 'selectDependencies': 'triggerid', }) @@ -119,7 +119,7 @@ def main(): content = zapi.get_content(zbx_class_name, 'get', - {'search': {'description': description}, + {'filter': {'description': description}, 'expandExpression': True, 'selectDependencies': 'triggerid', }) diff --git a/roles/lib_zabbix/tasks/create_template.yml b/roles/lib_zabbix/tasks/create_template.yml index 022ca52f2..444fd0a14 100644 --- a/roles/lib_zabbix/tasks/create_template.yml +++ b/roles/lib_zabbix/tasks/create_template.yml @@ -16,18 +16,21 @@ - debug: var=lzbx_applications -- name: Create Application - zbx_application: - zbx_server: "{{ server }}" - zbx_user: "{{ user }}" - zbx_password: "{{ password }}" - name: "{{ item }}" - template_name: "{{ template.name }}" - with_items: lzbx_applications - register: created_application - when: template.zitems is defined - -- debug: var=created_application +# +# twiest: This is commented out because it doesn't work correctly +# +#- name: Create Application +# zbx_application: +# zbx_server: "{{ server }}" +# zbx_user: "{{ user }}" +# zbx_password: "{{ password }}" +# name: "{{ item }}" +# template_name: "{{ template.name }}" +# with_items: lzbx_applications +# register: created_application +# when: template.zitems is defined + +#- debug: var=created_application - name: Create Items zbx_item: @@ -38,24 +41,19 @@ name: "{{ item.name | default(item.key, true) }}" value_type: "{{ item.value_type | default('int') }}" template_name: "{{ template.name }}" - applications: "{{ item.applications }}" +# applications: "{{ item.applications }}" with_items: template.zitems register: created_items when: template.zitems is defined -#- debug: var=ctp_created_items - - name: Create Triggers zbx_trigger: zbx_server: "{{ server }}" zbx_user: "{{ user }}" zbx_password: "{{ password }}" description: "{{ item.description }}" + dependencies: "{{ item.dependencies | default([], true) }}" expression: "{{ item.expression }}" priority: "{{ item.priority }}" with_items: template.ztriggers when: template.ztriggers is defined - -#- debug: var=ctp_created_triggers - - -- cgit v1.2.3 From d39837b2be8ce6abfa8c69d7cc83f04c6130ccd5 Mon Sep 17 00:00:00 2001 From: Kenny Woodson Date: Tue, 1 Sep 2015 10:22:22 -0400 Subject: Fix for zbx applications --- roles/lib_zabbix/library/zbx_application.py | 21 +++--- roles/lib_zabbix/library/zbx_item.py | 103 +++++++++++++++++++--------- roles/lib_zabbix/tasks/create_template.yml | 32 +++------ 3 files changed, 93 insertions(+), 63 deletions(-) (limited to 'roles/lib_zabbix') diff --git a/roles/lib_zabbix/library/zbx_application.py b/roles/lib_zabbix/library/zbx_application.py index d3d08c9dd..21e3d91f4 100644 --- a/roles/lib_zabbix/library/zbx_application.py +++ b/roles/lib_zabbix/library/zbx_application.py @@ -41,16 +41,17 @@ def exists(content, key='result'): return True -def get_template_ids(zapi, template_names): +def get_template_ids(zapi, template_name): ''' get related templates ''' template_ids = [] # Fetch templates by name - for template_name in template_names: - content = zapi.get_content('template', 'get', {'search': {'host': template_name}}) - if content.has_key('result'): - template_ids.append(content['result'][0]['templateid']) + content = zapi.get_content('template', + 'get', + {'search': {'host': template_name}}) + if content.has_key('result'): + template_ids.append(content['result'][0]['templateid']) return template_ids def main(): @@ -63,8 +64,8 @@ def main(): zbx_user=dict(default=os.environ.get('ZABBIX_USER', None), type='str'), zbx_password=dict(default=os.environ.get('ZABBIX_PASSWORD', None), type='str'), zbx_debug=dict(default=False, type='bool'), - name=dict(default=None, type='str'), - template_name=dict(default=None, type='list'), + name=dict(default=None, type='str', required=True), + template_name=dict(default=None, type='str'), state=dict(default='present', type='str'), ), #supports_check_mode=True @@ -81,10 +82,11 @@ def main(): aname = module.params['name'] state = module.params['state'] # get a applicationid, see if it exists + tids = get_template_ids(zapi, module.params['template_name']) content = zapi.get_content(zbx_class_name, 'get', {'search': {'name': aname}, - 'selectHost': 'hostid', + 'templateids': tids[0], }) if state == 'list': module.exit_json(changed=False, results=content['result'], state="list") @@ -97,9 +99,10 @@ def main(): module.exit_json(changed=True, results=content['result'], state="absent") if state == 'present': - params = {'hostid': get_template_ids(zapi, module.params['template_name'])[0], + params = {'hostid': tids[0], 'name': aname, } + if not exists(content): # if we didn't find it, create it content = zapi.get_content(zbx_class_name, 'create', params) diff --git a/roles/lib_zabbix/library/zbx_item.py b/roles/lib_zabbix/library/zbx_item.py index bcd389e47..388db31b9 100644 --- a/roles/lib_zabbix/library/zbx_item.py +++ b/roles/lib_zabbix/library/zbx_item.py @@ -60,18 +60,36 @@ def get_value_type(value_type): return vtype -def get_app_ids(zapi, application_names): +def get_app_ids(application_names, app_name_ids): ''' get application ids from names ''' - if isinstance(application_names, str): - application_names = [application_names] - app_ids = [] - for app_name in application_names: - content = zapi.get_content('application', 'get', {'search': {'name': app_name}}) - if content.has_key('result'): - app_ids.append(content['result'][0]['applicationid']) - return app_ids + applications = [] + if application_names: + for app in application_names: + applications.append(app_name_ids[app]) + return applications + +def get_template_id(zapi, template_name): + ''' + get related templates + ''' + template_ids = [] + app_ids = {} + # Fetch templates by name + content = zapi.get_content('template', + 'get', + {'search': {'host': template_name}, + 'selectApplications': ['applicationid', 'name']}) + if content.has_key('result'): + template_ids.append(content['result'][0]['templateid']) + for app in content['result'][0]['applications']: + app_ids[app['name']] = app['applicationid'] + + return template_ids, app_ids + +# The branches are needed for CRUD and error handling +# pylint: disable=too-many-branches def main(): ''' ansible zabbix module for zbx_item @@ -88,7 +106,7 @@ def main(): template_name=dict(default=None, type='str'), zabbix_type=dict(default=2, type='int'), value_type=dict(default='int', type='str'), - applications=dict(default=[], type='list'), + applications=dict(default=None, type='list'), state=dict(default='present', type='str'), ), #supports_check_mode=True @@ -101,59 +119,74 @@ def main(): #Set the instance and the template for the rest of the calls zbx_class_name = 'item' - idname = "itemid" state = module.params['state'] - key = module.params['key'] - template_name = module.params['template_name'] - - content = zapi.get_content('template', 'get', {'search': {'host': template_name}}) - templateid = None - if content['result']: - templateid = content['result'][0]['templateid'] - else: - module.exit_json(changed=False, - results='Error: Could find template with name %s for item.' % template_name, + + templateid, app_name_ids = get_template_id(zapi, module.params['template_name']) + + # Fail if a template was not found matching the name + if not templateid: + module.exit_json(failed=True, + changed=False, + results='Error: Could find template with name %s for item.' % module.params['template_name'], state="Unkown") content = zapi.get_content(zbx_class_name, 'get', - {'search': {'key_': key}, + {'search': {'key_': module.params['key']}, 'selectApplications': 'applicationid', + 'templateids': templateid, }) + # Get if state == 'list': module.exit_json(changed=False, results=content['result'], state="list") + # Delete if state == 'absent': if not exists(content): module.exit_json(changed=False, state="absent") - content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0][idname]]) + content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0]['itemid']]) module.exit_json(changed=True, results=content['result'], state="absent") + # Create and Update if state == 'present': + params = {'name': module.params.get('name', module.params['key']), - 'key_': key, - 'hostid': templateid, + 'key_': module.params['key'], + 'hostid': templateid[0], 'type': module.params['zabbix_type'], 'value_type': get_value_type(module.params['value_type']), - 'applications': get_app_ids(zapi, module.params['applications']), + 'applications': get_app_ids(module.params['applications'], app_name_ids), } + # Remove any None valued params + _ = [params.pop(key, None) for key in params.keys() if params[key] is None] + + #******# + # CREATE + #******# if not exists(content): - # if we didn't find it, create it content = zapi.get_content(zbx_class_name, 'create', params) + + if content.has_key('error'): + module.exit_json(failed=True, changed=True, results=content['error'], state="present") + module.exit_json(changed=True, results=content['result'], state='present') - # already exists, we need to update it - # let's compare properties + + + ######## + # UPDATE + ######## + _ = params.pop('hostid', None) differences = {} zab_results = content['result'][0] for key, value in params.items(): if key == 'applications': - zab_apps = set([item['applicationid'] for item in zab_results[key]]) - if zab_apps != set(value): - differences[key] = zab_apps + app_ids = [item['applicationid'] for item in zab_results[key]] + if set(app_ids) != set(value): + differences[key] = value elif zab_results[key] != value and zab_results[key] != str(value): differences[key] = value @@ -162,8 +195,12 @@ def main(): module.exit_json(changed=False, results=zab_results, state="present") # We have differences and need to update - differences[idname] = zab_results[idname] + differences['itemid'] = zab_results['itemid'] content = zapi.get_content(zbx_class_name, 'update', differences) + + if content.has_key('error'): + module.exit_json(failed=True, changed=False, results=content['error'], state="present") + module.exit_json(changed=True, results=content['result'], state="present") module.exit_json(failed=True, diff --git a/roles/lib_zabbix/tasks/create_template.yml b/roles/lib_zabbix/tasks/create_template.yml index 444fd0a14..630d5dd70 100644 --- a/roles/lib_zabbix/tasks/create_template.yml +++ b/roles/lib_zabbix/tasks/create_template.yml @@ -1,6 +1,4 @@ --- -- debug: var=template - - name: Template Create Template zbx_template: zbx_server: "{{ server }}" @@ -9,28 +7,20 @@ name: "{{ template.name }}" register: created_template -- debug: var=created_template - set_fact: lzbx_applications: "{{ template.zitems | oo_select_keys_from_list(['applications']) | oo_flatten | unique }}" -- debug: var=lzbx_applications - -# -# twiest: This is commented out because it doesn't work correctly -# -#- name: Create Application -# zbx_application: -# zbx_server: "{{ server }}" -# zbx_user: "{{ user }}" -# zbx_password: "{{ password }}" -# name: "{{ item }}" -# template_name: "{{ template.name }}" -# with_items: lzbx_applications -# register: created_application -# when: template.zitems is defined - -#- debug: var=created_application +- name: Create Application + zbx_application: + zbx_server: "{{ server }}" + zbx_user: "{{ user }}" + zbx_password: "{{ password }}" + name: "{{ item }}" + template_name: "{{ template.name }}" + with_items: lzbx_applications + register: created_application + when: template.zitems is defined - name: Create Items zbx_item: @@ -41,7 +31,7 @@ name: "{{ item.name | default(item.key, true) }}" value_type: "{{ item.value_type | default('int') }}" template_name: "{{ template.name }}" -# applications: "{{ item.applications }}" + applications: "{{ item.applications }}" with_items: template.zitems register: created_items when: template.zitems is defined -- cgit v1.2.3 From d1542a1df3c0e08a759f659b661b65b07d1e4678 Mon Sep 17 00:00:00 2001 From: Kenny Woodson Date: Thu, 3 Sep 2015 15:45:13 -0400 Subject: Adding url support for triggers --- roles/lib_zabbix/library/zbx_trigger.py | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) (limited to 'roles/lib_zabbix') diff --git a/roles/lib_zabbix/library/zbx_trigger.py b/roles/lib_zabbix/library/zbx_trigger.py index c707a2f64..c384f6fa3 100644 --- a/roles/lib_zabbix/library/zbx_trigger.py +++ b/roles/lib_zabbix/library/zbx_trigger.py @@ -101,6 +101,7 @@ def main(): description=dict(default=None, type='str'), dependencies=dict(default=[], type='list'), priority=dict(default='avg', type='str'), + url=dict(default=None, type='str'), state=dict(default='present', type='str'), ), #supports_check_mode=True @@ -123,28 +124,41 @@ def main(): 'expandExpression': True, 'selectDependencies': 'triggerid', }) + + # Get if state == 'list': module.exit_json(changed=False, results=content['result'], state="list") + # Delete if state == 'absent': if not exists(content): module.exit_json(changed=False, state="absent") content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0][idname]]) module.exit_json(changed=True, results=content['result'], state="absent") + # Create and Update if state == 'present': params = {'description': description, 'expression': module.params['expression'], 'dependencies': get_deps(zapi, module.params['dependencies']), 'priority': get_priority(module.params['priority']), + 'url': module.params['url'], } + # Remove any None valued params + _ = [params.pop(key, None) for key in params.keys() if params[key] is None] + + #******# + # CREATE + #******# if not exists(content): # if we didn't find it, create it content = zapi.get_content(zbx_class_name, 'create', params) module.exit_json(changed=True, results=content['result'], state='present') - # already exists, we need to update it - # let's compare properties + + ######## + # UPDATE + ######## differences = {} zab_results = content['result'][0] for key, value in params.items(): -- cgit v1.2.3 From fcae524b50878c6413fe9daadccc2dae1d1721ba Mon Sep 17 00:00:00 2001 From: Kenny Woodson Date: Thu, 3 Sep 2015 16:12:52 -0400 Subject: Added trigger url --- roles/lib_zabbix/tasks/create_template.yml | 1 + 1 file changed, 1 insertion(+) (limited to 'roles/lib_zabbix') diff --git a/roles/lib_zabbix/tasks/create_template.yml b/roles/lib_zabbix/tasks/create_template.yml index 630d5dd70..bc9aff997 100644 --- a/roles/lib_zabbix/tasks/create_template.yml +++ b/roles/lib_zabbix/tasks/create_template.yml @@ -45,5 +45,6 @@ dependencies: "{{ item.dependencies | default([], true) }}" expression: "{{ item.expression }}" priority: "{{ item.priority }}" + url: "{{ item.url | default(None, True) }}" with_items: template.ztriggers when: template.ztriggers is defined -- cgit v1.2.3 From 4824691f00c04936da74ddfbbeb6e521ddb86d98 Mon Sep 17 00:00:00 2001 From: Kenny Woodson Date: Tue, 8 Sep 2015 15:55:45 -0400 Subject: Adding desc, multiplier, and units to zabbix item --- roles/lib_zabbix/library/zbx_item.py | 33 ++++++++++++++++++++++++++++-- roles/lib_zabbix/tasks/create_template.yml | 3 +++ 2 files changed, 34 insertions(+), 2 deletions(-) (limited to 'roles/lib_zabbix') diff --git a/roles/lib_zabbix/library/zbx_item.py b/roles/lib_zabbix/library/zbx_item.py index 388db31b9..11e3c7b2b 100644 --- a/roles/lib_zabbix/library/zbx_item.py +++ b/roles/lib_zabbix/library/zbx_item.py @@ -88,6 +88,23 @@ def get_template_id(zapi, template_name): return template_ids, app_ids +def get_multiplier(inval): + ''' Determine the multiplier + ''' + if inval == None or inval == '': + return None, None + + rval = None + try: + rval = int(inval) + except ValueError: + pass + + if rval: + return rval, True + + return rval, False + # The branches are needed for CRUD and error handling # pylint: disable=too-many-branches def main(): @@ -106,6 +123,9 @@ def main(): template_name=dict(default=None, type='str'), zabbix_type=dict(default=2, type='int'), value_type=dict(default='int', type='str'), + multiplier=dict(default=None, type='str'), + description=dict(default=None, type='str'), + units=dict(default=None, type='str'), applications=dict(default=None, type='list'), state=dict(default='present', type='str'), ), @@ -137,11 +157,15 @@ def main(): 'templateids': templateid, }) - # Get + #******# + # GET + #******# if state == 'list': module.exit_json(changed=False, results=content['result'], state="list") - # Delete + #******# + # DELETE + #******# if state == 'absent': if not exists(content): module.exit_json(changed=False, state="absent") @@ -152,12 +176,17 @@ def main(): # Create and Update if state == 'present': + formula, use_multiplier = get_multiplier(module.params['multiplier']) params = {'name': module.params.get('name', module.params['key']), 'key_': module.params['key'], 'hostid': templateid[0], 'type': module.params['zabbix_type'], 'value_type': get_value_type(module.params['value_type']), 'applications': get_app_ids(module.params['applications'], app_name_ids), + 'formula': formula, + 'multiplier': use_multiplier, + 'description': module.params['description'], + 'units': module.params['units'], } # Remove any None valued params diff --git a/roles/lib_zabbix/tasks/create_template.yml b/roles/lib_zabbix/tasks/create_template.yml index bc9aff997..6307bf57a 100644 --- a/roles/lib_zabbix/tasks/create_template.yml +++ b/roles/lib_zabbix/tasks/create_template.yml @@ -30,6 +30,9 @@ key: "{{ item.key }}" name: "{{ item.name | default(item.key, true) }}" value_type: "{{ item.value_type | default('int') }}" + description: "{{ item.description | default('', True) }}" + multiplier: "{{ item.multiplier | default('', True) }}" + units: "{{ item.units | default('', True) }}" template_name: "{{ template.name }}" applications: "{{ item.applications }}" with_items: template.zitems -- cgit v1.2.3 From 4e5ddae5018ebab6cba0ba83de2702adfabeb478 Mon Sep 17 00:00:00 2001 From: Kenny Woodson Date: Thu, 10 Sep 2015 11:25:08 -0400 Subject: Adding capability to have descriptions on triggers --- roles/lib_zabbix/library/zbx_trigger.py | 8 +++++--- roles/lib_zabbix/tasks/create_template.yml | 5 +++-- 2 files changed, 8 insertions(+), 5 deletions(-) (limited to 'roles/lib_zabbix') diff --git a/roles/lib_zabbix/library/zbx_trigger.py b/roles/lib_zabbix/library/zbx_trigger.py index c384f6fa3..a05de7e68 100644 --- a/roles/lib_zabbix/library/zbx_trigger.py +++ b/roles/lib_zabbix/library/zbx_trigger.py @@ -98,6 +98,7 @@ def main(): zbx_password=dict(default=os.environ.get('ZABBIX_PASSWORD', None), type='str'), zbx_debug=dict(default=False, type='bool'), expression=dict(default=None, type='str'), + name=dict(default=None, type='str'), description=dict(default=None, type='str'), dependencies=dict(default=[], type='list'), priority=dict(default='avg', type='str'), @@ -116,11 +117,11 @@ def main(): zbx_class_name = 'trigger' idname = "triggerid" state = module.params['state'] - description = module.params['description'] + tname = module.params['name'] content = zapi.get_content(zbx_class_name, 'get', - {'filter': {'description': description}, + {'filter': {'description': tname}, 'expandExpression': True, 'selectDependencies': 'triggerid', }) @@ -138,7 +139,8 @@ def main(): # Create and Update if state == 'present': - params = {'description': description, + params = {'description': tname, + 'comments': module.params['description'], 'expression': module.params['expression'], 'dependencies': get_deps(zapi, module.params['dependencies']), 'priority': get_priority(module.params['priority']), diff --git a/roles/lib_zabbix/tasks/create_template.yml b/roles/lib_zabbix/tasks/create_template.yml index 6307bf57a..fd0cdd46f 100644 --- a/roles/lib_zabbix/tasks/create_template.yml +++ b/roles/lib_zabbix/tasks/create_template.yml @@ -44,8 +44,9 @@ zbx_server: "{{ server }}" zbx_user: "{{ user }}" zbx_password: "{{ password }}" - description: "{{ item.description }}" - dependencies: "{{ item.dependencies | default([], true) }}" + name: "{{ item.name }}" + description: "{{ item.description | default('', True) }}" + dependencies: "{{ item.dependencies | default([], True) }}" expression: "{{ item.expression }}" priority: "{{ item.priority }}" url: "{{ item.url | default(None, True) }}" -- cgit v1.2.3 From 5adc02254b9eb4ac2e308104711eeec7e39b2c4e Mon Sep 17 00:00:00 2001 From: Kenny Woodson Date: Fri, 11 Sep 2015 13:01:20 -0400 Subject: Fixes for zbx api --- roles/lib_zabbix/library/zbx_item.py | 6 +++--- roles/lib_zabbix/library/zbx_user.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) (limited to 'roles/lib_zabbix') diff --git a/roles/lib_zabbix/library/zbx_item.py b/roles/lib_zabbix/library/zbx_item.py index 11e3c7b2b..2ccc21292 100644 --- a/roles/lib_zabbix/library/zbx_item.py +++ b/roles/lib_zabbix/library/zbx_item.py @@ -92,7 +92,7 @@ def get_multiplier(inval): ''' Determine the multiplier ''' if inval == None or inval == '': - return None, None + return None, 0 rval = None try: @@ -101,9 +101,9 @@ def get_multiplier(inval): pass if rval: - return rval, True + return rval, 1 - return rval, False + return rval, 0 # The branches are needed for CRUD and error handling # pylint: disable=too-many-branches diff --git a/roles/lib_zabbix/library/zbx_user.py b/roles/lib_zabbix/library/zbx_user.py index c916fa96a..62c85c1bf 100644 --- a/roles/lib_zabbix/library/zbx_user.py +++ b/roles/lib_zabbix/library/zbx_user.py @@ -164,7 +164,7 @@ def main(): if key == 'usrgrps': # this must be done as a list of ordered dictionaries fails comparison - if not all([True for _ in zab_results[key][0] if _ in value[0]]): + if not all([_ in value for _ in zab_results[key]]): differences[key] = value elif zab_results[key] != value and zab_results[key] != str(value): -- cgit v1.2.3 From b800a153702168419d93ca82c8fa28f009bb64be Mon Sep 17 00:00:00 2001 From: Kenny Woodson Date: Tue, 22 Sep 2015 14:57:37 -0400 Subject: Fixed a few bugs and added support for prototypes and discoveryrules. --- roles/lib_zabbix/library/zbx_discoveryrule.py | 36 +++++++++++++++-- roles/lib_zabbix/library/zbx_itemprototype.py | 56 +++++++++++++++++++++------ 2 files changed, 76 insertions(+), 16 deletions(-) (limited to 'roles/lib_zabbix') diff --git a/roles/lib_zabbix/library/zbx_discoveryrule.py b/roles/lib_zabbix/library/zbx_discoveryrule.py index 71a0580c2..71141bd54 100644 --- a/roles/lib_zabbix/library/zbx_discoveryrule.py +++ b/roles/lib_zabbix/library/zbx_discoveryrule.py @@ -85,6 +85,7 @@ def main(): Ansible module for zabbix discovery rules ''' + module = AnsibleModule( argument_spec=dict( zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'), @@ -113,18 +114,27 @@ def main(): idname = "itemid" dname = module.params['name'] state = module.params['state'] + template = get_template(zapi, module.params['template_name']) # selectInterfaces doesn't appear to be working but is needed. content = zapi.get_content(zbx_class_name, 'get', {'search': {'name': dname}, + 'templateids': template['templateid'], #'selectDServices': 'extend', #'selectDChecks': 'extend', #'selectDhosts': 'dhostid', }) + + #******# + # GET + #******# if state == 'list': module.exit_json(changed=False, results=content['result'], state="list") + #******# + # DELETE + #******# if state == 'absent': if not exists(content): module.exit_json(changed=False, state="absent") @@ -132,8 +142,9 @@ def main(): content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0][idname]]) module.exit_json(changed=True, results=content['result'], state="absent") + + # Create and Update if state == 'present': - template = get_template(zapi, module.params['template_name']) params = {'name': dname, 'key_': module.params['key'], 'hostid': template['templateid'], @@ -144,12 +155,23 @@ def main(): if params['type'] in [2, 5, 7, 11]: params.pop('interfaceid') + # Remove any None valued params + _ = [params.pop(key, None) for key in params.keys() if params[key] is None] + + #******# + # CREATE + #******# if not exists(content): - # if we didn't find it, create it content = zapi.get_content(zbx_class_name, 'create', params) + + if content.has_key('error'): + module.exit_json(failed=True, changed=True, results=content['error'], state="present") + module.exit_json(changed=True, results=content['result'], state='present') - # already exists, we need to update it - # let's compare properties + + ######## + # UPDATE + ######## differences = {} zab_results = content['result'][0] for key, value in params.items(): @@ -161,8 +183,14 @@ def main(): module.exit_json(changed=False, results=zab_results, state="present") # We have differences and need to update + module.exit_json(failed=True, changed=False, results=differences, state="present") + differences[idname] = zab_results[idname] content = zapi.get_content(zbx_class_name, 'update', differences) + + if content.has_key('error'): + module.exit_json(failed=True, changed=False, results=content['error'], state="present") + module.exit_json(changed=True, results=content['result'], state="present") module.exit_json(failed=True, diff --git a/roles/lib_zabbix/library/zbx_itemprototype.py b/roles/lib_zabbix/library/zbx_itemprototype.py index 24f85710d..b93b7729e 100644 --- a/roles/lib_zabbix/library/zbx_itemprototype.py +++ b/roles/lib_zabbix/library/zbx_itemprototype.py @@ -38,13 +38,14 @@ def exists(content, key='result'): return True -def get_rule_id(zapi, discoveryrule_name): +def get_rule_id(zapi, discoveryrule_name, templateid): '''get a discoveryrule by name ''' content = zapi.get_content('discoveryrule', 'get', {'search': {'name': discoveryrule_name}, 'output': 'extend', + 'templateids': templateid, }) if not content['result']: return None @@ -53,6 +54,9 @@ def get_rule_id(zapi, discoveryrule_name): def get_template(zapi, template_name): '''get a template by name ''' + if not template_name: + return None + content = zapi.get_content('template', 'get', {'search': {'host': template_name}, @@ -134,6 +138,7 @@ def get_app_ids(zapi, application_names): app_ids.append(content['result'][0]['applicationid']) return app_ids +# pylint: disable=too-many-branches def main(): ''' Ansible module for zabbix discovery rules @@ -152,10 +157,10 @@ def main(): value_type=dict(default='float', type='str'), delay=dict(default=60, type='int'), lifetime=dict(default=30, type='int'), - template_name=dict(default=[], type='list'), + template_name=dict(default=None, required=True, type='str'), state=dict(default='present', type='str'), status=dict(default='enabled', type='str'), - discoveryrule_name=dict(default=None, type='str'), + discoveryrule_name=dict(default=None, required=True, type='str'), applications=dict(default=[], type='list'), ), #supports_check_mode=True @@ -169,20 +174,26 @@ def main(): #Set the instance and the template for the rest of the calls zbx_class_name = 'itemprototype' idname = "itemid" - dname = module.params['name'] state = module.params['state'] + template = get_template(zapi, module.params['template_name']) # selectInterfaces doesn't appear to be working but is needed. content = zapi.get_content(zbx_class_name, 'get', - {'search': {'name': dname}, + {'search': {'name': module.params['name']}, 'selectApplications': 'applicationid', 'selectDiscoveryRule': 'itemid', - #'selectDhosts': 'dhostid', }) + + #******# + # GET + #******# if state == 'list': module.exit_json(changed=False, results=content['result'], state="list") + #******# + # DELETE + #******# if state == 'absent': if not exists(content): module.exit_json(changed=False, state="absent") @@ -190,26 +201,38 @@ def main(): content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0][idname]]) module.exit_json(changed=True, results=content['result'], state="absent") + # Create and Update if state == 'present': - template = get_template(zapi, module.params['template_name']) - params = {'name': dname, + params = {'name': module.params['name'], 'key_': module.params['key'], 'hostid': template['templateid'], 'interfaceid': module.params['interfaceid'], - 'ruleid': get_rule_id(zapi, module.params['discoveryrule_name']), + 'ruleid': get_rule_id(zapi, module.params['discoveryrule_name'], template['templateid']), 'type': get_type(module.params['ztype']), 'value_type': get_value_type(module.params['value_type']), 'applications': get_app_ids(zapi, module.params['applications']), } + if params['type'] in [2, 5, 7, 8, 11, 15]: params.pop('interfaceid') + # Remove any None valued params + _ = [params.pop(key, None) for key in params.keys() if params[key] is None] + + #******# + # CREATE + #******# if not exists(content): - # if we didn't find it, create it content = zapi.get_content(zbx_class_name, 'create', params) + + if content.has_key('error'): + module.exit_json(failed=True, changed=True, results=content['error'], state="present") + module.exit_json(changed=True, results=content['result'], state='present') - # already exists, we need to update it - # let's compare properties + + #******# + # UPDATE + #******# differences = {} zab_results = content['result'][0] for key, value in params.items(): @@ -218,6 +241,11 @@ def main(): if value != zab_results['discoveryRule']['itemid']: differences[key] = value + elif key == 'applications': + app_ids = [app['applicationid'] for app in zab_results[key]] + if set(app_ids) - set(value): + differences[key] = value + elif zab_results[key] != value and zab_results[key] != str(value): differences[key] = value @@ -227,6 +255,10 @@ def main(): # We have differences and need to update differences[idname] = zab_results[idname] content = zapi.get_content(zbx_class_name, 'update', differences) + + if content.has_key('error'): + module.exit_json(failed=True, changed=False, results=content['error'], state="present") + module.exit_json(changed=True, results=content['result'], state="present") module.exit_json(failed=True, -- cgit v1.2.3 From 176258e9c9e9254fed8ba997a80a0262b5e2ede5 Mon Sep 17 00:00:00 2001 From: Kenny Woodson Date: Tue, 22 Sep 2015 15:33:39 -0400 Subject: Fixed a bug and removed the need for template and discoveryrule --- roles/lib_zabbix/library/zbx_discoveryrule.py | 2 -- roles/lib_zabbix/library/zbx_itemprototype.py | 12 +++++------- 2 files changed, 5 insertions(+), 9 deletions(-) (limited to 'roles/lib_zabbix') diff --git a/roles/lib_zabbix/library/zbx_discoveryrule.py b/roles/lib_zabbix/library/zbx_discoveryrule.py index 71141bd54..f32267818 100644 --- a/roles/lib_zabbix/library/zbx_discoveryrule.py +++ b/roles/lib_zabbix/library/zbx_discoveryrule.py @@ -183,8 +183,6 @@ def main(): module.exit_json(changed=False, results=zab_results, state="present") # We have differences and need to update - module.exit_json(failed=True, changed=False, results=differences, state="present") - differences[idname] = zab_results[idname] content = zapi.get_content(zbx_class_name, 'update', differences) diff --git a/roles/lib_zabbix/library/zbx_itemprototype.py b/roles/lib_zabbix/library/zbx_itemprototype.py index b93b7729e..75b9e25b7 100644 --- a/roles/lib_zabbix/library/zbx_itemprototype.py +++ b/roles/lib_zabbix/library/zbx_itemprototype.py @@ -157,10 +157,8 @@ def main(): value_type=dict(default='float', type='str'), delay=dict(default=60, type='int'), lifetime=dict(default=30, type='int'), - template_name=dict(default=None, required=True, type='str'), state=dict(default='present', type='str'), status=dict(default='enabled', type='str'), - discoveryrule_name=dict(default=None, required=True, type='str'), applications=dict(default=[], type='list'), ), #supports_check_mode=True @@ -175,14 +173,14 @@ def main(): zbx_class_name = 'itemprototype' idname = "itemid" state = module.params['state'] - template = get_template(zapi, module.params['template_name']) # selectInterfaces doesn't appear to be working but is needed. content = zapi.get_content(zbx_class_name, 'get', - {'search': {'name': module.params['name']}, + {'search': {'key_': module.params['key']}, 'selectApplications': 'applicationid', 'selectDiscoveryRule': 'itemid', + 'templated': True, }) #******# @@ -205,9 +203,9 @@ def main(): if state == 'present': params = {'name': module.params['name'], 'key_': module.params['key'], - 'hostid': template['templateid'], + 'hostid': content['result'][0]['hostid'], 'interfaceid': module.params['interfaceid'], - 'ruleid': get_rule_id(zapi, module.params['discoveryrule_name'], template['templateid']), + 'ruleid': content['result'][0]['discoveryRule']['itemid'], 'type': get_type(module.params['ztype']), 'value_type': get_value_type(module.params['value_type']), 'applications': get_app_ids(zapi, module.params['applications']), @@ -226,7 +224,7 @@ def main(): content = zapi.get_content(zbx_class_name, 'create', params) if content.has_key('error'): - module.exit_json(failed=True, changed=True, results=content['error'], state="present") + module.exit_json(failed=True, changed=False, results=content['error'], state="present") module.exit_json(changed=True, results=content['result'], state='present') -- cgit v1.2.3 From 984c3f7e47039be37b700536367d26ca02b61522 Mon Sep 17 00:00:00 2001 From: Kenny Woodson Date: Tue, 22 Sep 2015 15:56:46 -0400 Subject: Added descriptions and parameters required for associating prototypes to discovery rules. --- roles/lib_zabbix/library/zbx_discoveryrule.py | 2 ++ roles/lib_zabbix/library/zbx_itemprototype.py | 13 +++++++++---- 2 files changed, 11 insertions(+), 4 deletions(-) (limited to 'roles/lib_zabbix') diff --git a/roles/lib_zabbix/library/zbx_discoveryrule.py b/roles/lib_zabbix/library/zbx_discoveryrule.py index f32267818..f52f350a5 100644 --- a/roles/lib_zabbix/library/zbx_discoveryrule.py +++ b/roles/lib_zabbix/library/zbx_discoveryrule.py @@ -94,6 +94,7 @@ def main(): zbx_debug=dict(default=False, type='bool'), name=dict(default=None, type='str'), key=dict(default=None, type='str'), + description=dict(default=None, type='str'), interfaceid=dict(default=None, type='int'), ztype=dict(default='trapper', type='str'), delay=dict(default=60, type='int'), @@ -151,6 +152,7 @@ def main(): 'interfaceid': module.params['interfaceid'], 'lifetime': module.params['lifetime'], 'type': get_type(module.params['ztype']), + 'description': module.params['description'], } if params['type'] in [2, 5, 7, 11]: params.pop('interfaceid') diff --git a/roles/lib_zabbix/library/zbx_itemprototype.py b/roles/lib_zabbix/library/zbx_itemprototype.py index 75b9e25b7..4ec1b8e02 100644 --- a/roles/lib_zabbix/library/zbx_itemprototype.py +++ b/roles/lib_zabbix/library/zbx_itemprototype.py @@ -38,12 +38,12 @@ def exists(content, key='result'): return True -def get_rule_id(zapi, discoveryrule_name, templateid): +def get_rule_id(zapi, discoveryrule_key, templateid): '''get a discoveryrule by name ''' content = zapi.get_content('discoveryrule', 'get', - {'search': {'name': discoveryrule_name}, + {'search': {'key_': discoveryrule_key}, 'output': 'extend', 'templateids': templateid, }) @@ -152,6 +152,7 @@ def main(): zbx_debug=dict(default=False, type='bool'), name=dict(default=None, type='str'), key=dict(default=None, type='str'), + description=dict(default=None, type='str'), interfaceid=dict(default=None, type='int'), ztype=dict(default='trapper', type='str'), value_type=dict(default='float', type='str'), @@ -160,6 +161,8 @@ def main(): state=dict(default='present', type='str'), status=dict(default='enabled', type='str'), applications=dict(default=[], type='list'), + template_name=dict(default=None, type='str'), + discoveryrule_key=dict(default=None, type='str'), ), #supports_check_mode=True ) @@ -173,6 +176,7 @@ def main(): zbx_class_name = 'itemprototype' idname = "itemid" state = module.params['state'] + template = get_template(zapi, module.params['template_name']) # selectInterfaces doesn't appear to be working but is needed. content = zapi.get_content(zbx_class_name, @@ -203,12 +207,13 @@ def main(): if state == 'present': params = {'name': module.params['name'], 'key_': module.params['key'], - 'hostid': content['result'][0]['hostid'], + 'hostid': template['templateid'], 'interfaceid': module.params['interfaceid'], - 'ruleid': content['result'][0]['discoveryRule']['itemid'], + 'ruleid': get_rule_id(zapi, module.params['discoveryrule_key'], template['templateid']), 'type': get_type(module.params['ztype']), 'value_type': get_value_type(module.params['value_type']), 'applications': get_app_ids(zapi, module.params['applications']), + 'description': module.params['description'], } if params['type'] in [2, 5, 7, 8, 11, 15]: -- cgit v1.2.3 From 19f91f7b7844ec3c89d8ee0e6a6c08655e897266 Mon Sep 17 00:00:00 2001 From: Matt Woodson Date: Fri, 25 Sep 2015 12:05:03 -0400 Subject: added support for dynaic keys and items. added dynamic filesystems to zabbix --- roles/lib_zabbix/tasks/create_template.yml | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) (limited to 'roles/lib_zabbix') diff --git a/roles/lib_zabbix/tasks/create_template.yml b/roles/lib_zabbix/tasks/create_template.yml index fd0cdd46f..b4821bdc7 100644 --- a/roles/lib_zabbix/tasks/create_template.yml +++ b/roles/lib_zabbix/tasks/create_template.yml @@ -52,3 +52,31 @@ url: "{{ item.url | default(None, True) }}" with_items: template.ztriggers when: template.ztriggers is defined + +- name: Create Discoveryrules + zbx_discoveryrule: + zbx_server: "{{ server }}" + zbx_user: "{{ user }}" + zbx_password: "{{ password }}" + name: "{{ item.name }}" + key: "{{ item.key }}" + lifetime: "{{ item.lifetime }}" + template_name: "{{ template.name }}" + description: "{{ item.description | default('', True) }}" + with_items: template.zdiscoveryrules + when: template.zdiscoveryrules is defined + +- name: Create Item Prototype + zbx_itemprototype: + zbx_server: "{{ server }}" + zbx_user: "{{ user }}" + zbx_password: "{{ password }}" + name: "{{ item.name }}" + key: "{{ item.key }}" + discoveryrule_key: "{{ item.discoveryrule_key }}" + value_type: "{{ item.value_type }}" + template_name: "{{ template.name }}" + applications: "{{ item.applications }}" + description: "{{ item.description | default('', True) }}" + with_items: template.zitemprototypes + when: template.zitemprototypes is defined -- cgit v1.2.3 From 10c85e1e5f283f7e0fa788b43b022314284dc776 Mon Sep 17 00:00:00 2001 From: Kenny Woodson Date: Wed, 23 Sep 2015 17:31:05 -0400 Subject: Initial stab at zabbix actions --- roles/lib_zabbix/library/zbx_action.py | 538 +++++++++++++++++++++++++++++++++ 1 file changed, 538 insertions(+) create mode 100644 roles/lib_zabbix/library/zbx_action.py (limited to 'roles/lib_zabbix') diff --git a/roles/lib_zabbix/library/zbx_action.py b/roles/lib_zabbix/library/zbx_action.py new file mode 100644 index 000000000..d64cebae1 --- /dev/null +++ b/roles/lib_zabbix/library/zbx_action.py @@ -0,0 +1,538 @@ +#!/usr/bin/env python +''' + Ansible module for zabbix actions +''' +# vim: expandtab:tabstop=4:shiftwidth=4 +# +# Zabbix action ansible module +# +# +# Copyright 2015 Red Hat Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# This is in place because each module looks similar to each other. +# These need duplicate code as their behavior is very similar +# but different for each zabbix class. +# pylint: disable=duplicate-code + +# pylint: disable=import-error +from openshift_tools.monitoring.zbxapi import ZabbixAPI, ZabbixConnection, ZabbixAPIError + +def exists(content, key='result'): + ''' Check if key exists in content or the size of content[key] > 0 + ''' + if not content.has_key(key): + return False + + if not content[key]: + return False + + return True + +def conditions_equal(zab_conditions, user_conditions): + '''Compare two lists of conditions''' + c_type = 'conditiontype' + _op = 'operator' + val = 'value' + if len(user_conditions) != len(zab_conditions): + return False + + for zab_cond, user_cond in zip(zab_conditions, user_conditions): + if zab_cond[c_type] != str(user_cond[c_type]) or zab_cond[_op] != str(user_cond[_op]) or \ + zab_cond[val] != str(user_cond[val]): + return False + + return True + +def filter_differences(zabbix_filters, user_filters): + '''Determine the differences from user and zabbix for operations''' + rval = {} + for key, val in user_filters.items(): + + if key == 'conditions': + if not conditions_equal(zabbix_filters[key], val): + rval[key] = val + + elif zabbix_filters[key] != str(val): + rval[key] = val + + return rval + +# This logic is quite complex. We are comparing two lists of dictionaries. +# The outer for-loops allow us to descend down into both lists at the same time +# and then walk over the key,val pairs of the incoming user dict's changes +# or updates. The if-statements are looking at different sub-object types and +# comparing them. The other suggestion on how to write this is to write a recursive +# compare function but for the time constraints and for complexity I decided to go +# this route. +# pylint: disable=too-many-branches +def operation_differences(zabbix_ops, user_ops): + '''Determine the differences from user and zabbix for operations''' + + # if they don't match, take the user options + if len(zabbix_ops) != len(user_ops): + return user_ops + + rval = {} + for zab, user in zip(zabbix_ops, user_ops): + for key, val in user.items(): + if key == 'opconditions': + for z_cond, u_cond in zip(zab[key], user[key]): + if not all([str(u_cond[op_key]) == z_cond[op_key] for op_key in \ + ['conditiontype', 'operator', 'value']]): + rval[key] = val + break + elif key == 'opmessage': + # Verify each passed param matches + for op_msg_key, op_msg_val in val.items(): + if zab[key][op_msg_key] != str(op_msg_val): + rval[key] = val + break + + elif key == 'opmessage_grp': + zab_grp_ids = set([ugrp['usrgrpid'] for ugrp in zab[key]]) + usr_grp_ids = set([ugrp['usrgrpid'] for ugrp in val]) + if usr_grp_ids != zab_grp_ids: + rval[key] = val + + elif key == 'opmessage_usr': + zab_usr_ids = set([usr['userid'] for usr in zab[key]]) + usr_ids = set([usr['userid'] for usr in val]) + if usr_ids != zab_usr_ids: + rval[key] = val + + elif zab[key] != str(val): + rval[key] = val + return rval + +def get_users(zapi, users): + '''get the mediatype id from the mediatype name''' + rval_users = [] + + for user in users: + content = zapi.get_content('user', + 'get', + {'filter': {'alias': user}}) + rval_users.append({'userid': content['result'][0]['userid']}) + + return rval_users + +def get_user_groups(zapi, groups): + '''get the mediatype id from the mediatype name''' + user_groups = [] + + content = zapi.get_content('usergroup', + 'get', + {'search': {'name': groups}}) + + for usr_grp in content['result']: + user_groups.append({'usrgrpid': usr_grp['usrgrpid']}) + + return user_groups + +def get_mediatype_id_by_name(zapi, m_name): + '''get the mediatype id from the mediatype name''' + content = zapi.get_content('mediatype', + 'get', + {'filter': {'description': m_name}}) + + return content['result'][0]['mediatypeid'] + +def get_priority(priority): + ''' determine priority + ''' + prior = 0 + if 'info' in priority: + prior = 1 + elif 'warn' in priority: + prior = 2 + elif 'avg' == priority or 'ave' in priority: + prior = 3 + elif 'high' in priority: + prior = 4 + elif 'dis' in priority: + prior = 5 + + return prior + +def get_event_source(from_src): + '''Translate even str into value''' + choices = ['trigger', 'discovery', 'auto', 'internal'] + rval = 0 + try: + rval = choices.index(from_src) + except ValueError as _: + ZabbixAPIError('Value not found for event source [%s]' % from_src) + + return rval + +def get_status(inc_status): + '''determine status for action''' + rval = 1 + if inc_status == 'enabled': + rval = 0 + + return rval + +def get_condition_operator(inc_operator): + ''' determine the condition operator''' + vals = {'=': 0, + '<>': 1, + 'like': 2, + 'not like': 3, + 'in': 4, + '>=': 5, + '<=': 6, + 'not in': 7, + } + + return vals[inc_operator] + +def get_host_id_by_name(zapi, host_name): + '''Get host id by name''' + content = zapi.get_content('host', + 'get', + {'filter': {'name': host_name}}) + + return content['result'][0]['hostid'] + +def get_trigger_value(inc_trigger): + '''determine the proper trigger value''' + rval = 1 + if inc_trigger == 'PROBLEM': + rval = 1 + else: + rval = 0 + + return rval + +def get_template_id_by_name(zapi, t_name): + '''get the template id by name''' + content = zapi.get_content('template', + 'get', + {'filter': {'host': t_name}}) + + return content['result'][0]['templateid'] + + +def get_host_group_id_by_name(zapi, hg_name): + '''Get hostgroup id by name''' + content = zapi.get_content('hostgroup', + 'get', + {'filter': {'name': hg_name}}) + + return content['result'][0]['groupid'] + +def get_condition_type(event_source, inc_condition): + '''determine the condition type''' + c_types = {} + if event_source == 'trigger': + c_types = {'host group': 0, + 'host': 1, + 'trigger': 2, + 'trigger name': 3, + 'trigger severity': 4, + 'trigger value': 5, + 'time period': 6, + 'host template': 13, + 'application': 15, + 'maintenance status': 16, + } + + elif event_source == 'discovery': + c_types = {'host IP': 7, + 'discovered service type': 8, + 'discovered service port': 9, + 'discovery status': 10, + 'uptime or downtime duration': 11, + 'received value': 12, + 'discovery rule': 18, + 'discovery check': 19, + 'proxy': 20, + 'discovery object': 21, + } + + elif event_source == 'auto': + c_types = {'proxy': 20, + 'host name': 22, + 'host metadata': 24, + } + + elif event_source == 'internal': + c_types = {'host group': 0, + 'host': 1, + 'host template': 13, + 'application': 15, + 'event type': 23, + } + else: + raise ZabbixAPIError('Unkown event source %s' % event_source) + + return c_types[inc_condition] + +def get_operation_type(inc_operation): + ''' determine the correct operation type''' + o_types = {'send message': 0, + 'remote command': 1, + 'add host': 2, + 'remove host': 3, + 'add to host group': 4, + 'remove from host group': 5, + 'link to template': 6, + 'unlink from template': 7, + 'enable host': 8, + 'disable host': 9, + } + + return o_types[inc_operation] + +def get_action_operations(zapi, inc_operations): + '''Convert the operations into syntax for api''' + for operation in inc_operations: + operation['operationtype'] = get_operation_type(operation['operationtype']) + if operation['operationtype'] == 0: # send message. Need to fix the + operation['opmessage']['mediatypeid'] = \ + get_mediatype_id_by_name(zapi, operation['opmessage']['mediatypeid']) + operation['opmessage_grp'] = get_user_groups(zapi, operation.get('opmessage_grp', [])) + operation['opmessage_usr'] = get_users(zapi, operation.get('opmessage_usr', [])) + if operation['opmessage']['default_msg']: + operation['opmessage']['default_msg'] = 1 + else: + operation['opmessage']['default_msg'] = 0 + + # NOT supported for remote commands + elif operation['operationtype'] == 1: + continue + + # Handle Operation conditions: + # Currently there is only 1 available which + # is 'event acknowledged'. In the future + # if there are any added we will need to pass this + # option to a function and return the correct conditiontype + if operation.has_key('opconditions'): + for condition in operation['opconditions']: + if condition['conditiontype'] == 'event acknowledged': + condition['conditiontype'] = 14 + + if condition['operator'] == '=': + condition['operator'] = 0 + + if condition['value'] == 'acknowledged': + condition['operator'] = 1 + else: + condition['operator'] = 0 + + + return inc_operations + +def get_operation_evaltype(inc_type): + '''get the operation evaltype''' + rval = 0 + if inc_type == 'and/or': + rval = 0 + elif inc_type == 'and': + rval = 1 + elif inc_type == 'or': + rval = 2 + elif inc_type == 'custom': + rval = 3 + + return rval + +def get_action_conditions(zapi, event_source, inc_conditions): + '''Convert the conditions into syntax for api''' + + calc_type = inc_conditions.pop('calculation_type') + inc_conditions['evaltype'] = get_operation_evaltype(calc_type) + for cond in inc_conditions['conditions']: + + cond['operator'] = get_condition_operator(cond['operator']) + # Based on conditiontype we need to set the proper value + # e.g. conditiontype = hostgroup then the value needs to be a hostgroup id + # e.g. conditiontype = host the value needs to be a host id + cond['conditiontype'] = get_condition_type(event_source, cond['conditiontype']) + if cond['conditiontype'] == 0: + cond['value'] = get_host_group_id_by_name(zapi, cond['value']) + elif cond['conditiontype'] == 1: + cond['value'] = get_host_id_by_name(zapi, cond['value']) + elif cond['conditiontype'] == 4: + cond['value'] = get_priority(cond['value']) + + elif cond['conditiontype'] == 5: + cond['value'] = get_trigger_value(cond['value']) + elif cond['conditiontype'] == 13: + cond['value'] = get_template_id_by_name(zapi, cond['value']) + elif cond['conditiontype'] == 16: + cond['value'] = '' + + return inc_conditions + + +def get_send_recovery(send_recovery): + '''Get the integer value''' + rval = 0 + if send_recovery: + rval = 1 + + return rval + +# The branches are needed for CRUD and error handling +# pylint: disable=too-many-branches +def main(): + ''' + ansible zabbix module for zbx_item + ''' + + + module = AnsibleModule( + argument_spec=dict( + zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'), + zbx_user=dict(default=os.environ.get('ZABBIX_USER', None), type='str'), + zbx_password=dict(default=os.environ.get('ZABBIX_PASSWORD', None), type='str'), + zbx_debug=dict(default=False, type='bool'), + + name=dict(default=None, type='str'), + event_source=dict(default='trigger', choices=['trigger', 'discovery', 'auto', 'internal'], type='str'), + action_subject=dict(default="{TRIGGER.NAME}: {TRIGGER.STATUS}", type='str'), + action_message=dict(default="{TRIGGER.NAME}: {TRIGGER.STATUS}\r\n" + + "Last value: {ITEM.LASTVALUE}\r\n\r\n{TRIGGER.URL}", type='str'), + reply_subject=dict(default="{TRIGGER.NAME}: {TRIGGER.STATUS}", type='str'), + reply_message=dict(default="Trigger: {TRIGGER.NAME}\r\nTrigger status: {TRIGGER.STATUS}\r\n" + + "Trigger severity: {TRIGGER.SEVERITY}\r\nTrigger URL: {TRIGGER.URL}\r\n\r\n" + + "Item values:\r\n\r\n1. {ITEM.NAME1} ({HOST.NAME1}:{ITEM.KEY1}): " + + "{ITEM.VALUE1}\r\n2. {ITEM.NAME2} ({HOST.NAME2}:{ITEM.KEY2}): " + + "{ITEM.VALUE2}\r\n3. {ITEM.NAME3} ({HOST.NAME3}:{ITEM.KEY3}): " + + "{ITEM.VALUE3}", type='str'), + send_recovery=dict(default=False, type='bool'), + status=dict(default=None, type='str'), + escalation_time=dict(default=60, type='int'), + conditions_filter=dict(default=None, type='dict'), + operations=dict(default=None, type='list'), + state=dict(default='present', type='str'), + ), + #supports_check_mode=True + ) + + zapi = ZabbixAPI(ZabbixConnection(module.params['zbx_server'], + module.params['zbx_user'], + module.params['zbx_password'], + module.params['zbx_debug'])) + + #Set the instance and the template for the rest of the calls + zbx_class_name = 'action' + state = module.params['state'] + + content = zapi.get_content(zbx_class_name, + 'get', + {'search': {'name': module.params['name']}, + 'selectFilter': 'extend', + 'selectOperations': 'extend', + }) + + #******# + # GET + #******# + if state == 'list': + module.exit_json(changed=False, results=content['result'], state="list") + + #******# + # DELETE + #******# + if state == 'absent': + if not exists(content): + module.exit_json(changed=False, state="absent") + + content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0]['itemid']]) + module.exit_json(changed=True, results=content['result'], state="absent") + + # Create and Update + if state == 'present': + + conditions = get_action_conditions(zapi, module.params['event_source'], module.params['conditions_filter']) + operations = get_action_operations(zapi, module.params['operations']) + params = {'name': module.params['name'], + 'esc_period': module.params['escalation_time'], + 'eventsource': get_event_source(module.params['event_source']), + 'status': get_status(module.params['status']), + 'def_shortdata': module.params['action_subject'], + 'def_longdata': module.params['action_message'], + 'r_shortdata': module.params['reply_subject'], + 'r_longdata': module.params['reply_message'], + 'recovery_msg': get_send_recovery(module.params['send_recovery']), + 'filter': conditions, + 'operations': operations, + } + + # Remove any None valued params + _ = [params.pop(key, None) for key in params.keys() if params[key] is None] + + #******# + # CREATE + #******# + if not exists(content): + content = zapi.get_content(zbx_class_name, 'create', params) + + if content.has_key('error'): + module.exit_json(failed=True, changed=True, results=content['error'], state="present") + + module.exit_json(changed=True, results=content['result'], state='present') + + + ######## + # UPDATE + ######## + _ = params.pop('hostid', None) + differences = {} + zab_results = content['result'][0] + for key, value in params.items(): + + if key == 'operations': + ops = operation_differences(zab_results[key], value) + if ops: + differences[key] = ops + + elif key == 'filter': + filters = filter_differences(zab_results[key], value) + if filters: + differences[key] = filters + + elif zab_results[key] != value and zab_results[key] != str(value): + differences[key] = value + + if not differences: + module.exit_json(changed=False, results=zab_results, state="present") + + # We have differences and need to update. + # action update requires an id, filters, and operations + differences['actionid'] = zab_results['actionid'] + differences['operations'] = params['operations'] + differences['filter'] = params['filter'] + content = zapi.get_content(zbx_class_name, 'update', differences) + + if content.has_key('error'): + module.exit_json(failed=True, changed=False, results=content['error'], state="present") + + module.exit_json(changed=True, results=content['result'], state="present") + + module.exit_json(failed=True, + changed=False, + results='Unknown state passed. %s' % state, + state="unknown") + +# pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled +# import module snippets. This are required +from ansible.module_utils.basic import * + +main() -- cgit v1.2.3 From 920fd5c2f6c6f9e588375f644d526e095194a479 Mon Sep 17 00:00:00 2001 From: Kenny Woodson Date: Fri, 25 Sep 2015 15:11:22 -0400 Subject: Updates to zbx_user_media --- roles/lib_zabbix/library/zbx_user_media.py | 53 +++++++++++++++++++++++++----- 1 file changed, 44 insertions(+), 9 deletions(-) (limited to 'roles/lib_zabbix') diff --git a/roles/lib_zabbix/library/zbx_user_media.py b/roles/lib_zabbix/library/zbx_user_media.py index 3f7760475..9ed838f81 100644 --- a/roles/lib_zabbix/library/zbx_user_media.py +++ b/roles/lib_zabbix/library/zbx_user_media.py @@ -54,8 +54,8 @@ def get_mtype(zapi, mtype): except ValueError: pass - content = zapi.get_content('mediatype', 'get', {'search': {'description': mtype}}) - if content.has_key['result'] and content['result']: + content = zapi.get_content('mediatype', 'get', {'filter': {'description': mtype}}) + if content.has_key('result') and content['result']: return content['result'][0]['mediatypeid'] return None @@ -63,7 +63,7 @@ def get_mtype(zapi, mtype): def get_user(zapi, user): ''' Get userids from user aliases ''' - content = zapi.get_content('user', 'get', {'search': {'alias': user}}) + content = zapi.get_content('user', 'get', {'filter': {'alias': user}}) if content['result']: return content['result'][0] @@ -104,15 +104,17 @@ def find_media(medias, user_media): ''' Find the user media in the list of medias ''' for media in medias: - if all([media[key] == user_media[key] for key in user_media.keys()]): + if all([media[key] == str(user_media[key]) for key in user_media.keys()]): return media return None -def get_active(in_active): +def get_active(is_active): '''Determine active value + 0 - enabled + 1 - disabled ''' active = 1 - if in_active: + if is_active: active = 0 return active @@ -128,6 +130,21 @@ def get_mediatype(zapi, mediatype, mediatype_desc): return mtypeid +def preprocess_medias(zapi, medias): + ''' Insert the correct information when processing medias ''' + for media in medias: + # Fetch the mediatypeid from the media desc (name) + if media.has_key('mediatype'): + media['mediatypeid'] = get_mediatype(zapi, mediatype=None, mediatype_desc=media.pop('mediatype')) + + media['active'] = get_active(media.get('active')) + media['severity'] = int(get_severity(media['severity'])) + + return medias + +# Disabling branching as the logic requires branches. +# I've also added a few safeguards which required more branches. +# pylint: disable=too-many-branches def main(): ''' Ansible zabbix module for mediatype @@ -166,11 +183,17 @@ def main(): # User media is fetched through the usermedia.get zbx_user_query = get_zbx_user_query_data(zapi, module.params['login']) - content = zapi.get_content('usermedia', 'get', zbx_user_query) - + content = zapi.get_content('usermedia', 'get', + {'userids': [uid for user, uid in zbx_user_query.items()]}) + ##### + # Get + ##### if state == 'list': module.exit_json(changed=False, results=content['result'], state="list") + ######## + # Delete + ######## if state == 'absent': if not exists(content) or len(content['result']) == 0: module.exit_json(changed=False, state="absent") @@ -178,13 +201,14 @@ def main(): if not module.params['login']: module.exit_json(failed=True, changed=False, results='Must specifiy a user login.', state="absent") - content = zapi.get_content(zbx_class_name, 'deletemedia', [content['result'][0][idname]]) + content = zapi.get_content(zbx_class_name, 'deletemedia', [res[idname] for res in content['result']]) if content.has_key('error'): module.exit_json(changed=False, results=content['error'], state="absent") module.exit_json(changed=True, results=content['result'], state="absent") + # Create and Update if state == 'present': active = get_active(module.params['active']) mtypeid = get_mediatype(zapi, module.params['mediatype'], module.params['mediatype_desc']) @@ -197,13 +221,21 @@ def main(): 'severity': int(get_severity(module.params['severity'])), 'period': module.params['period'], }] + else: + medias = preprocess_medias(zapi, medias) params = {'users': [zbx_user_query], 'medias': medias, 'output': 'extend', } + ######## + # Create + ######## if not exists(content): + if not params['medias']: + module.exit_json(changed=False, results=content['result'], state='present') + # if we didn't find it, create it content = zapi.get_content(zbx_class_name, 'addmedia', params) @@ -216,6 +248,9 @@ def main(): # If user params exists, check to see if they already exist in zabbix # if they exist, then return as no update # elif they do not exist, then take user params only + ######## + # Update + ######## diff = {'medias': [], 'users': {}} _ = [diff['medias'].append(media) for media in params['medias'] if not find_media(content['result'], media)] -- cgit v1.2.3 From 3a15b711e8d47e7365e361534533c28e234e87d3 Mon Sep 17 00:00:00 2001 From: Kenny Woodson Date: Mon, 28 Sep 2015 12:03:43 -0400 Subject: Trigger prototype support --- roles/lib_zabbix/library/zbx_trigger.py | 14 ++ roles/lib_zabbix/library/zbx_triggerprototype.py | 177 +++++++++++++++++++++++ roles/lib_zabbix/tasks/create_template.yml | 15 +- 3 files changed, 205 insertions(+), 1 deletion(-) create mode 100644 roles/lib_zabbix/library/zbx_triggerprototype.py (limited to 'roles/lib_zabbix') diff --git a/roles/lib_zabbix/library/zbx_trigger.py b/roles/lib_zabbix/library/zbx_trigger.py index a05de7e68..8a7b29d07 100644 --- a/roles/lib_zabbix/library/zbx_trigger.py +++ b/roles/lib_zabbix/library/zbx_trigger.py @@ -74,6 +74,18 @@ def get_deps(zapi, deps): return results + +def get_trigger_status(inc_status): + ''' Determine the trigger's status + 0 is enabled + 1 is disabled + ''' + r_status = 0 + if inc_status == 'disabled': + r_status = 1 + + return r_status + def main(): ''' Create a trigger in zabbix @@ -103,6 +115,7 @@ def main(): dependencies=dict(default=[], type='list'), priority=dict(default='avg', type='str'), url=dict(default=None, type='str'), + status=dict(default=None, type='str'), state=dict(default='present', type='str'), ), #supports_check_mode=True @@ -145,6 +158,7 @@ def main(): 'dependencies': get_deps(zapi, module.params['dependencies']), 'priority': get_priority(module.params['priority']), 'url': module.params['url'], + 'status': get_trigger_status(module.params['status']), } # Remove any None valued params diff --git a/roles/lib_zabbix/library/zbx_triggerprototype.py b/roles/lib_zabbix/library/zbx_triggerprototype.py new file mode 100644 index 000000000..c1224b268 --- /dev/null +++ b/roles/lib_zabbix/library/zbx_triggerprototype.py @@ -0,0 +1,177 @@ +#!/usr/bin/env python +''' +ansible module for zabbix triggerprototypes +''' +# vim: expandtab:tabstop=4:shiftwidth=4 +# +# Zabbix triggerprototypes ansible module +# +# +# Copyright 2015 Red Hat Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# This is in place because each module looks similar to each other. +# These need duplicate code as their behavior is very similar +# but different for each zabbix class. +# pylint: disable=duplicate-code + +# pylint: disable=import-error +from openshift_tools.monitoring.zbxapi import ZabbixAPI, ZabbixConnection + +def exists(content, key='result'): + ''' Check if key exists in content or the size of content[key] > 0 + ''' + if not content.has_key(key): + return False + + if not content[key]: + return False + + return True + +def get_priority(priority): + ''' determine priority + ''' + prior = 0 + if 'info' in priority: + prior = 1 + elif 'warn' in priority: + prior = 2 + elif 'avg' == priority or 'ave' in priority: + prior = 3 + elif 'high' in priority: + prior = 4 + elif 'dis' in priority: + prior = 5 + + return prior + +def get_trigger_status(inc_status): + ''' Determine the trigger's status + 0 is enabled + 1 is disabled + ''' + r_status = 0 + if inc_status == 'disabled': + r_status = 1 + + return r_status + + +def main(): + ''' + Create a triggerprototype in zabbix + ''' + + module = AnsibleModule( + argument_spec=dict( + zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'), + zbx_user=dict(default=os.environ.get('ZABBIX_USER', None), type='str'), + zbx_password=dict(default=os.environ.get('ZABBIX_PASSWORD', None), type='str'), + zbx_debug=dict(default=False, type='bool'), + name=dict(default=None, type='str'), + expression=dict(default=None, type='str'), + description=dict(default=None, type='str'), + priority=dict(default='avg', type='str'), + url=dict(default=None, type='str'), + status=dict(default=None, type='str'), + state=dict(default='present', type='str'), + ), + #supports_check_mode=True + ) + + zapi = ZabbixAPI(ZabbixConnection(module.params['zbx_server'], + module.params['zbx_user'], + module.params['zbx_password'], + module.params['zbx_debug'])) + + #Set the instance and the template for the rest of the calls + zbx_class_name = 'triggerprototype' + idname = "triggerid" + state = module.params['state'] + tname = module.params['name'] + + content = zapi.get_content(zbx_class_name, + 'get', + {'filter': {'description': tname}, + 'expandExpression': True, + 'selectDependencies': 'triggerid', + }) + + # Get + if state == 'list': + module.exit_json(changed=False, results=content['result'], state="list") + + # Delete + if state == 'absent': + if not exists(content): + module.exit_json(changed=False, state="absent") + content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0][idname]]) + module.exit_json(changed=True, results=content['result'], state="absent") + + # Create and Update + if state == 'present': + params = {'description': tname, + 'comments': module.params['description'], + 'expression': module.params['expression'], + 'priority': get_priority(module.params['priority']), + 'url': module.params['url'], + 'status': get_trigger_status(module.params['status']), + } + + # Remove any None valued params + _ = [params.pop(key, None) for key in params.keys() if params[key] is None] + + #******# + # CREATE + #******# + if not exists(content): + # if we didn't find it, create it + content = zapi.get_content(zbx_class_name, 'create', params) + + if content.has_key('error'): + module.exit_json(failed=True, changed=True, results=content['error'], state="present") + + module.exit_json(changed=True, results=content['result'], state='present') + + ######## + # UPDATE + ######## + differences = {} + zab_results = content['result'][0] + for key, value in params.items(): + + if zab_results[key] != value and zab_results[key] != str(value): + differences[key] = value + + if not differences: + module.exit_json(changed=False, results=zab_results, state="present") + + # We have differences and need to update + differences[idname] = zab_results[idname] + content = zapi.get_content(zbx_class_name, 'update', differences) + module.exit_json(changed=True, results=content['result'], state="present") + + + module.exit_json(failed=True, + changed=False, + results='Unknown state passed. %s' % state, + state="unknown") + +# pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled +# import module snippets. This are required +from ansible.module_utils.basic import * + +main() diff --git a/roles/lib_zabbix/tasks/create_template.yml b/roles/lib_zabbix/tasks/create_template.yml index b4821bdc7..62259b680 100644 --- a/roles/lib_zabbix/tasks/create_template.yml +++ b/roles/lib_zabbix/tasks/create_template.yml @@ -66,7 +66,7 @@ with_items: template.zdiscoveryrules when: template.zdiscoveryrules is defined -- name: Create Item Prototype +- name: Create Item Prototypes zbx_itemprototype: zbx_server: "{{ server }}" zbx_user: "{{ user }}" @@ -80,3 +80,16 @@ description: "{{ item.description | default('', True) }}" with_items: template.zitemprototypes when: template.zitemprototypes is defined + +- name: Create Trigger Prototypes + zbx_triggerprototype: + zbx_server: "{{ server }}" + zbx_user: "{{ user }}" + zbx_password: "{{ password }}" + name: "{{ item.name }}" + expression: "{{ item.expression }}" + url: "{{ item.url | default('', True) }}" + priority: "{{ item.priority | default('average', True) }}" + description: "{{ item.description | default('', True) }}" + with_items: template.ztriggerprototypes + when: template.ztriggerprototypes is defined -- cgit v1.2.3 From 1cca69d33920681b1040987a4b9681216703d99d Mon Sep 17 00:00:00 2001 From: Kenny Woodson Date: Mon, 28 Sep 2015 14:43:22 -0400 Subject: Added some debug when zbxapi has an issue --- roles/lib_zabbix/library/zbx_trigger.py | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'roles/lib_zabbix') diff --git a/roles/lib_zabbix/library/zbx_trigger.py b/roles/lib_zabbix/library/zbx_trigger.py index 8a7b29d07..21d0fcfd2 100644 --- a/roles/lib_zabbix/library/zbx_trigger.py +++ b/roles/lib_zabbix/library/zbx_trigger.py @@ -170,6 +170,10 @@ def main(): if not exists(content): # if we didn't find it, create it content = zapi.get_content(zbx_class_name, 'create', params) + + if content.has_key('error'): + module.exit_json(failed=True, changed=True, results=content['error'], state="present") + module.exit_json(changed=True, results=content['result'], state='present') ######## -- cgit v1.2.3 From e40b829103db88072c0e5fc759bff239cb214a43 Mon Sep 17 00:00:00 2001 From: Thomas Wiest Date: Wed, 30 Sep 2015 15:22:36 -0400 Subject: added Template Ops Tools --- roles/lib_zabbix/tasks/create_template.yml | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) (limited to 'roles/lib_zabbix') diff --git a/roles/lib_zabbix/tasks/create_template.yml b/roles/lib_zabbix/tasks/create_template.yml index 62259b680..41381e76c 100644 --- a/roles/lib_zabbix/tasks/create_template.yml +++ b/roles/lib_zabbix/tasks/create_template.yml @@ -9,7 +9,8 @@ - set_fact: - lzbx_applications: "{{ template.zitems | oo_select_keys_from_list(['applications']) | oo_flatten | unique }}" + lzbx_item_applications: "{{ template.zitems | default([], True) | oo_select_keys_from_list(['applications']) | oo_flatten | unique }}" + lzbx_itemprototype_applications: "{{ template.zitemprototypes | default([], True) | oo_select_keys_from_list(['applications']) | oo_flatten | unique }}" - name: Create Application zbx_application: @@ -18,9 +19,11 @@ zbx_password: "{{ password }}" name: "{{ item }}" template_name: "{{ template.name }}" - with_items: lzbx_applications + with_items: + - "{{ lzbx_item_applications }}" + - "{{ lzbx_itemprototype_applications }}" register: created_application - when: template.zitems is defined + when: template.zitems is defined or template.zitemprototypes is defined - name: Create Items zbx_item: -- cgit v1.2.3 From aacf1839073ebd40ea0e379abeac5754b0656987 Mon Sep 17 00:00:00 2001 From: Kenny Woodson Date: Wed, 7 Oct 2015 16:56:46 -0400 Subject: Zabbix server template added --- roles/lib_zabbix/library/zbx_trigger.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) (limited to 'roles/lib_zabbix') diff --git a/roles/lib_zabbix/library/zbx_trigger.py b/roles/lib_zabbix/library/zbx_trigger.py index 21d0fcfd2..ab7731faa 100644 --- a/roles/lib_zabbix/library/zbx_trigger.py +++ b/roles/lib_zabbix/library/zbx_trigger.py @@ -86,6 +86,24 @@ def get_trigger_status(inc_status): return r_status +def get_template_id(zapi, template_name): + ''' + get related templates + ''' + template_ids = [] + app_ids = {} + # Fetch templates by name + content = zapi.get_content('template', + 'get', + {'search': {'host': template_name}, + 'selectApplications': ['applicationid', 'name']}) + if content.has_key('result'): + template_ids.append(content['result'][0]['templateid']) + for app in content['result'][0]['applications']: + app_ids[app['name']] = app['applicationid'] + + return template_ids, app_ids + def main(): ''' Create a trigger in zabbix @@ -117,6 +135,7 @@ def main(): url=dict(default=None, type='str'), status=dict(default=None, type='str'), state=dict(default='present', type='str'), + template_name=dict(default=None, type='str'), ), #supports_check_mode=True ) @@ -132,11 +151,16 @@ def main(): state = module.params['state'] tname = module.params['name'] + templateid = None + if module.params['template_name']: + templateid, _ = get_template_id(zapi, module.params['template_name']) + content = zapi.get_content(zbx_class_name, 'get', {'filter': {'description': tname}, 'expandExpression': True, 'selectDependencies': 'triggerid', + 'templateids': templateid, }) # Get -- cgit v1.2.3 From 6b3d70aec80f1cc9b4f9bd14aab062410e3d77ac Mon Sep 17 00:00:00 2001 From: Kenny Woodson Date: Wed, 7 Oct 2015 17:26:26 -0400 Subject: Fixed a bug where applicationids were not being filtered properly --- roles/lib_zabbix/library/zbx_itemprototype.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'roles/lib_zabbix') diff --git a/roles/lib_zabbix/library/zbx_itemprototype.py b/roles/lib_zabbix/library/zbx_itemprototype.py index 4ec1b8e02..e7fd6fa21 100644 --- a/roles/lib_zabbix/library/zbx_itemprototype.py +++ b/roles/lib_zabbix/library/zbx_itemprototype.py @@ -128,12 +128,12 @@ def get_status(status): return _status -def get_app_ids(zapi, application_names): +def get_app_ids(zapi, application_names, templateid): ''' get application ids from names ''' app_ids = [] for app_name in application_names: - content = zapi.get_content('application', 'get', {'search': {'name': app_name}}) + content = zapi.get_content('application', 'get', {'filter': {'name': app_name}, 'templateids': templateid}) if content.has_key('result'): app_ids.append(content['result'][0]['applicationid']) return app_ids @@ -212,7 +212,7 @@ def main(): 'ruleid': get_rule_id(zapi, module.params['discoveryrule_key'], template['templateid']), 'type': get_type(module.params['ztype']), 'value_type': get_value_type(module.params['value_type']), - 'applications': get_app_ids(zapi, module.params['applications']), + 'applications': get_app_ids(zapi, module.params['applications'], template['templateid']), 'description': module.params['description'], } -- cgit v1.2.3 From 365f9c5503f1a9f8d685b91eb1175b7029058e3b Mon Sep 17 00:00:00 2001 From: Kenny Woodson Date: Thu, 8 Oct 2015 14:34:16 -0400 Subject: Fixed user media bug where we would update media when we really wanted to create. --- roles/lib_zabbix/library/zbx_user_media.py | 3 +++ 1 file changed, 3 insertions(+) (limited to 'roles/lib_zabbix') diff --git a/roles/lib_zabbix/library/zbx_user_media.py b/roles/lib_zabbix/library/zbx_user_media.py index 9ed838f81..8895c78c3 100644 --- a/roles/lib_zabbix/library/zbx_user_media.py +++ b/roles/lib_zabbix/library/zbx_user_media.py @@ -260,6 +260,9 @@ def main(): for user in params['users']: diff['users']['userid'] = user['userid'] + # Medias have no real unique key so therefore we need to make it like the incoming user's request + diff['medias'] = medias + # We have differences and need to update content = zapi.get_content(zbx_class_name, 'updatemedia', diff) -- cgit v1.2.3 From e5f0b4944a434a51ae9b460d60a0e00a626158e6 Mon Sep 17 00:00:00 2001 From: Kenny Woodson Date: Thu, 8 Oct 2015 15:18:05 -0400 Subject: Adding zabbix agent template --- roles/lib_zabbix/library/zbx_item.py | 2 ++ 1 file changed, 2 insertions(+) (limited to 'roles/lib_zabbix') diff --git a/roles/lib_zabbix/library/zbx_item.py b/roles/lib_zabbix/library/zbx_item.py index 2ccc21292..6faa82dfc 100644 --- a/roles/lib_zabbix/library/zbx_item.py +++ b/roles/lib_zabbix/library/zbx_item.py @@ -53,6 +53,8 @@ def get_value_type(value_type): vtype = 0 if 'int' in value_type: vtype = 3 + elif 'log' in value_type: + vtype = 2 elif 'char' in value_type: vtype = 1 elif 'str' in value_type: -- cgit v1.2.3 From ba80a2c5b19614c87d2ce0568ed8830c62d40f95 Mon Sep 17 00:00:00 2001 From: Kenny Woodson Date: Tue, 20 Oct 2015 17:00:14 -0400 Subject: Zabbix server stat fixes. enable the proper item types. --- roles/lib_zabbix/library/zbx_item.py | 2 ++ roles/lib_zabbix/tasks/create_template.yml | 2 ++ 2 files changed, 4 insertions(+) (limited to 'roles/lib_zabbix') diff --git a/roles/lib_zabbix/library/zbx_item.py b/roles/lib_zabbix/library/zbx_item.py index 6faa82dfc..caca2df52 100644 --- a/roles/lib_zabbix/library/zbx_item.py +++ b/roles/lib_zabbix/library/zbx_item.py @@ -125,6 +125,7 @@ def main(): template_name=dict(default=None, type='str'), zabbix_type=dict(default=2, type='int'), value_type=dict(default='int', type='str'), + interval=dict(default=60, type='int'), multiplier=dict(default=None, type='str'), description=dict(default=None, type='str'), units=dict(default=None, type='str'), @@ -189,6 +190,7 @@ def main(): 'multiplier': use_multiplier, 'description': module.params['description'], 'units': module.params['units'], + 'delay': module.params['interval'], } # Remove any None valued params diff --git a/roles/lib_zabbix/tasks/create_template.yml b/roles/lib_zabbix/tasks/create_template.yml index 41381e76c..df7888a95 100644 --- a/roles/lib_zabbix/tasks/create_template.yml +++ b/roles/lib_zabbix/tasks/create_template.yml @@ -38,6 +38,8 @@ units: "{{ item.units | default('', True) }}" template_name: "{{ template.name }}" applications: "{{ item.applications }}" + zabbix_type: "{{ item.zabbix_type | default(2, True) }}" + interval: "{{ item.interval | default(60, True) }}" with_items: template.zitems register: created_items when: template.zitems is defined -- cgit v1.2.3 From c16cc8398b4313cdee12a1332a268c8979481ac7 Mon Sep 17 00:00:00 2001 From: Kenny Woodson Date: Tue, 20 Oct 2015 17:31:09 -0400 Subject: Adding delta feature to zbx_item --- roles/lib_zabbix/library/zbx_item.py | 2 ++ roles/lib_zabbix/tasks/create_template.yml | 1 + 2 files changed, 3 insertions(+) (limited to 'roles/lib_zabbix') diff --git a/roles/lib_zabbix/library/zbx_item.py b/roles/lib_zabbix/library/zbx_item.py index caca2df52..2cd00dd27 100644 --- a/roles/lib_zabbix/library/zbx_item.py +++ b/roles/lib_zabbix/library/zbx_item.py @@ -126,6 +126,7 @@ def main(): zabbix_type=dict(default=2, type='int'), value_type=dict(default='int', type='str'), interval=dict(default=60, type='int'), + delta=dict(default=0, type='int'), multiplier=dict(default=None, type='str'), description=dict(default=None, type='str'), units=dict(default=None, type='str'), @@ -191,6 +192,7 @@ def main(): 'description': module.params['description'], 'units': module.params['units'], 'delay': module.params['interval'], + 'delta': module.params['delta'], } # Remove any None valued params diff --git a/roles/lib_zabbix/tasks/create_template.yml b/roles/lib_zabbix/tasks/create_template.yml index df7888a95..d5168a9f4 100644 --- a/roles/lib_zabbix/tasks/create_template.yml +++ b/roles/lib_zabbix/tasks/create_template.yml @@ -40,6 +40,7 @@ applications: "{{ item.applications }}" zabbix_type: "{{ item.zabbix_type | default(2, True) }}" interval: "{{ item.interval | default(60, True) }}" + delta: "{{ item.delta | default(0, True) }}" with_items: template.zitems register: created_items when: template.zitems is defined -- cgit v1.2.3