summaryrefslogtreecommitdiffstats
path: root/roles/lib_zabbix
diff options
context:
space:
mode:
Diffstat (limited to 'roles/lib_zabbix')
-rw-r--r--roles/lib_zabbix/library/zbx_action.py11
-rw-r--r--roles/lib_zabbix/library/zbx_graph.py331
-rw-r--r--roles/lib_zabbix/library/zbx_graphprototype.py331
-rw-r--r--roles/lib_zabbix/library/zbx_httptest.py290
-rw-r--r--roles/lib_zabbix/library/zbx_usergroup.py64
-rw-r--r--roles/lib_zabbix/tasks/create_template.yml24
6 files changed, 1025 insertions, 26 deletions
diff --git a/roles/lib_zabbix/library/zbx_action.py b/roles/lib_zabbix/library/zbx_action.py
index d64cebae1..8bb586c0b 100644
--- a/roles/lib_zabbix/library/zbx_action.py
+++ b/roles/lib_zabbix/library/zbx_action.py
@@ -1,8 +1,8 @@
#!/usr/bin/env python
+# vim: expandtab:tabstop=4:shiftwidth=4
'''
Ansible module for zabbix actions
'''
-# vim: expandtab:tabstop=4:shiftwidth=4
#
# Zabbix action ansible module
#
@@ -89,6 +89,9 @@ def operation_differences(zabbix_ops, user_ops):
for zab, user in zip(zabbix_ops, user_ops):
for key, val in user.items():
if key == 'opconditions':
+ if len(zab[key]) != len(val):
+ rval[key] = val
+ break
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']]):
@@ -330,9 +333,9 @@ def get_action_operations(zapi, inc_operations):
condition['operator'] = 0
if condition['value'] == 'acknowledged':
- condition['operator'] = 1
+ condition['value'] = 1
else:
- condition['operator'] = 0
+ condition['value'] = 0
return inc_operations
@@ -454,7 +457,7 @@ def main():
if not exists(content):
module.exit_json(changed=False, state="absent")
- content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0]['itemid']])
+ content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0]['actionid']])
module.exit_json(changed=True, results=content['result'], state="absent")
# Create and Update
diff --git a/roles/lib_zabbix/library/zbx_graph.py b/roles/lib_zabbix/library/zbx_graph.py
new file mode 100644
index 000000000..121ec3dee
--- /dev/null
+++ b/roles/lib_zabbix/library/zbx_graph.py
@@ -0,0 +1,331 @@
+#!/usr/bin/env python
+'''
+ Ansible module for zabbix graphs
+'''
+# vim: expandtab:tabstop=4:shiftwidth=4
+#
+# Zabbix graphs 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.
+#
+
+#---
+#- hosts: localhost
+# gather_facts: no
+# tasks:
+# - zbx_graph:
+# zbx_server: https://zabbixserver/zabbix/api_jsonrpc.php
+# zbx_user: Admin
+# zbx_password: zabbix
+# name: Test Graph
+# height: 300
+# width: 500
+# graph_items:
+# - item_name: openshift.master.etcd.create.fail
+# color: red
+# line_style: bold
+# - item_name: openshift.master.etcd.create.success
+# color: red
+# line_style: bold
+#
+#
+
+# 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_graph_type(graphtype):
+ '''
+ Possible values:
+ 0 - normal;
+ 1 - stacked;
+ 2 - pie;
+ 3 - exploded;
+ '''
+ gtype = 0
+ if 'stacked' in graphtype:
+ gtype = 1
+ elif 'pie' in graphtype:
+ gtype = 2
+ elif 'exploded' in graphtype:
+ gtype = 3
+
+ return gtype
+
+def get_show_legend(show_legend):
+ '''Get the value for show_legend
+ 0 - hide
+ 1 - (default) show
+ '''
+ rval = 1
+ if 'hide' == show_legend:
+ rval = 0
+
+ return rval
+
+def get_template_id(zapi, template_name):
+ '''
+ get related templates
+ '''
+ # Fetch templates by name
+ content = zapi.get_content('template',
+ 'get',
+ {'filter': {'host': template_name},})
+
+ if content.has_key('result'):
+ return content['result'][0]['templateid']
+
+ return None
+
+def get_color(color_in):
+ ''' Receive a color and translate it to a hex representation of the color
+
+ Will have a few setup by default
+ '''
+ colors = {'black': '000000',
+ 'red': 'FF0000',
+ 'pink': 'FFC0CB',
+ 'purple': '800080',
+ 'orange': 'FFA500',
+ 'gold': 'FFD700',
+ 'yellow': 'FFFF00',
+ 'green': '008000',
+ 'cyan': '00FFFF',
+ 'aqua': '00FFFF',
+ 'blue': '0000FF',
+ 'brown': 'A52A2A',
+ 'gray': '808080',
+ 'grey': '808080',
+ 'silver': 'C0C0C0',
+ }
+ if colors.has_key(color_in):
+ return colors[color_in]
+
+ return color_in
+
+def get_line_style(style):
+ '''determine the line style
+ '''
+ line_style = {'line': 0,
+ 'filled': 1,
+ 'bold': 2,
+ 'dot': 3,
+ 'dashed': 4,
+ 'gradient': 5,
+ }
+
+ if line_style.has_key(style):
+ return line_style[style]
+
+ return 0
+
+def get_calc_function(func):
+ '''Determine the caclulation function'''
+ rval = 2 # default to avg
+ if 'min' in func:
+ rval = 1
+ elif 'max' in func:
+ rval = 4
+ elif 'all' in func:
+ rval = 7
+ elif 'last' in func:
+ rval = 9
+
+ return rval
+
+def get_graph_item_type(gtype):
+ '''Determine the graph item type
+ '''
+ rval = 0 # simple graph type
+ if 'sum' in gtype:
+ rval = 2
+
+ return rval
+
+def get_graph_items(zapi, gitems):
+ '''Get graph items by id'''
+
+ r_items = []
+ for item in gitems:
+ content = zapi.get_content('item',
+ 'get',
+ {'filter': {'name': item['item_name']}})
+ _ = item.pop('item_name')
+ color = get_color(item.pop('color'))
+ drawtype = get_line_style(item.get('line_style', 'line'))
+ func = get_calc_function(item.get('calc_func', 'avg'))
+ g_type = get_graph_item_type(item.get('graph_item_type', 'simple'))
+
+ if content.has_key('result'):
+ tmp = {'itemid': content['result'][0]['itemid'],
+ 'color': color,
+ 'drawtype': drawtype,
+ 'calc_fnc': func,
+ 'type': g_type,
+ }
+ r_items.append(tmp)
+
+ return r_items
+
+def compare_gitems(zabbix_items, user_items):
+ '''Compare zabbix results with the user's supplied items
+ return True if user_items are equal
+ return False if any of the values differ
+ '''
+ if len(zabbix_items) != len(user_items):
+ return False
+
+ for u_item in user_items:
+ for z_item in zabbix_items:
+ if u_item['itemid'] == z_item['itemid']:
+ if not all([str(value) == z_item[key] for key, value in u_item.items()]):
+ return False
+
+ return True
+
+# The branches are needed for CRUD and error handling
+# pylint: disable=too-many-branches
+def main():
+ '''
+ ansible zabbix module for zbx_graphs
+ '''
+
+ 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'),
+ height=dict(default=None, type='int'),
+ width=dict(default=None, type='int'),
+ graph_type=dict(default='normal', type='str'),
+ show_legend=dict(default='show', type='str'),
+ state=dict(default='present', type='str'),
+ graph_items=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 = 'graph'
+ state = module.params['state']
+
+ content = zapi.get_content(zbx_class_name,
+ 'get',
+ {'filter': {'name': module.params['name']},
+ #'templateids': templateid,
+ 'selectGraphItems': '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]['graphid']])
+ module.exit_json(changed=True, results=content['result'], state="absent")
+
+ # Create and Update
+ if state == 'present':
+
+ params = {'name': module.params['name'],
+ 'height': module.params['height'],
+ 'width': module.params['width'],
+ 'graphtype': get_graph_type(module.params['graph_type']),
+ 'show_legend': get_show_legend(module.params['show_legend']),
+ 'gitems': get_graph_items(zapi, module.params['graph_items']),
+ }
+
+ # 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
+ ########
+ differences = {}
+ zab_results = content['result'][0]
+ for key, value in params.items():
+
+ if key == 'gitems':
+ if not compare_gitems(zab_results[key], 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['graphid'] = zab_results['graphid']
+ 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_graphprototype.py b/roles/lib_zabbix/library/zbx_graphprototype.py
new file mode 100644
index 000000000..8287c1e2d
--- /dev/null
+++ b/roles/lib_zabbix/library/zbx_graphprototype.py
@@ -0,0 +1,331 @@
+#!/usr/bin/env python
+'''
+ Ansible module for zabbix graphprototypes
+'''
+# vim: expandtab:tabstop=4:shiftwidth=4
+#
+# Zabbix graphprototypes 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.
+#
+
+#---
+#- hosts: localhost
+# gather_facts: no
+# tasks:
+# - zbx_graphprototype:
+# zbx_server: https://zabbixserver/zabbix/api_jsonrpc.php
+# zbx_user: Admin
+# zbx_password: zabbix
+# name: Test Graph
+# height: 300
+# width: 500
+# graph_items:
+# - item_name: Bytes per second IN on network interface {#OSO_NET_INTERFACE}
+# color: red
+# line_style: bold
+# item_type: prototype
+# - item_name: Template OS Linux: Bytes per second OUT on network interface {#OSO_NET_INTERFACE}
+# item_type: prototype
+#
+#
+
+# 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_graph_type(graphtype):
+ '''
+ Possible values:
+ 0 - normal;
+ 1 - stacked;
+ 2 - pie;
+ 3 - exploded;
+ '''
+ gtype = 0
+ if 'stacked' in graphtype:
+ gtype = 1
+ elif 'pie' in graphtype:
+ gtype = 2
+ elif 'exploded' in graphtype:
+ gtype = 3
+
+ return gtype
+
+def get_show_legend(show_legend):
+ '''Get the value for show_legend
+ 0 - hide
+ 1 - (default) show
+ '''
+ rval = 1
+ if 'hide' == show_legend:
+ rval = 0
+
+ return rval
+
+def get_template_id(zapi, template_name):
+ '''
+ get related templates
+ '''
+ # Fetch templates by name
+ content = zapi.get_content('template',
+ 'get',
+ {'filter': {'host': template_name},})
+
+ if content.has_key('result'):
+ return content['result'][0]['templateid']
+
+ return None
+
+def get_color(color_in='black'):
+ ''' Receive a color and translate it to a hex representation of the color
+
+ Will have a few setup by default
+ '''
+ colors = {'black': '000000',
+ 'red': 'FF0000',
+ 'pink': 'FFC0CB',
+ 'purple': '800080',
+ 'orange': 'FFA500',
+ 'gold': 'FFD700',
+ 'yellow': 'FFFF00',
+ 'green': '008000',
+ 'cyan': '00FFFF',
+ 'aqua': '00FFFF',
+ 'blue': '0000FF',
+ 'brown': 'A52A2A',
+ 'gray': '808080',
+ 'grey': '808080',
+ 'silver': 'C0C0C0',
+ }
+ if colors.has_key(color_in):
+ return colors[color_in]
+
+ return color_in
+
+def get_line_style(style):
+ '''determine the line style
+ '''
+ line_style = {'line': 0,
+ 'filled': 1,
+ 'bold': 2,
+ 'dot': 3,
+ 'dashed': 4,
+ 'gradient': 5,
+ }
+
+ if line_style.has_key(style):
+ return line_style[style]
+
+ return 0
+
+def get_calc_function(func):
+ '''Determine the caclulation function'''
+ rval = 2 # default to avg
+ if 'min' in func:
+ rval = 1
+ elif 'max' in func:
+ rval = 4
+ elif 'all' in func:
+ rval = 7
+ elif 'last' in func:
+ rval = 9
+
+ return rval
+
+def get_graph_item_type(gtype):
+ '''Determine the graph item type
+ '''
+ rval = 0 # simple graph type
+ if 'sum' in gtype:
+ rval = 2
+
+ return rval
+
+def get_graph_items(zapi, gitems):
+ '''Get graph items by id'''
+
+ r_items = []
+ for item in gitems:
+ content = zapi.get_content('item%s' % item.get('item_type', ''),
+ 'get',
+ {'filter': {'name': item['item_name']}})
+ _ = item.pop('item_name')
+ color = get_color(item.pop('color', 'black'))
+ drawtype = get_line_style(item.get('line_style', 'line'))
+ func = get_calc_function(item.get('calc_func', 'avg'))
+ g_type = get_graph_item_type(item.get('graph_item_type', 'simple'))
+
+ if content.has_key('result'):
+ tmp = {'itemid': content['result'][0]['itemid'],
+ 'color': color,
+ 'drawtype': drawtype,
+ 'calc_fnc': func,
+ 'type': g_type,
+ }
+ r_items.append(tmp)
+
+ return r_items
+
+def compare_gitems(zabbix_items, user_items):
+ '''Compare zabbix results with the user's supplied items
+ return True if user_items are equal
+ return False if any of the values differ
+ '''
+ if len(zabbix_items) != len(user_items):
+ return False
+
+ for u_item in user_items:
+ for z_item in zabbix_items:
+ if u_item['itemid'] == z_item['itemid']:
+ if not all([str(value) == z_item[key] for key, value in u_item.items()]):
+ return False
+
+ return True
+
+# The branches are needed for CRUD and error handling
+# pylint: disable=too-many-branches
+def main():
+ '''
+ ansible zabbix module for zbx_graphprototypes
+ '''
+
+ 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'),
+ height=dict(default=None, type='int'),
+ width=dict(default=None, type='int'),
+ graph_type=dict(default='normal', type='str'),
+ show_legend=dict(default='show', type='str'),
+ state=dict(default='present', type='str'),
+ graph_items=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 = 'graphprototype'
+ state = module.params['state']
+
+ content = zapi.get_content(zbx_class_name,
+ 'get',
+ {'filter': {'name': module.params['name']},
+ #'templateids': templateid,
+ 'selectGraphItems': '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]['graphid']])
+ module.exit_json(changed=True, results=content['result'], state="absent")
+
+ # Create and Update
+ if state == 'present':
+
+ params = {'name': module.params['name'],
+ 'height': module.params['height'],
+ 'width': module.params['width'],
+ 'graphtype': get_graph_type(module.params['graph_type']),
+ 'show_legend': get_show_legend(module.params['show_legend']),
+ 'gitems': get_graph_items(zapi, module.params['graph_items']),
+ }
+
+ # 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
+ ########
+ differences = {}
+ zab_results = content['result'][0]
+ for key, value in params.items():
+
+ if key == 'gitems':
+ if not compare_gitems(zab_results[key], 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['graphid'] = zab_results['graphid']
+ 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_httptest.py b/roles/lib_zabbix/library/zbx_httptest.py
new file mode 100644
index 000000000..6b28117ad
--- /dev/null
+++ b/roles/lib_zabbix/library/zbx_httptest.py
@@ -0,0 +1,290 @@
+#!/usr/bin/env python
+'''
+ Ansible module for zabbix httpservice
+'''
+# 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_authentication_method(auth):
+ ''' determine authentication type'''
+ rval = 0
+ if 'basic' in auth:
+ rval = 1
+ elif 'ntlm' in auth:
+ rval = 2
+
+ return rval
+
+def get_verify_host(verify):
+ '''
+ get the values for verify_host
+ '''
+ if verify:
+ return 1
+
+ return 0
+
+def get_app_id(zapi, application):
+ '''
+ get related templates
+ '''
+ # Fetch templates by name
+ content = zapi.get_content('application',
+ 'get',
+ {'search': {'name': application},
+ 'selectApplications': ['applicationid', 'name']})
+ if content.has_key('result'):
+ return content['result'][0]['applicationid']
+
+ return None
+
+def get_template_id(zapi, template_name):
+ '''
+ get related templates
+ '''
+ # Fetch templates by name
+ content = zapi.get_content('template',
+ 'get',
+ {'search': {'host': template_name},
+ 'selectApplications': ['applicationid', 'name']})
+ if content.has_key('result'):
+ return content['result'][0]['templateid']
+
+ return None
+
+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_status(status):
+ ''' Determine the status of the web scenario '''
+ rval = 0
+ if 'disabled' in status:
+ return 1
+
+ return rval
+
+def find_step(idx, step_list):
+ ''' find step by index '''
+ for step in step_list:
+ if str(step['no']) == str(idx):
+ return step
+
+ return None
+
+def steps_equal(zab_steps, user_steps):
+ '''compare steps returned from zabbix
+ and steps passed from user
+ '''
+
+ if len(user_steps) != len(zab_steps):
+ return False
+
+ for idx in range(1, len(user_steps)+1):
+
+ user = find_step(idx, user_steps)
+ zab = find_step(idx, zab_steps)
+
+ for key, value in user.items():
+ if str(value) != str(zab[key]):
+ return False
+
+ return True
+
+def process_steps(steps):
+ '''Preprocess the step parameters'''
+ for idx, step in enumerate(steps):
+ if not step.has_key('no'):
+ step['no'] = idx + 1
+
+ return steps
+
+# 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, require=True, type='str'),
+ agent=dict(default=None, type='str'),
+ template_name=dict(default=None, type='str'),
+ host_name=dict(default=None, type='str'),
+ interval=dict(default=60, type='int'),
+ application=dict(default=None, type='str'),
+ authentication=dict(default=None, type='str'),
+ http_user=dict(default=None, type='str'),
+ http_password=dict(default=None, type='str'),
+ state=dict(default='present', type='str'),
+ status=dict(default='enabled', type='str'),
+ steps=dict(default='present', type='list'),
+ verify_host=dict(default=False, type='bool'),
+ retries=dict(default=1, type='int'),
+ headers=dict(default=None, type='dict'),
+ query_type=dict(default='filter', choices=['filter', 'search'], type='str'),
+ ),
+ #supports_check_mode=True
+ mutually_exclusive=[['template_name', 'host_name']],
+ )
+
+ 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 = 'httptest'
+ state = module.params['state']
+ hostid = None
+
+ # If a template name was passed then accept the template
+ if module.params['template_name']:
+ hostid = get_template_id(zapi, module.params['template_name'])
+ else:
+ hostid = get_host_id_by_name(zapi, module.params['host_name'])
+
+ # Fail if a template was not found matching the name
+ if not hostid:
+ module.exit_json(failed=True,
+ changed=False,
+ results='Error: Could find template or host with name [%s].' %
+ (module.params.get('template_name', module.params['host_name'])),
+ state="Unkown")
+
+ content = zapi.get_content(zbx_class_name,
+ 'get',
+ {module.params['query_type']: {'name': module.params['name']},
+ 'selectSteps': '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]['httptestid']])
+ module.exit_json(changed=True, results=content['result'], state="absent")
+
+ # Create and Update
+ if state == 'present':
+
+ params = {'name': module.params['name'],
+ 'hostid': hostid,
+ 'agent': module.params['agent'],
+ 'retries': module.params['retries'],
+ 'steps': process_steps(module.params['steps']),
+ 'applicationid': get_app_id(zapi, module.params['application']),
+ 'delay': module.params['interval'],
+ 'verify_host': get_verify_host(module.params['verify_host']),
+ 'status': get_status(module.params['status']),
+ 'headers': module.params['headers'],
+ 'http_user': module.params['http_user'],
+ 'http_password': module.params['http_password'],
+ }
+
+
+ # 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
+ ########
+ differences = {}
+ zab_results = content['result'][0]
+ for key, value in params.items():
+
+ if key == 'steps':
+ if not steps_equal(zab_results[key], value):
+ differences[key] = value
+
+ elif zab_results[key] != value and zab_results[key] != str(value):
+ differences[key] = value
+
+ # We have differences and need to update
+ if not differences:
+ module.exit_json(changed=False, results=zab_results, state="present")
+
+ differences['httptestid'] = zab_results['httptestid']
+ 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_usergroup.py b/roles/lib_zabbix/library/zbx_usergroup.py
index 297d8ef91..3fd44d80c 100644
--- a/roles/lib_zabbix/library/zbx_usergroup.py
+++ b/roles/lib_zabbix/library/zbx_usergroup.py
@@ -27,6 +27,10 @@ zabbix ansible module for usergroups
# but different for each zabbix class.
# pylint: disable=duplicate-code
+# Disabling too-many-branches as we need the error checking and the if-statements
+# to determine the proper state
+# pylint: disable=too-many-branches
+
# pylint: disable=import-error
from openshift_tools.monitoring.zbxapi import ZabbixAPI, ZabbixConnection
@@ -92,26 +96,24 @@ def get_user_status(status):
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 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'),
@@ -123,7 +125,7 @@ def main():
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'),
+ users=dict(default=None, type='list'),
state=dict(default='present', type='str'),
),
#supports_check_mode=True
@@ -144,9 +146,15 @@ def main():
{'search': {'name': uname},
'selectUsers': 'userid',
})
+ #******#
+ # 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")
@@ -157,6 +165,7 @@ 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':
params = {'name': uname,
@@ -164,26 +173,37 @@ def main():
'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']),
+ 'userids': get_userids(zapi, module.params['users']),
}
+ # Remove any None valued params
_ = [params.pop(key, None) for key in params.keys() if params[key] == 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():
if key == 'rights':
differences['rights'] = value
- #elif key == 'userids' and zab_results.has_key('users'):
- #if zab_results['users'] != value:
- #differences['userids'] = 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
diff --git a/roles/lib_zabbix/tasks/create_template.yml b/roles/lib_zabbix/tasks/create_template.yml
index 2992505bf..47749389e 100644
--- a/roles/lib_zabbix/tasks/create_template.yml
+++ b/roles/lib_zabbix/tasks/create_template.yml
@@ -105,3 +105,27 @@
description: "{{ item.description | default('', True) }}"
with_items: template.ztriggerprototypes
when: template.ztriggerprototypes is defined
+
+- name: Create Graphs
+ zbx_graph:
+ zbx_server: "{{ server }}"
+ zbx_user: "{{ user }}"
+ zbx_password: "{{ password }}"
+ name: "{{ item.name }}"
+ height: "{{ item.height }}"
+ width: "{{ item.width }}"
+ graph_items: "{{ item.graph_items }}"
+ with_items: template.zgraphs
+ when: template.zgraphs is defined
+
+- name: Create Graph Prototypes
+ zbx_graphprototype:
+ zbx_server: "{{ server }}"
+ zbx_user: "{{ user }}"
+ zbx_password: "{{ password }}"
+ name: "{{ item.name }}"
+ height: "{{ item.height }}"
+ width: "{{ item.width }}"
+ graph_items: "{{ item.graph_items }}"
+ with_items: template.zgraphprototypes
+ when: template.zgraphprototypes is defined