repository_name
stringclasses 316
values | func_path_in_repository
stringlengths 6
223
| func_name
stringlengths 1
134
| language
stringclasses 1
value | func_code_string
stringlengths 57
65.5k
| func_documentation_string
stringlengths 1
46.3k
| split_name
stringclasses 1
value | func_code_url
stringlengths 91
315
| called_functions
listlengths 1
156
⌀ | enclosing_scope
stringlengths 2
1.48M
|
|---|---|---|---|---|---|---|---|---|---|
saltstack/salt
|
salt/modules/zabbix.py
|
_frontend_url
|
python
|
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
|
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L108-L127
| null |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
_query
|
python
|
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
|
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L130-L177
|
[
"def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
_login
|
python
|
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
|
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L180-L240
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _frontend_url():\n '''\n Tries to guess the url of zabbix frontend.\n\n .. versionadded:: 2016.3.0\n '''\n hostname = socket.gethostname()\n frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'\n try:\n try:\n response = salt.utils.http.query(frontend_url)\n error = response['error']\n except HTTPError as http_e:\n error = six.text_type(http_e)\n if error.find('412: Precondition Failed'):\n return frontend_url\n else:\n raise KeyError\n except (ValueError, KeyError):\n return False\n",
"def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
_params_extend
|
python
|
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
|
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L243-L273
| null |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
substitute_params
|
python
|
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
|
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L287-L323
|
[
"def get_object_id_by_params(obj, params=None, **kwargs):\n '''\n .. versionadded:: 2017.7\n\n Get ID of single Zabbix object specified by its name.\n\n :param obj: Zabbix object type\n :param params: Parameters by which object is uniquely identified\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: object ID\n '''\n if params is None:\n params = {}\n res = run_query(obj + '.get', params, **kwargs)\n if res and len(res) == 1:\n return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])\n else:\n raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '\n 'result. Called method {0} with params {1}. '\n 'Result: {2}'.format(obj + '.get', params, res))\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
compare_params
|
python
|
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
|
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L327-L402
| null |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
get_object_id_by_params
|
python
|
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
|
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L405-L427
|
[
"def run_query(method, params, **kwargs):\n '''\n Send Zabbix API call\n\n Args:\n method: actual operation to perform via the API\n params: parameters required for specific method\n\n optional kwargs:\n _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)\n _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)\n _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)\n\n all optional template.get parameters: keyword argument names depends on your zabbix version, see:\n\n https://www.zabbix.com/documentation/2.4/manual/api/reference/\n\n Returns:\n Response from Zabbix API\n\n CLI Example:\n .. code-block:: bash\n\n salt '*' zabbix.run_query proxy.create '{\"host\": \"zabbixproxy.domain.com\", \"status\": \"5\"}'\n '''\n conn_args = _login(**kwargs)\n ret = {}\n try:\n if conn_args:\n method = method\n params = params\n params = _params_extend(params, **kwargs)\n ret = _query(method, params, conn_args['url'], conn_args['auth'])\n if isinstance(ret['result'], bool):\n return ret['result']\n return ret['result'] if ret['result'] else False\n else:\n raise KeyError\n except KeyError:\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
apiinfo_version
|
python
|
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
|
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L430-L458
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
user_create
|
python
|
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
|
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L461-L509
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n",
"def _params_extend(params, _ignore_name=False, **kwargs):\n '''\n Extends the params dictionary by values from keyword arguments.\n\n .. versionadded:: 2016.3.0\n\n :param params: Dictionary with parameters for zabbix API.\n :param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter\n 'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to\n not mess these values.\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: Extended params dictionary with parameters.\n\n '''\n # extend params value by optional zabbix API parameters\n for key in kwargs:\n if not key.startswith('_'):\n params.setdefault(key, kwargs[key])\n\n # ignore name parameter passed from Salt state module, use firstname or visible_name instead\n if _ignore_name:\n params.pop('name', None)\n if 'firstname' in params:\n params['name'] = params.pop('firstname')\n elif 'visible_name' in params:\n params['name'] = params.pop('visible_name')\n\n return params\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
user_delete
|
python
|
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
|
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L512-L545
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
user_exists
|
python
|
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L548-L577
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
user_get
|
python
|
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L580-L617
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n",
"def _params_extend(params, _ignore_name=False, **kwargs):\n '''\n Extends the params dictionary by values from keyword arguments.\n\n .. versionadded:: 2016.3.0\n\n :param params: Dictionary with parameters for zabbix API.\n :param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter\n 'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to\n not mess these values.\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: Extended params dictionary with parameters.\n\n '''\n # extend params value by optional zabbix API parameters\n for key in kwargs:\n if not key.startswith('_'):\n params.setdefault(key, kwargs[key])\n\n # ignore name parameter passed from Salt state module, use firstname or visible_name instead\n if _ignore_name:\n params.pop('name', None)\n if 'firstname' in params:\n params['name'] = params.pop('firstname')\n elif 'visible_name' in params:\n params['name'] = params.pop('visible_name')\n\n return params\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
user_update
|
python
|
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
|
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L620-L656
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n",
"def _params_extend(params, _ignore_name=False, **kwargs):\n '''\n Extends the params dictionary by values from keyword arguments.\n\n .. versionadded:: 2016.3.0\n\n :param params: Dictionary with parameters for zabbix API.\n :param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter\n 'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to\n not mess these values.\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: Extended params dictionary with parameters.\n\n '''\n # extend params value by optional zabbix API parameters\n for key in kwargs:\n if not key.startswith('_'):\n params.setdefault(key, kwargs[key])\n\n # ignore name parameter passed from Salt state module, use firstname or visible_name instead\n if _ignore_name:\n params.pop('name', None)\n if 'firstname' in params:\n params['name'] = params.pop('firstname')\n elif 'visible_name' in params:\n params['name'] = params.pop('visible_name')\n\n return params\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
user_getmedia
|
python
|
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
|
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L659-L699
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n",
"def _params_extend(params, _ignore_name=False, **kwargs):\n '''\n Extends the params dictionary by values from keyword arguments.\n\n .. versionadded:: 2016.3.0\n\n :param params: Dictionary with parameters for zabbix API.\n :param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter\n 'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to\n not mess these values.\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: Extended params dictionary with parameters.\n\n '''\n # extend params value by optional zabbix API parameters\n for key in kwargs:\n if not key.startswith('_'):\n params.setdefault(key, kwargs[key])\n\n # ignore name parameter passed from Salt state module, use firstname or visible_name instead\n if _ignore_name:\n params.pop('name', None)\n if 'firstname' in params:\n params['name'] = params.pop('firstname')\n elif 'visible_name' in params:\n params['name'] = params.pop('visible_name')\n\n return params\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
user_addmedia
|
python
|
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
|
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L702-L747
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
user_deletemedia
|
python
|
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
|
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L750-L782
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
usergroup_delete
|
python
|
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
|
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L855-L885
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
usergroup_exists
|
python
|
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
|
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L888-L940
|
[
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n",
"def apiinfo_version(**kwargs):\n '''\n Retrieve the version of the Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success string with Zabbix API version, False on failure.\n\n CLI Example:\n .. code-block:: bash\n\n salt '*' zabbix.apiinfo_version\n '''\n conn_args = _login(**kwargs)\n ret = {}\n try:\n if conn_args:\n method = 'apiinfo.version'\n params = {}\n ret = _query(method, params, conn_args['url'], conn_args['auth'])\n return ret['result']\n else:\n raise KeyError\n except KeyError:\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
usergroup_get
|
python
|
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
|
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L943-L995
|
[
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n",
"def apiinfo_version(**kwargs):\n '''\n Retrieve the version of the Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success string with Zabbix API version, False on failure.\n\n CLI Example:\n .. code-block:: bash\n\n salt '*' zabbix.apiinfo_version\n '''\n conn_args = _login(**kwargs)\n ret = {}\n try:\n if conn_args:\n method = 'apiinfo.version'\n params = {}\n ret = _query(method, params, conn_args['url'], conn_args['auth'])\n return ret['result']\n else:\n raise KeyError\n except KeyError:\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
usergroup_update
|
python
|
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
|
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L998-L1034
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n",
"def _params_extend(params, _ignore_name=False, **kwargs):\n '''\n Extends the params dictionary by values from keyword arguments.\n\n .. versionadded:: 2016.3.0\n\n :param params: Dictionary with parameters for zabbix API.\n :param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter\n 'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to\n not mess these values.\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: Extended params dictionary with parameters.\n\n '''\n # extend params value by optional zabbix API parameters\n for key in kwargs:\n if not key.startswith('_'):\n params.setdefault(key, kwargs[key])\n\n # ignore name parameter passed from Salt state module, use firstname or visible_name instead\n if _ignore_name:\n params.pop('name', None)\n if 'firstname' in params:\n params['name'] = params.pop('firstname')\n elif 'visible_name' in params:\n params['name'] = params.pop('visible_name')\n\n return params\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
usergroup_list
|
python
|
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
|
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L1037-L1065
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
host_create
|
python
|
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
|
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L1068-L1123
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n",
"def _params_extend(params, _ignore_name=False, **kwargs):\n '''\n Extends the params dictionary by values from keyword arguments.\n\n .. versionadded:: 2016.3.0\n\n :param params: Dictionary with parameters for zabbix API.\n :param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter\n 'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to\n not mess these values.\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: Extended params dictionary with parameters.\n\n '''\n # extend params value by optional zabbix API parameters\n for key in kwargs:\n if not key.startswith('_'):\n params.setdefault(key, kwargs[key])\n\n # ignore name parameter passed from Salt state module, use firstname or visible_name instead\n if _ignore_name:\n params.pop('name', None)\n if 'firstname' in params:\n params['name'] = params.pop('firstname')\n elif 'visible_name' in params:\n params['name'] = params.pop('visible_name')\n\n return params\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
host_delete
|
python
|
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
|
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L1126-L1158
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
host_exists
|
python
|
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
|
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L1161-L1223
|
[
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n",
"def apiinfo_version(**kwargs):\n '''\n Retrieve the version of the Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success string with Zabbix API version, False on failure.\n\n CLI Example:\n .. code-block:: bash\n\n salt '*' zabbix.apiinfo_version\n '''\n conn_args = _login(**kwargs)\n ret = {}\n try:\n if conn_args:\n method = 'apiinfo.version'\n params = {}\n ret = _query(method, params, conn_args['url'], conn_args['auth'])\n return ret['result']\n else:\n raise KeyError\n except KeyError:\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
host_get
|
python
|
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L1226-L1273
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n",
"def _params_extend(params, _ignore_name=False, **kwargs):\n '''\n Extends the params dictionary by values from keyword arguments.\n\n .. versionadded:: 2016.3.0\n\n :param params: Dictionary with parameters for zabbix API.\n :param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter\n 'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to\n not mess these values.\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: Extended params dictionary with parameters.\n\n '''\n # extend params value by optional zabbix API parameters\n for key in kwargs:\n if not key.startswith('_'):\n params.setdefault(key, kwargs[key])\n\n # ignore name parameter passed from Salt state module, use firstname or visible_name instead\n if _ignore_name:\n params.pop('name', None)\n if 'firstname' in params:\n params['name'] = params.pop('firstname')\n elif 'visible_name' in params:\n params['name'] = params.pop('visible_name')\n\n return params\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
host_update
|
python
|
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
|
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L1276-L1318
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n",
"def _params_extend(params, _ignore_name=False, **kwargs):\n '''\n Extends the params dictionary by values from keyword arguments.\n\n .. versionadded:: 2016.3.0\n\n :param params: Dictionary with parameters for zabbix API.\n :param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter\n 'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to\n not mess these values.\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: Extended params dictionary with parameters.\n\n '''\n # extend params value by optional zabbix API parameters\n for key in kwargs:\n if not key.startswith('_'):\n params.setdefault(key, kwargs[key])\n\n # ignore name parameter passed from Salt state module, use firstname or visible_name instead\n if _ignore_name:\n params.pop('name', None)\n if 'firstname' in params:\n params['name'] = params.pop('firstname')\n elif 'visible_name' in params:\n params['name'] = params.pop('visible_name')\n\n return params\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
host_inventory_get
|
python
|
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
|
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L1321-L1354
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n",
"def _params_extend(params, _ignore_name=False, **kwargs):\n '''\n Extends the params dictionary by values from keyword arguments.\n\n .. versionadded:: 2016.3.0\n\n :param params: Dictionary with parameters for zabbix API.\n :param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter\n 'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to\n not mess these values.\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: Extended params dictionary with parameters.\n\n '''\n # extend params value by optional zabbix API parameters\n for key in kwargs:\n if not key.startswith('_'):\n params.setdefault(key, kwargs[key])\n\n # ignore name parameter passed from Salt state module, use firstname or visible_name instead\n if _ignore_name:\n params.pop('name', None)\n if 'firstname' in params:\n params['name'] = params.pop('firstname')\n elif 'visible_name' in params:\n params['name'] = params.pop('visible_name')\n\n return params\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
host_inventory_set
|
python
|
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
|
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L1357-L1409
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n",
"def _params_extend(params, _ignore_name=False, **kwargs):\n '''\n Extends the params dictionary by values from keyword arguments.\n\n .. versionadded:: 2016.3.0\n\n :param params: Dictionary with parameters for zabbix API.\n :param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter\n 'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to\n not mess these values.\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: Extended params dictionary with parameters.\n\n '''\n # extend params value by optional zabbix API parameters\n for key in kwargs:\n if not key.startswith('_'):\n params.setdefault(key, kwargs[key])\n\n # ignore name parameter passed from Salt state module, use firstname or visible_name instead\n if _ignore_name:\n params.pop('name', None)\n if 'firstname' in params:\n params['name'] = params.pop('firstname')\n elif 'visible_name' in params:\n params['name'] = params.pop('visible_name')\n\n return params\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
hostgroup_create
|
python
|
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
|
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L1443-L1479
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n",
"def _params_extend(params, _ignore_name=False, **kwargs):\n '''\n Extends the params dictionary by values from keyword arguments.\n\n .. versionadded:: 2016.3.0\n\n :param params: Dictionary with parameters for zabbix API.\n :param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter\n 'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to\n not mess these values.\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: Extended params dictionary with parameters.\n\n '''\n # extend params value by optional zabbix API parameters\n for key in kwargs:\n if not key.startswith('_'):\n params.setdefault(key, kwargs[key])\n\n # ignore name parameter passed from Salt state module, use firstname or visible_name instead\n if _ignore_name:\n params.pop('name', None)\n if 'firstname' in params:\n params['name'] = params.pop('firstname')\n elif 'visible_name' in params:\n params['name'] = params.pop('visible_name')\n\n return params\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
hostgroup_delete
|
python
|
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
|
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L1482-L1514
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
hostgroup_exists
|
python
|
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
|
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L1517-L1574
|
[
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n",
"def apiinfo_version(**kwargs):\n '''\n Retrieve the version of the Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success string with Zabbix API version, False on failure.\n\n CLI Example:\n .. code-block:: bash\n\n salt '*' zabbix.apiinfo_version\n '''\n conn_args = _login(**kwargs)\n ret = {}\n try:\n if conn_args:\n method = 'apiinfo.version'\n params = {}\n ret = _query(method, params, conn_args['url'], conn_args['auth'])\n return ret['result']\n else:\n raise KeyError\n except KeyError:\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
hostgroup_get
|
python
|
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L1577-L1627
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n",
"def _params_extend(params, _ignore_name=False, **kwargs):\n '''\n Extends the params dictionary by values from keyword arguments.\n\n .. versionadded:: 2016.3.0\n\n :param params: Dictionary with parameters for zabbix API.\n :param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter\n 'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to\n not mess these values.\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: Extended params dictionary with parameters.\n\n '''\n # extend params value by optional zabbix API parameters\n for key in kwargs:\n if not key.startswith('_'):\n params.setdefault(key, kwargs[key])\n\n # ignore name parameter passed from Salt state module, use firstname or visible_name instead\n if _ignore_name:\n params.pop('name', None)\n if 'firstname' in params:\n params['name'] = params.pop('firstname')\n elif 'visible_name' in params:\n params['name'] = params.pop('visible_name')\n\n return params\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
hostgroup_update
|
python
|
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
|
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L1630-L1669
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n",
"def _params_extend(params, _ignore_name=False, **kwargs):\n '''\n Extends the params dictionary by values from keyword arguments.\n\n .. versionadded:: 2016.3.0\n\n :param params: Dictionary with parameters for zabbix API.\n :param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter\n 'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to\n not mess these values.\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: Extended params dictionary with parameters.\n\n '''\n # extend params value by optional zabbix API parameters\n for key in kwargs:\n if not key.startswith('_'):\n params.setdefault(key, kwargs[key])\n\n # ignore name parameter passed from Salt state module, use firstname or visible_name instead\n if _ignore_name:\n params.pop('name', None)\n if 'firstname' in params:\n params['name'] = params.pop('firstname')\n elif 'visible_name' in params:\n params['name'] = params.pop('visible_name')\n\n return params\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
hostinterface_create
|
python
|
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
|
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L1748-L1814
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n",
"def _params_extend(params, _ignore_name=False, **kwargs):\n '''\n Extends the params dictionary by values from keyword arguments.\n\n .. versionadded:: 2016.3.0\n\n :param params: Dictionary with parameters for zabbix API.\n :param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter\n 'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to\n not mess these values.\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: Extended params dictionary with parameters.\n\n '''\n # extend params value by optional zabbix API parameters\n for key in kwargs:\n if not key.startswith('_'):\n params.setdefault(key, kwargs[key])\n\n # ignore name parameter passed from Salt state module, use firstname or visible_name instead\n if _ignore_name:\n params.pop('name', None)\n if 'firstname' in params:\n params['name'] = params.pop('firstname')\n elif 'visible_name' in params:\n params['name'] = params.pop('visible_name')\n\n return params\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
hostinterface_delete
|
python
|
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
|
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L1817-L1849
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
hostinterface_update
|
python
|
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
|
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L1852-L1891
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n",
"def _params_extend(params, _ignore_name=False, **kwargs):\n '''\n Extends the params dictionary by values from keyword arguments.\n\n .. versionadded:: 2016.3.0\n\n :param params: Dictionary with parameters for zabbix API.\n :param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter\n 'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to\n not mess these values.\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: Extended params dictionary with parameters.\n\n '''\n # extend params value by optional zabbix API parameters\n for key in kwargs:\n if not key.startswith('_'):\n params.setdefault(key, kwargs[key])\n\n # ignore name parameter passed from Salt state module, use firstname or visible_name instead\n if _ignore_name:\n params.pop('name', None)\n if 'firstname' in params:\n params['name'] = params.pop('firstname')\n elif 'visible_name' in params:\n params['name'] = params.pop('visible_name')\n\n return params\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
usermacro_get
|
python
|
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L1894-L1951
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n",
"def _params_extend(params, _ignore_name=False, **kwargs):\n '''\n Extends the params dictionary by values from keyword arguments.\n\n .. versionadded:: 2016.3.0\n\n :param params: Dictionary with parameters for zabbix API.\n :param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter\n 'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to\n not mess these values.\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: Extended params dictionary with parameters.\n\n '''\n # extend params value by optional zabbix API parameters\n for key in kwargs:\n if not key.startswith('_'):\n params.setdefault(key, kwargs[key])\n\n # ignore name parameter passed from Salt state module, use firstname or visible_name instead\n if _ignore_name:\n params.pop('name', None)\n if 'firstname' in params:\n params['name'] = params.pop('firstname')\n elif 'visible_name' in params:\n params['name'] = params.pop('visible_name')\n\n return params\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
usermacro_create
|
python
|
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
|
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L1954-L1994
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n",
"def _params_extend(params, _ignore_name=False, **kwargs):\n '''\n Extends the params dictionary by values from keyword arguments.\n\n .. versionadded:: 2016.3.0\n\n :param params: Dictionary with parameters for zabbix API.\n :param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter\n 'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to\n not mess these values.\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: Extended params dictionary with parameters.\n\n '''\n # extend params value by optional zabbix API parameters\n for key in kwargs:\n if not key.startswith('_'):\n params.setdefault(key, kwargs[key])\n\n # ignore name parameter passed from Salt state module, use firstname or visible_name instead\n if _ignore_name:\n params.pop('name', None)\n if 'firstname' in params:\n params['name'] = params.pop('firstname')\n elif 'visible_name' in params:\n params['name'] = params.pop('visible_name')\n\n return params\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
usermacro_delete
|
python
|
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
|
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L2038-L2070
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
usermacro_update
|
python
|
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
|
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L2108-L2140
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n",
"def _params_extend(params, _ignore_name=False, **kwargs):\n '''\n Extends the params dictionary by values from keyword arguments.\n\n .. versionadded:: 2016.3.0\n\n :param params: Dictionary with parameters for zabbix API.\n :param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter\n 'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to\n not mess these values.\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: Extended params dictionary with parameters.\n\n '''\n # extend params value by optional zabbix API parameters\n for key in kwargs:\n if not key.startswith('_'):\n params.setdefault(key, kwargs[key])\n\n # ignore name parameter passed from Salt state module, use firstname or visible_name instead\n if _ignore_name:\n params.pop('name', None)\n if 'firstname' in params:\n params['name'] = params.pop('firstname')\n elif 'visible_name' in params:\n params['name'] = params.pop('visible_name')\n\n return params\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
usermacro_updateglobal
|
python
|
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
|
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L2143-L2175
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n",
"def _params_extend(params, _ignore_name=False, **kwargs):\n '''\n Extends the params dictionary by values from keyword arguments.\n\n .. versionadded:: 2016.3.0\n\n :param params: Dictionary with parameters for zabbix API.\n :param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter\n 'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to\n not mess these values.\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: Extended params dictionary with parameters.\n\n '''\n # extend params value by optional zabbix API parameters\n for key in kwargs:\n if not key.startswith('_'):\n params.setdefault(key, kwargs[key])\n\n # ignore name parameter passed from Salt state module, use firstname or visible_name instead\n if _ignore_name:\n params.pop('name', None)\n if 'firstname' in params:\n params['name'] = params.pop('firstname')\n elif 'visible_name' in params:\n params['name'] = params.pop('visible_name')\n\n return params\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
mediatype_get
|
python
|
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L2178-L2220
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n",
"def _params_extend(params, _ignore_name=False, **kwargs):\n '''\n Extends the params dictionary by values from keyword arguments.\n\n .. versionadded:: 2016.3.0\n\n :param params: Dictionary with parameters for zabbix API.\n :param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter\n 'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to\n not mess these values.\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: Extended params dictionary with parameters.\n\n '''\n # extend params value by optional zabbix API parameters\n for key in kwargs:\n if not key.startswith('_'):\n params.setdefault(key, kwargs[key])\n\n # ignore name parameter passed from Salt state module, use firstname or visible_name instead\n if _ignore_name:\n params.pop('name', None)\n if 'firstname' in params:\n params['name'] = params.pop('firstname')\n elif 'visible_name' in params:\n params['name'] = params.pop('visible_name')\n\n return params\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
mediatype_create
|
python
|
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
|
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L2223-L2268
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n",
"def _params_extend(params, _ignore_name=False, **kwargs):\n '''\n Extends the params dictionary by values from keyword arguments.\n\n .. versionadded:: 2016.3.0\n\n :param params: Dictionary with parameters for zabbix API.\n :param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter\n 'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to\n not mess these values.\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: Extended params dictionary with parameters.\n\n '''\n # extend params value by optional zabbix API parameters\n for key in kwargs:\n if not key.startswith('_'):\n params.setdefault(key, kwargs[key])\n\n # ignore name parameter passed from Salt state module, use firstname or visible_name instead\n if _ignore_name:\n params.pop('name', None)\n if 'firstname' in params:\n params['name'] = params.pop('firstname')\n elif 'visible_name' in params:\n params['name'] = params.pop('visible_name')\n\n return params\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
mediatype_delete
|
python
|
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
|
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L2271-L2302
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
mediatype_update
|
python
|
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
|
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L2305-L2343
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n",
"def _params_extend(params, _ignore_name=False, **kwargs):\n '''\n Extends the params dictionary by values from keyword arguments.\n\n .. versionadded:: 2016.3.0\n\n :param params: Dictionary with parameters for zabbix API.\n :param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter\n 'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to\n not mess these values.\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: Extended params dictionary with parameters.\n\n '''\n # extend params value by optional zabbix API parameters\n for key in kwargs:\n if not key.startswith('_'):\n params.setdefault(key, kwargs[key])\n\n # ignore name parameter passed from Salt state module, use firstname or visible_name instead\n if _ignore_name:\n params.pop('name', None)\n if 'firstname' in params:\n params['name'] = params.pop('firstname')\n elif 'visible_name' in params:\n params['name'] = params.pop('visible_name')\n\n return params\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
template_get
|
python
|
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L2346-L2391
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n",
"def _params_extend(params, _ignore_name=False, **kwargs):\n '''\n Extends the params dictionary by values from keyword arguments.\n\n .. versionadded:: 2016.3.0\n\n :param params: Dictionary with parameters for zabbix API.\n :param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter\n 'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to\n not mess these values.\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: Extended params dictionary with parameters.\n\n '''\n # extend params value by optional zabbix API parameters\n for key in kwargs:\n if not key.startswith('_'):\n params.setdefault(key, kwargs[key])\n\n # ignore name parameter passed from Salt state module, use firstname or visible_name instead\n if _ignore_name:\n params.pop('name', None)\n if 'firstname' in params:\n params['name'] = params.pop('firstname')\n elif 'visible_name' in params:\n params['name'] = params.pop('visible_name')\n\n return params\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
run_query
|
python
|
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L2394-L2433
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n",
"def _params_extend(params, _ignore_name=False, **kwargs):\n '''\n Extends the params dictionary by values from keyword arguments.\n\n .. versionadded:: 2016.3.0\n\n :param params: Dictionary with parameters for zabbix API.\n :param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter\n 'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to\n not mess these values.\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: Extended params dictionary with parameters.\n\n '''\n # extend params value by optional zabbix API parameters\n for key in kwargs:\n if not key.startswith('_'):\n params.setdefault(key, kwargs[key])\n\n # ignore name parameter passed from Salt state module, use firstname or visible_name instead\n if _ignore_name:\n params.pop('name', None)\n if 'firstname' in params:\n params['name'] = params.pop('firstname')\n elif 'visible_name' in params:\n params['name'] = params.pop('visible_name')\n\n return params\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
configuration_import
|
python
|
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
|
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L2436-L2505
|
[
"def mkstemp(*args, **kwargs):\n '''\n Helper function which does exactly what ``tempfile.mkstemp()`` does but\n accepts another argument, ``close_fd``, which, by default, is true and closes\n the fd before returning the file path. Something commonly done throughout\n Salt's code.\n '''\n if 'prefix' not in kwargs:\n kwargs['prefix'] = '__salt.tmp.'\n close_fd = kwargs.pop('close_fd', True)\n fd_, f_path = tempfile.mkstemp(*args, **kwargs)\n if close_fd is False:\n return fd_, f_path\n os.close(fd_)\n del fd_\n return f_path\n",
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def safe_rm(tgt):\n '''\n Safely remove a file\n '''\n try:\n os.remove(tgt)\n except (IOError, OSError):\n pass\n",
"def run_query(method, params, **kwargs):\n '''\n Send Zabbix API call\n\n Args:\n method: actual operation to perform via the API\n params: parameters required for specific method\n\n optional kwargs:\n _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)\n _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)\n _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)\n\n all optional template.get parameters: keyword argument names depends on your zabbix version, see:\n\n https://www.zabbix.com/documentation/2.4/manual/api/reference/\n\n Returns:\n Response from Zabbix API\n\n CLI Example:\n .. code-block:: bash\n\n salt '*' zabbix.run_query proxy.create '{\"host\": \"zabbixproxy.domain.com\", \"status\": \"5\"}'\n '''\n conn_args = _login(**kwargs)\n ret = {}\n try:\n if conn_args:\n method = method\n params = params\n params = _params_extend(params, **kwargs)\n ret = _query(method, params, conn_args['url'], conn_args['auth'])\n if isinstance(ret['result'], bool):\n return ret['result']\n return ret['result'] if ret['result'] else False\n else:\n raise KeyError\n except KeyError:\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
triggerid_get
|
python
|
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
|
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L2508-L2554
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n",
"def _params_extend(params, _ignore_name=False, **kwargs):\n '''\n Extends the params dictionary by values from keyword arguments.\n\n .. versionadded:: 2016.3.0\n\n :param params: Dictionary with parameters for zabbix API.\n :param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter\n 'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to\n not mess these values.\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: Extended params dictionary with parameters.\n\n '''\n # extend params value by optional zabbix API parameters\n for key in kwargs:\n if not key.startswith('_'):\n params.setdefault(key, kwargs[key])\n\n # ignore name parameter passed from Salt state module, use firstname or visible_name instead\n if _ignore_name:\n params.pop('name', None)\n if 'firstname' in params:\n params['name'] = params.pop('firstname')\n elif 'visible_name' in params:\n params['name'] = params.pop('visible_name')\n\n return params\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
service_add
|
python
|
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L2557-L2603
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n",
"def _params_extend(params, _ignore_name=False, **kwargs):\n '''\n Extends the params dictionary by values from keyword arguments.\n\n .. versionadded:: 2016.3.0\n\n :param params: Dictionary with parameters for zabbix API.\n :param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter\n 'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to\n not mess these values.\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: Extended params dictionary with parameters.\n\n '''\n # extend params value by optional zabbix API parameters\n for key in kwargs:\n if not key.startswith('_'):\n params.setdefault(key, kwargs[key])\n\n # ignore name parameter passed from Salt state module, use firstname or visible_name instead\n if _ignore_name:\n params.pop('name', None)\n if 'firstname' in params:\n params['name'] = params.pop('firstname')\n elif 'visible_name' in params:\n params['name'] = params.pop('visible_name')\n\n return params\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
service_get
|
python
|
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L2606-L2647
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n",
"def _params_extend(params, _ignore_name=False, **kwargs):\n '''\n Extends the params dictionary by values from keyword arguments.\n\n .. versionadded:: 2016.3.0\n\n :param params: Dictionary with parameters for zabbix API.\n :param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter\n 'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to\n not mess these values.\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: Extended params dictionary with parameters.\n\n '''\n # extend params value by optional zabbix API parameters\n for key in kwargs:\n if not key.startswith('_'):\n params.setdefault(key, kwargs[key])\n\n # ignore name parameter passed from Salt state module, use firstname or visible_name instead\n if _ignore_name:\n params.pop('name', None)\n if 'firstname' in params:\n params['name'] = params.pop('firstname')\n elif 'visible_name' in params:\n params['name'] = params.pop('visible_name')\n\n return params\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/modules/zabbix.py
|
service_delete
|
python
|
def service_delete(service_id=None, **kwargs):
'''
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.delete'
if not service_id:
return {'result': False, 'comment': 'service_id param is required'}
params = [str(service_id)]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
.. versionadded:: Fluorine
Delete service specified by id.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/delete
:param service_id: ID of service which should be deleted
.. note::
Service can't be deleted if it has any children.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted service, False if service could not be deleted or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_delete 10
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L2650-L2689
|
[
"def _query(method, params, url, auth=None):\n '''\n JSON request to Zabbix API.\n\n .. versionadded:: 2016.3.0\n\n :param method: actual operation to perform via the API\n :param params: parameters required for specific method\n :param url: url of zabbix api\n :param auth: auth token for zabbix api (only for methods with required authentication)\n\n :return: Response from API with desired data in JSON format. In case of error returns more specific description.\n\n .. versionchanged:: 2017.7\n '''\n\n unauthenticated_methods = ['user.login', 'apiinfo.version', ]\n\n header_dict = {'Content-type': 'application/json'}\n data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}\n\n if method not in unauthenticated_methods:\n data['auth'] = auth\n\n data = salt.utils.json.dumps(data)\n\n log.info('_QUERY input:\\nurl: %s\\ndata: %s', six.text_type(url), six.text_type(data))\n\n try:\n result = salt.utils.http.query(url,\n method='POST',\n data=data,\n header_dict=header_dict,\n decode_type='json',\n decode=True,\n status=True,\n headers=True)\n log.info('_QUERY result: %s', six.text_type(result))\n if 'error' in result:\n raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))\n ret = result.get('dict', {})\n if 'error' in ret:\n raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))\n return ret\n except ValueError as err:\n raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))\n except socket.error as err:\n raise SaltException('Check hostname in URL! ({})'.format(err))\n",
"def _login(**kwargs):\n '''\n Log in to the API and generate the authentication token.\n\n .. versionadded:: 2016.3.0\n\n :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n :return: On success connargs dictionary with auth token and frontend url, False on failure.\n\n '''\n connargs = dict()\n\n def _connarg(name, key=None):\n '''\n Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__\n\n Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).\n\n Inspired by mysql salt module.\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n else:\n prefix = '_connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('zabbix.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n _connarg('_connection_user', 'user')\n _connarg('_connection_password', 'password')\n _connarg('_connection_url', 'url')\n\n if 'url' not in connargs:\n connargs['url'] = _frontend_url()\n\n try:\n if connargs['user'] and connargs['password'] and connargs['url']:\n params = {'user': connargs['user'], 'password': connargs['password']}\n method = 'user.login'\n ret = _query(method, params, connargs['url'])\n auth = ret['result']\n connargs['auth'] = auth\n connargs.pop('user', None)\n connargs.pop('password', None)\n return connargs\n else:\n raise KeyError\n except KeyError as err:\n raise SaltException('URL is probably not correct! ({})'.format(err))\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Zabbix
:optdepends: - zabbix server
:configuration: This module is not usable until the zabbix user and zabbix password are specified either in a pillar
or in the minion's config file. Zabbix url should be also specified.
.. code-block:: yaml
zabbix.user: Admin
zabbix.password: mypassword
zabbix.url: http://127.0.0.1/zabbix/api_jsonrpc.php
Connection arguments from the minion config file can be overridden on the CLI by using arguments with
``_connection_`` prefix.
.. code-block:: bash
zabbix.apiinfo_version _connection_user=Admin _connection_password=zabbix _connection_url=http://host/zabbix/
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import socket
import os
# Import Salt libs
from salt.ext import six
from salt.exceptions import SaltException
import salt.utils.data
import salt.utils.files
import salt.utils.http
import salt.utils.json
from salt.utils.versions import LooseVersion as _LooseVersion
# pylint: disable=import-error,no-name-in-module,unused-import
from salt.ext.six.moves.urllib.error import HTTPError, URLError
# pylint: enable=import-error,no-name-in-module,unused-import
log = logging.getLogger(__name__)
INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345]
ZABBIX_TOP_LEVEL_OBJECTS = ('hostgroup', 'template', 'host', 'maintenance', 'action', 'drule', 'service', 'proxy',
'screen', 'usergroup', 'mediatype', 'script', 'valuemap')
# Zabbix object and its ID name mapping
ZABBIX_ID_MAPPER = {
'action': 'actionid',
'alert': 'alertid',
'application': 'applicationid',
'dhost': 'dhostid',
'dservice': 'dserviceid',
'dcheck': 'dcheckid',
'drule': 'druleid',
'event': 'eventid',
'graph': 'graphid',
'graphitem': 'gitemid',
'graphprototype': 'graphid',
'history': 'itemid',
'host': 'hostid',
'hostgroup': 'groupid',
'hostinterface': 'interfaceid',
'hostprototype': 'hostid',
'iconmap': 'iconmapid',
'image': 'imageid',
'item': 'itemid',
'itemprototype': 'itemid',
'service': 'serviceid',
'discoveryrule': 'itemid',
'maintenance': 'maintenanceid',
'map': 'sysmapid',
'usermedia': 'mediaid',
'mediatype': 'mediatypeid',
'proxy': 'proxyid',
'screen': 'screenid',
'screenitem': 'screenitemid',
'script': 'scriptid',
'template': 'templateid',
'templatescreen': 'screenid',
'templatescreenitem': 'screenitemid',
'trend': 'itemid',
'trigger': 'triggerid',
'triggerprototype': 'triggerid',
'user': 'userid',
'usergroup': 'usrgrpid',
'usermacro': 'globalmacroid',
'valuemap': 'valuemapid',
'httptest': 'httptestid'
}
# Define the module's virtual name
__virtualname__ = 'zabbix'
def __virtual__():
'''
Only load the module if all modules are imported correctly.
'''
return __virtualname__
def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error = response['error']
except HTTPError as http_e:
error = six.text_type(http_e)
if error.find('412: Precondition Failed'):
return frontend_url
else:
raise KeyError
except (ValueError, KeyError):
return False
def _query(method, params, url, auth=None):
'''
JSON request to Zabbix API.
.. versionadded:: 2016.3.0
:param method: actual operation to perform via the API
:param params: parameters required for specific method
:param url: url of zabbix api
:param auth: auth token for zabbix api (only for methods with required authentication)
:return: Response from API with desired data in JSON format. In case of error returns more specific description.
.. versionchanged:: 2017.7
'''
unauthenticated_methods = ['user.login', 'apiinfo.version', ]
header_dict = {'Content-type': 'application/json'}
data = {'jsonrpc': '2.0', 'id': 0, 'method': method, 'params': params}
if method not in unauthenticated_methods:
data['auth'] = auth
data = salt.utils.json.dumps(data)
log.info('_QUERY input:\nurl: %s\ndata: %s', six.text_type(url), six.text_type(data))
try:
result = salt.utils.http.query(url,
method='POST',
data=data,
header_dict=header_dict,
decode_type='json',
decode=True,
status=True,
headers=True)
log.info('_QUERY result: %s', six.text_type(result))
if 'error' in result:
raise SaltException('Zabbix API: Status: {0} ({1})'.format(result['status'], result['error']))
ret = result.get('dict', {})
if 'error' in ret:
raise SaltException('Zabbix API: {} ({})'.format(ret['error']['message'], ret['error']['data']))
return ret
except ValueError as err:
raise SaltException('URL or HTTP headers are probably not correct! ({})'.format(err))
except socket.error as err:
raise SaltException('Check hostname in URL! ({})'.format(err))
def _login(**kwargs):
'''
Log in to the API and generate the authentication token.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success connargs dictionary with auth token and frontend url, False on failure.
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__
Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.).
Inspired by mysql salt module.
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = '_connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('zabbix.{0}'.format(name), None)
if val is not None:
connargs[key] = val
_connarg('_connection_user', 'user')
_connarg('_connection_password', 'password')
_connarg('_connection_url', 'url')
if 'url' not in connargs:
connargs['url'] = _frontend_url()
try:
if connargs['user'] and connargs['password'] and connargs['url']:
params = {'user': connargs['user'], 'password': connargs['password']}
method = 'user.login'
ret = _query(method, params, connargs['url'])
auth = ret['result']
connargs['auth'] = auth
connargs.pop('user', None)
connargs.pop('password', None)
return connargs
else:
raise KeyError
except KeyError as err:
raise SaltException('URL is probably not correct! ({})'.format(err))
def _params_extend(params, _ignore_name=False, **kwargs):
'''
Extends the params dictionary by values from keyword arguments.
.. versionadded:: 2016.3.0
:param params: Dictionary with parameters for zabbix API.
:param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter
'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to
not mess these values.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Extended params dictionary with parameters.
'''
# extend params value by optional zabbix API parameters
for key in kwargs:
if not key.startswith('_'):
params.setdefault(key, kwargs[key])
# ignore name parameter passed from Salt state module, use firstname or visible_name instead
if _ignore_name:
params.pop('name', None)
if 'firstname' in params:
params['name'] = params.pop('firstname')
elif 'visible_name' in params:
params['name'] = params.pop('visible_name')
return params
def get_zabbix_id_mapper():
'''
.. versionadded:: 2017.7
Make ZABBIX_ID_MAPPER constant available to state modules.
:return: ZABBIX_ID_MAPPER
'''
return ZABBIX_ID_MAPPER
def substitute_params(input_object, extend_params=None, filter_key='name', **kwargs):
'''
.. versionadded:: 2017.7
Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back
as a value. Definition of the object is done via dict with keys "query_object" and "query_name".
:param input_object: Zabbix object type specified in state file
:param extend_params: Specify query with params
:param filter_key: Custom filtering key (default: name)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Params structure with values converted to string for further comparison purposes
'''
if extend_params is None:
extend_params = {}
if isinstance(input_object, list):
return [substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object]
elif isinstance(input_object, dict):
if 'query_object' in input_object:
query_params = {}
if input_object['query_object'] not in ZABBIX_TOP_LEVEL_OBJECTS:
query_params.update(extend_params)
try:
query_params.update({'filter': {filter_key: input_object['query_name']}})
return get_object_id_by_params(input_object['query_object'], query_params, **kwargs)
except KeyError:
raise SaltException('Qyerying object ID requested '
'but object name not provided: {0}'.format(input_object))
else:
return {key: substitute_params(val, extend_params, filter_key, **kwargs)
for key, val in input_object.items()}
else:
# Zabbix response is always str, return everything in str as well
return six.text_type(input_object)
# pylint: disable=too-many-return-statements,too-many-nested-blocks
def compare_params(defined, existing, return_old_value=False):
'''
.. versionadded:: 2017.7
Compares Zabbix object definition against existing Zabbix object.
:param defined: Zabbix object definition taken from sls file.
:param existing: Existing Zabbix object taken from result of an API call.
:param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose.
:return: Params that are different from existing object. Result extended by
object ID can be passed directly to Zabbix API update method.
'''
# Comparison of data types
if not isinstance(defined, type(existing)):
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
# Comparison of values
if not salt.utils.data.is_iter(defined):
if six.text_type(defined) != six.text_type(existing) and return_old_value:
return {'new': six.text_type(defined), 'old': six.text_type(existing)}
elif six.text_type(defined) != six.text_type(existing) and not return_old_value:
return six.text_type(defined)
# Comparison of lists of values or lists of dicts
if isinstance(defined, list):
if len(defined) != len(existing):
log.info('Different list length!')
return {'new': defined, 'old': existing} if return_old_value else defined
else:
difflist = []
for ditem in defined:
d_in_e = []
for eitem in existing:
comp = compare_params(ditem, eitem, return_old_value)
if return_old_value:
d_in_e.append(comp['new'])
else:
d_in_e.append(comp)
if all(d_in_e):
difflist.append(ditem)
# If there is any difference in a list then whole defined list must be returned and provided for update
if any(difflist) and return_old_value:
return {'new': defined, 'old': existing}
elif any(difflist) and not return_old_value:
return defined
# Comparison of dicts
if isinstance(defined, dict):
try:
# defined must be a subset of existing to be compared
if set(defined) <= set(existing):
intersection = set(defined) & set(existing)
diffdict = {'new': {}, 'old': {}} if return_old_value else {}
for i in intersection:
comp = compare_params(defined[i], existing[i], return_old_value)
if return_old_value:
if comp or (not comp and isinstance(comp, list)):
diffdict['new'].update({i: defined[i]})
diffdict['old'].update({i: existing[i]})
else:
if comp or (not comp and isinstance(comp, list)):
diffdict.update({i: defined[i]})
return diffdict
return {'new': defined, 'old': existing} if return_old_value else defined
except TypeError:
raise SaltException('Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. '
'Existing value: "{2}", defined value: "{3}").'.format(type(existing),
type(defined),
existing,
defined))
def get_object_id_by_params(obj, params=None, **kwargs):
'''
.. versionadded:: 2017.7
Get ID of single Zabbix object specified by its name.
:param obj: Zabbix object type
:param params: Parameters by which object is uniquely identified
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: object ID
'''
if params is None:
params = {}
res = run_query(obj + '.get', params, **kwargs)
if res and len(res) == 1:
return six.text_type(res[0][ZABBIX_ID_MAPPER[obj]])
else:
raise SaltException('Zabbix API: Object does not exist or bad Zabbix user permissions or other unexpected '
'result. Called method {0} with params {1}. '
'Result: {2}'.format(obj + '.get', params, res))
def apiinfo_version(**kwargs):
'''
Retrieve the version of the Zabbix API.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success string with Zabbix API version, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.apiinfo_version
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'apiinfo.version'
params = {}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return False
def user_create(alias, passwd, usrgrps, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new zabbix user
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param alias: user alias
:param passwd: user's password
:param usrgrps: user groups to add the user to
:param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
:param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess
with value supplied from Salt sls file.
:return: On success string with id of the created user.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.create'
params = {"alias": alias, "passwd": passwd, "usrgrps": []}
# User groups
if not isinstance(usrgrps, list):
usrgrps = [usrgrps]
for usrgrp in usrgrps:
params['usrgrps'].append({"usrgrpid": usrgrp})
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_delete(users, **kwargs):
'''
Delete zabbix users.
.. versionadded:: 2016.3.0
:param users: array of users (userids) to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: On success array with userids of deleted users.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_delete 15
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.delete'
if not isinstance(users, list):
params = [users]
else:
params = users
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_exists(alias, **kwargs):
'''
Checks if user with given alias exists.
.. versionadded:: 2016.3.0
:param alias: user alias
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if user exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_exists james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {"alias": alias}}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return True if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_get(alias=None, userids=None, **kwargs):
'''
Retrieve users according to the given parameters.
.. versionadded:: 2016.3.0
:param alias: user alias
:param userids: return only users with the given IDs
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details of convenient users, False on failure of if no user found.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_get james
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend", "filter": {}}
if not userids and not alias:
return {'result': False, 'comment': 'Please submit alias or userids parameter to retrieve users.'}
if alias:
params['filter'].setdefault('alias', alias)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def user_update(userid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing users
.. note::
This function accepts all standard user properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user
:param userid: id of the user to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Id of the updated user on success.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_update 16 visible_name='James Brown'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.update'
params = {"userid": userid, }
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['userids']
else:
raise KeyError
except KeyError:
return ret
def user_getmedia(userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve media according to the given parameters
.. note::
This function accepts all standard usermedia.get properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get
:param userids: return only media that are used by the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: List of retrieved media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_getmedia
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermedia.get'
if userids:
params = {"userids": userids}
else:
params = {}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):
'''
Add new media to multiple users.
.. versionadded:: 2016.3.0
:param userids: ID of the user that uses the media
:param active: Whether the media is enabled (0 enabled, 1 disabled)
:param mediatypeid: ID of the media type used by the media
:param period: Time when the notifications can be sent as a time period
:param sendto: Address, user name or other identifier of the recipient
:param severity: Trigger severities to send notifications about
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created media.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'
severity=63
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.addmedia'
params = {"users": []}
# Users
if not isinstance(userids, list):
userids = [userids]
for user in userids:
params['users'].append({"userid": user})
# Medias
params['medias'] = [{"active": active, "mediatypeid": mediatypeid, "period": period,
"sendto": sendto, "severity": severity}, ]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_deletemedia(mediaids, **kwargs):
'''
Delete media by id.
.. versionadded:: 2016.3.0
:param mediaids: IDs of the media to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted media, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_deletemedia 27
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.deletemedia'
if not isinstance(mediaids, list):
mediaids = [mediaids]
params = mediaids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediaids']
else:
raise KeyError
except KeyError:
return ret
def user_list(**kwargs):
'''
Retrieve all of the configured users.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with user details.
CLI Example:
.. code-block:: bash
salt '*' zabbix.user_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'user.get'
params = {"output": "extend"}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the created user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_create GroupName
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_delete(usergroupids, **kwargs):
'''
.. versionadded:: 2016.3.0
:param usergroupids: IDs of the user groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted user groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_delete 28
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.delete'
if not isinstance(usergroupids, list):
usergroupids = [usergroupids]
params = usergroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one user group that matches the given filter criteria exists
.. versionadded:: 2016.3.0
:param name: names of the user groups
:param node: name of the node the user groups must belong to (This will override the nodeids parameter.)
:param nodeids: IDs of the nodes the user groups must belong to
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one user group that matches the given filter criteria exists, else False.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_exists Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# usergroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not name:
name = ''
ret = usergroup_get(name, None, **kwargs)
return bool(ret)
# zabbix 2.4 and earlier
else:
method = 'usergroup.exists'
params = {}
if not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '
'at least one user group exists.'}
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get
:param name: names of the user groups
:param usrgrpids: return only user groups with the given IDs
:param userids: return only user groups that contain the given users
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient user groups details, False if no user group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_get Guests
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
# Versions above 2.4 allow retrieving user group permissions
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
params = {"selectRights": "extend", "output": "extend", "filter": {}}
else:
params = {"output": "extend", "filter": {}}
if not name and not usrgrpids and not userids:
return False
if name:
params['filter'].setdefault('name', name)
if usrgrpids:
params.setdefault('usrgrpids', usrgrpids)
if userids:
params.setdefault('userids', userids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return False if not ret['result'] else ret['result']
else:
raise KeyError
except KeyError:
return ret
def usergroup_update(usrgrpid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing user group
.. note::
This function accepts all standard user group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group
:param usrgrpid: ID of the user group to update.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated user group, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name=guestsRenamed
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.update'
params = {"usrgrpid": usrgrpid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['usrgrpids']
else:
raise KeyError
except KeyError:
return ret
def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with enabled user groups details, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usergroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
return: ID of the created host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_create technicalname 4
interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}'
visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.create'
params = {"host": host}
# Groups
if not isinstance(groups, list):
groups = [groups]
grps = []
for group in groups:
grps.append({"groupid": group})
params['groups'] = grps
# Interfaces
if not isinstance(interfaces, list):
interfaces = [interfaces]
params['interfaces'] = interfaces
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_delete(hostids, **kwargs):
'''
Delete hosts.
.. versionadded:: 2016.3.0
:param hostids: Hosts (hostids) to delete.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_delete 10106
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.delete'
if not isinstance(hostids, list):
params = [hostids]
else:
params = hostids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
:param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the deleted hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_exists 'Zabbix server'
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not host:
host = None
if not name:
name = None
if not hostid:
hostid = None
ret = host_get(host, name, hostid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
method = 'host.exists'
params = {}
if hostid:
params['hostid'] = hostid
if host:
params['host'] = host
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not hostid and not host and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit hostid, host, name, node or nodeids parameter to'
'check if at least one host that matches the given filter '
'criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_get(host=None, name=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve hosts according to the given parameters
.. note::
This function accepts all optional host.get parameters: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get
:param host: technical name of the host
:param name: visible name of the host
:param hostids: ids of the hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with convenient hosts details, False if no host found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_get 'Zabbix server'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", "filter": {}}
if not name and not hostids and not host:
return False
if name:
params['filter'].setdefault('name', name)
if hostids:
params.setdefault('hostids', hostids)
if host:
params['filter'].setdefault('host', host)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def host_update(hostid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts
.. note::
This function accepts all standard host and host.update properties:
keyword argument names differ depending on your zabbix version, see the
documentation for `host objects`_ and the documentation for `updating
hosts`_.
.. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update
:param hostid: ID of the host to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: string with visible name of the host, use
'visible_name' instead of 'name' parameter to not mess with value
supplied from Salt sls file.
:return: ID of the updated host.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_update 10084 name='Zabbix server2'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.update'
params = {"hostid": hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostids']
else:
raise KeyError
except KeyError:
return ret
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"selectInventory": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'][0]['inventory'] if ret['result'][0]['inventory'] else False
else:
raise KeyError
except KeyError:
return ret
def host_inventory_set(hostid, **kwargs):
'''
Update host inventory items
NOTE: This function accepts all standard host: keyword argument names for inventory
see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostid: ID of the host to update
:param clear_old: Set to True in order to remove all existing inventory items before setting the specified items
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
clear_old = False
method = 'host.update'
if kwargs.get('clear_old'):
clear_old = True
kwargs.pop('clear_old', None)
inventory_params = dict(_params_extend(params, **kwargs))
for key in inventory_params:
params.pop(key, None)
if hostid:
params.setdefault('hostid', hostid)
if clear_old:
# Set inventory to disabled in order to clear existing data
params["inventory_mode"] = "-1"
ret = _query(method, params, conn_args['url'], conn_args['auth'])
# Set inventory mode to manual in order to submit inventory data
params['inventory_mode'] = "0"
params['inventory'] = inventory_params
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def host_list(**kwargs):
'''
Retrieve all hosts.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about hosts, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.host_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'host.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_create(name, **kwargs):
'''
.. versionadded:: 2016.3.0
Create a host group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the created host group.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_create MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.create'
params = {"name": name}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_delete(hostgroupids, **kwargs):
'''
Delete the host group.
.. versionadded:: 2016.3.0
:param hostgroupids: IDs of the host groups to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the deleted host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_delete 23
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.delete'
if not isinstance(hostgroupids, list):
params = [hostgroupids]
else:
params = hostgroupids
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_exists(name=None, groupid=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host group that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to (zabbix API < 2.4)
:param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: True if at least one host group exists, False if not or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_exists MyNewGroup
'''
conn_args = _login(**kwargs)
zabbix_version = apiinfo_version(**kwargs)
ret = {}
try:
if conn_args:
# hostgroup.exists deprecated
if _LooseVersion(zabbix_version) > _LooseVersion("2.5"):
if not groupid:
groupid = None
if not name:
name = None
ret = hostgroup_get(name, groupid, **kwargs)
return bool(ret)
# zabbix 2.4 nad earlier
else:
params = {}
method = 'hostgroup.exists'
if groupid:
params['groupid'] = groupid
if name:
params['name'] = name
# deprecated in 2.4
if _LooseVersion(zabbix_version) < _LooseVersion("2.4"):
if node:
params['node'] = node
if nodeids:
params['nodeids'] = nodeids
if not groupid and not name and not node and not nodeids:
return {'result': False, 'comment': 'Please submit groupid, name, node or nodeids parameter to'
'check if at least one host group that matches the given filter'
' criteria exists.'}
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostgroup.get properities: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get
:param name: names of the host groups
:param groupid: host group IDs
:param node: name of the node the host groups must belong to
:param nodeids: IDs of the nodes the host groups must belong to
:param hostids: return only host groups that contain the given hosts
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host groups details, False if no convenient host group found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_get MyNewGroup
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend"}
if not groupids and not name and not hostids:
return False
if name:
name_dict = {"name": name}
params.setdefault('filter', name_dict)
if groupids:
params.setdefault('groupids', groupids)
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostgroup_update(groupid, name=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Update existing hosts group
.. note::
This function accepts all standard host group properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group
:param groupid: ID of the host group to update
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of updated host groups.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_update 24 name='Renamed Name'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.update'
params = {"groupid": groupid}
if name:
params['name'] = name
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['groupids']
else:
raise KeyError
except KeyError:
return ret
def hostgroup_list(**kwargs):
'''
Retrieve all host groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with details about host groups, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostgroup_list
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostgroup.get'
params = {"output": "extend", }
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_get(hostids, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve host groups according to the given parameters
.. note::
This function accepts all standard hostinterface.get properities:
keyword argument names differ depending on your zabbix version, see
here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_get 101054
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.get'
params = {"output": "extend"}
if hostids:
params.setdefault('hostids', hostids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host interface
.. note::
This function accepts all standard host group interface: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object
:param hostid: ID of the host the interface belongs to
:param ip_: IP address used by the interface
:param dns: DNS name used by the interface
:param main: whether the interface is used as default on the host (0 - not default, 1 - default)
:param port: port number used by the interface
:param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX)
:param useip: Whether the connection should be made via IP (0 - connect
using host DNS name; 1 - connect using host IP address for this host
interface)
:param _connection_user: Optional - zabbix user (can also be set in opts or
pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in
opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set
in opts, pillar, see module's docstring)
:return: ID of the created host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_create 10105 192.193.194.197
'''
conn_args = _login(**kwargs)
ret = {}
if not port:
port = INTERFACE_DEFAULT_PORTS[if_type]
try:
if conn_args:
method = 'hostinterface.create'
params = {"hostid": hostid,
"ip": ip_,
"dns": dns,
"main": main,
"port": port,
"type": if_type,
"useip": useip}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_delete(interfaceids, **kwargs):
'''
Delete host interface
.. versionadded:: 2016.3.0
:param interfaceids: IDs of the host interfaces to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted host interfaces, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_delete 50
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.delete'
if isinstance(interfaceids, list):
params = interfaceids
else:
params = [interfaceids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def hostinterface_update(interfaceid, **kwargs):
'''
.. versionadded:: 2016.3.0
Update host interface
.. note::
This function accepts all standard hostinterface: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface
:param interfaceid: ID of the hostinterface to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of the updated host interface, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'hostinterface.update'
params = {"interfaceid": interfaceid}
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['interfaceids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True)
globalmacro: if True, returns only global macros
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
Returns:
Array with usermacro details, False if no usermacro found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {"output": "extend", "filter": {}}
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['filter'].setdefault('macro', macro)
if hostids:
params.setdefault('hostids', hostids)
elif templateids:
params.setdefault('templateids', hostids)
if hostmacroids:
params.setdefault('hostmacroids', hostmacroids)
elif globalmacroids:
globalmacro = True
params.setdefault('globalmacroids', globalmacroids)
if globalmacro:
params = _params_extend(params, globalmacro=True)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def usermacro_create(macro, value, hostid, **kwargs):
'''
Create new host usermacro.
:param macro: name of the host usermacro
:param value: value of the host usermacro
:param hostid: hostid or templateid
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.create'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params['hostid'] = hostid
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_createglobal(macro, value, **kwargs):
'''
Create new global usermacro.
:param macro: name of the global usermacro
:param value: value of the global usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.createglobal'
if macro:
# Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict
if isinstance(macro, dict):
macro = "{" + six.text_type(macro.keys()[0]) +"}"
if not macro.startswith('{') and not macro.endswith('}'):
macro = "{" + macro + "}"
params['macro'] = macro
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_delete 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.delete'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_deleteglobal(macroids, **kwargs):
'''
Delete global usermacros.
:param macroids: macroids of the global usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: IDs of the deleted global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_deleteglobal 21
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.deleteglobal'
if isinstance(macroids, list):
params = macroids
else:
params = [macroids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids']
else:
raise KeyError
except KeyError:
return ret
def usermacro_update(hostmacroid, value, **kwargs):
'''
Update existing host usermacro.
:param hostmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update host usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_update 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.update'
params['hostmacroid'] = hostmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['hostmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the update global usermacro.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usermacro_updateglobal 1 'public'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
params = {}
method = 'usermacro.updateglobal'
params['globalmacroid'] = globalmacroid
params['value'] = value
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['globalmacroids'][0]
else:
raise KeyError
except KeyError:
return ret
def mediatype_get(name=None, mediatypeids=None, **kwargs):
'''
Retrieve mediatypes according to the given parameters.
Args:
name: Name or description of the mediatype
mediatypeids: ids of the mediatypes
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get
Returns:
Array with mediatype details, False if no mediatype found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_get name='Email'
salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('description', name)
if mediatypeids:
params.setdefault('mediatypeids', mediatypeids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def mediatype_create(name, mediatype, **kwargs):
'''
Create new mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting
:param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs
:param gsm_modem: exec path - Required for sms type, see Zabbix API docs
:param smtp_email: email address from which notifications will be sent, required for email type
:param smtp_helo: SMTP HELO, required for email type
:param smtp_server: SMTP server, required for email type
:param status: whether the media type is enabled - 0: enabled, 1: disabled
:param username: authentication user, required for Jabber and Ez Texting types
:param passwd: authentication password, required for Jabber and Ez Texting types
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
return: ID of the created mediatype.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'
smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.create'
params = {"description": name}
params['type'] = mediatype
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeid']
else:
raise KeyError
except KeyError:
return ret
def mediatype_delete(mediatypeids, **kwargs):
'''
Delete mediatype
:param interfaceids: IDs of the mediatypes to delete
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: ID of deleted mediatype, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.mediatype_delete 3
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.delete'
if isinstance(mediatypeids, list):
params = mediatypeids
else:
params = [mediatypeids]
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def mediatype_update(mediatypeid, name=False, mediatype=False, **kwargs):
'''
Update existing mediatype
.. note::
This function accepts all standard mediatype properties: keyword
argument names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object
:param mediatypeid: ID of the mediatype to update
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: IDs of the updated mediatypes, False on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.usergroup_update 8 name="Email update"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'mediatype.update'
params = {"mediatypeid": mediatypeid}
if name:
params['description'] = name
if mediatype:
params['type'] = mediatype
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result']['mediatypeids']
else:
raise KeyError
except KeyError:
return ret
def template_get(name=None, host=None, templateids=None, **kwargs):
'''
Retrieve templates according to the given parameters.
Args:
host: technical name of the template
name: visible name of the template
hostids: ids of the templates
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get
Returns:
Array with convenient template details, False if no template found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.template_get name='Template OS Linux'
salt '*' zabbix.template_get templateids="['10050', '10001']"
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'template.get'
params = {"output": "extend", "filter": {}}
if name:
params['filter'].setdefault('name', name)
if host:
params['filter'].setdefault('host', host)
if templateids:
params.setdefault('templateids', templateids)
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def run_query(method, params, **kwargs):
'''
Send Zabbix API call
Args:
method: actual operation to perform via the API
params: parameters required for specific method
optional kwargs:
_connection_user: zabbix user (can also be set in opts or pillar, see module's docstring)
_connection_password: zabbix password (can also be set in opts or pillar, see module's docstring)
_connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring)
all optional template.get parameters: keyword argument names depends on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/
Returns:
Response from Zabbix API
CLI Example:
.. code-block:: bash
salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}'
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = method
params = params
params = _params_extend(params, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if isinstance(ret['result'], bool):
return ret['result']
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.)
:param file_format: Config file format (default: xml)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
CLI Example:
.. code-block:: bash
salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \
"{'screens': {'createMissing': True, 'updateExisting': True}}"
'''
if rules is None:
rules = {}
default_rules = {'applications': {'createMissing': True, 'updateExisting': False, 'deleteMissing': False},
'discoveryRules': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'graphs': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'groups': {'createMissing': True},
'hosts': {'createMissing': False, 'updateExisting': False},
'images': {'createMissing': False, 'updateExisting': False},
'items': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'maps': {'createMissing': False, 'updateExisting': False},
'screens': {'createMissing': False, 'updateExisting': False},
'templateLinkage': {'createMissing': True},
'templates': {'createMissing': True, 'updateExisting': True},
'templateScreens': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'triggers': {'createMissing': True, 'updateExisting': True, 'deleteMissing': False},
'valueMaps': {'createMissing': True, 'updateExisting': False}}
new_rules = dict(default_rules)
if rules:
for rule in rules:
if rule in new_rules:
new_rules[rule].update(rules[rule])
else:
new_rules[rule] = rules[rule]
if 'salt://' in config_file:
tmpfile = salt.utils.files.mkstemp()
cfile = __salt__['cp.get_file'](config_file, tmpfile)
if not cfile or os.path.getsize(cfile) == 0:
return {'name': config_file, 'result': False, 'message': 'Failed to fetch config file.'}
else:
cfile = config_file
if not os.path.isfile(cfile):
return {'name': config_file, 'result': False, 'message': 'Invalid file path.'}
with salt.utils.files.fopen(cfile, mode='r') as fp_:
xml = fp_.read()
if 'salt://' in config_file:
salt.utils.files.safe_rm(cfile)
params = {'format': file_format,
'rules': new_rules,
'source': xml}
log.info('CONFIGURATION IMPORT: rules: %s', six.text_type(params['rules']))
try:
run_query('configuration.import', params, **kwargs)
return {'name': config_file, 'result': True, 'message': 'Zabbix API "configuration.import" method '
'called successfully.'}
except SaltException as exc:
return {'name': config_file, 'result': False, 'message': six.text_type(exc)}
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
'''
.. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger (trigger name) whose we want to find
:param priority: Priority of trigger (useful if we have same name for more triggers with different priorities)
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.triggerid_get 1111 'trigger name to find' 5
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'trigger.get'
if not hostid or not trigger_desc:
return {'result': False, 'comment': 'hostid and trigger_desc params are required'}
params = {'output': ['triggerid', 'description'],
'filter': {'priority': priority}, 'hostids': hostid}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
if ret['result']:
for r in ret['result']:
if trigger_desc in r['description']:
ret['result'] = r
return ret
return False
else:
return False
else:
raise KeyError
except KeyError:
return ret
def service_add(service_rootid=None, service_name=None, triggerid=None, **kwargs):
'''
.. versionadded:: Fluorine
Create service under service with id specified as parameter.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/create
:param service_rootid: Service id under which service should be added
:param service_name: Name of new service
:param triggerid: Optional - ID of trigger which should be watched in service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if service could not be added or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_add 11 'My service' 11111
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.create'
params = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
# Ensure that we have required params.
params.setdefault('algorithm', 1)
params.setdefault('showsla', 1)
params.setdefault('goodsla', 99.7)
params.setdefault('sortorder', 1)
if service_rootid:
params.setdefault('parentid', service_rootid)
if triggerid:
params.setdefault('triggerid', triggerid)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
def service_get(service_name=None, service_rootid=None, **kwargs):
'''
.. versionadded:: Fluorine
Get service according to name and parent service ID.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/service/get
:param service_name: Name of the service
:param service_rootid: ID of service parent
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:return: Service details, False if no service found or on failure.
CLI Example:
.. code-block:: bash
salt '*' zabbix.service_get 'My service' 11
'''
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'service.get'
if not service_name:
return {'result': False, 'comment': 'service_name param is required'}
params = {'output': ['name']}
if service_rootid:
params['parentids'] = service_rootid
params['filter'] = {'name': service_name}
params = _params_extend(params, _ignore_name=True, **kwargs)
ret = _query(method, params, conn_args['url'], conn_args['auth'])
return ret['result'] if ret['result'] else False
else:
raise KeyError
except KeyError:
return ret
|
saltstack/salt
|
salt/states/lxd_container.py
|
present
|
python
|
def present(name,
running=None,
source=None,
profiles=None,
config=None,
devices=None,
architecture='x86_64',
ephemeral=False,
restart_on_change=False,
remote_addr=None,
cert=None,
key=None,
verify_cert=True):
'''
Create the named container if it does not exist
name
The name of the container to be created
running : None
* If ``True``, ensure that the container is running
* If ``False``, ensure that the container is stopped
* If ``None``, do nothing with regards to the running state of the
container
source : None
Can be either a string containing an image alias:
"xenial/amd64"
or an dict with type "image" with alias:
{"type": "image",
"alias": "xenial/amd64"}
or image with "fingerprint":
{"type": "image",
"fingerprint": "SHA-256"}
or image with "properties":
{"type": "image",
"properties": {
"os": "ubuntu",
"release": "14.04",
"architecture": "x86_64"
}}
or none:
{"type": "none"}
or copy:
{"type": "copy",
"source": "my-old-container"}
profiles : ['default']
List of profiles to apply on this container
config :
A config dict or None (None = unset).
Can also be a list:
[{'key': 'boot.autostart', 'value': 1},
{'key': 'security.privileged', 'value': '1'}]
devices :
A device dict or None (None = unset).
architecture : 'x86_64'
Can be one of the following:
* unknown
* i686
* x86_64
* armv7l
* aarch64
* ppc
* ppc64
* ppc64le
* s390x
ephemeral : False
Destroy this container after stop?
restart_on_change : False
Restart the container when we detect changes on the config or
its devices?
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
'''
if profiles is None:
profiles = ['default']
if source is None:
source = {}
ret = {
'name': name,
'running': running,
'profiles': profiles,
'source': source,
'config': config,
'devices': devices,
'architecture': architecture,
'ephemeral': ephemeral,
'restart_on_change': restart_on_change,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert,
'changes': {}
}
container = None
try:
container = __salt__['lxd.container_get'](
name, remote_addr, cert, key, verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Profile not found
pass
if container is None:
if __opts__['test']:
# Test is on, just return that we would create the container
msg = 'Would create the container "{0}"'.format(name)
ret['changes'] = {
'created': msg
}
if running is True:
msg = msg + ' and start it.'
ret['changes']['started'] = (
'Would start the container "{0}"'.format(name)
)
ret['changes'] = {'created': msg}
return _unchanged(ret, msg)
# create the container
try:
__salt__['lxd.container_create'](
name,
source,
profiles,
config,
devices,
architecture,
ephemeral,
True, # Wait
remote_addr,
cert,
key,
verify_cert
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
msg = 'Created the container "{0}"'.format(name)
ret['changes'] = {
'created': msg
}
if running is True:
try:
__salt__['lxd.container_start'](
name,
remote_addr,
cert,
key,
verify_cert
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
msg = msg + ' and started it.'
ret['changes'] = {
'started': 'Started the container "{0}"'.format(name)
}
return _success(ret, msg)
# Container exists, lets check for differences
new_profiles = set(map(six.text_type, profiles))
old_profiles = set(map(six.text_type, container.profiles))
container_changed = False
profile_changes = []
# Removed profiles
for k in old_profiles.difference(new_profiles):
if not __opts__['test']:
profile_changes.append('Removed profile "{0}"'.format(k))
old_profiles.discard(k)
else:
profile_changes.append('Would remove profile "{0}"'.format(k))
# Added profiles
for k in new_profiles.difference(old_profiles):
if not __opts__['test']:
profile_changes.append('Added profile "{0}"'.format(k))
old_profiles.add(k)
else:
profile_changes.append('Would add profile "{0}"'.format(k))
if profile_changes:
container_changed = True
ret['changes']['profiles'] = profile_changes
container.profiles = list(old_profiles)
# Config and devices changes
config, devices = __salt__['lxd.normalize_input_values'](
config,
devices
)
changes = __salt__['lxd.sync_config_devices'](
container, config, devices, __opts__['test']
)
if changes:
container_changed = True
ret['changes'].update(changes)
is_running = \
container.status_code == CONTAINER_STATUS_RUNNING
if not __opts__['test']:
try:
__salt__['lxd.pylxd_save_object'](container)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
if running != is_running:
if running is True:
if __opts__['test']:
changes['running'] = 'Would start the container'
return _unchanged(
ret,
('Container "{0}" would get changed '
'and started.').format(name)
)
else:
container.start(wait=True)
changes['running'] = 'Started the container'
elif running is False:
if __opts__['test']:
changes['stopped'] = 'Would stopped the container'
return _unchanged(
ret,
('Container "{0}" would get changed '
'and stopped.').format(name)
)
else:
container.stop(wait=True)
changes['stopped'] = 'Stopped the container'
if ((running is True or running is None) and
is_running and
restart_on_change and
container_changed):
if __opts__['test']:
changes['restarted'] = 'Would restart the container'
return _unchanged(
ret,
'Would restart the container "{0}"'.format(name)
)
else:
container.restart(wait=True)
changes['restarted'] = (
'Container "{0}" has been restarted'.format(name)
)
return _success(
ret,
'Container "{0}" has been restarted'.format(name)
)
if not container_changed:
return _success(ret, 'No changes')
if __opts__['test']:
return _unchanged(
ret,
'Container "{0}" would get changed.'.format(name)
)
return _success(ret, '{0} changes'.format(len(ret['changes'].keys())))
|
Create the named container if it does not exist
name
The name of the container to be created
running : None
* If ``True``, ensure that the container is running
* If ``False``, ensure that the container is stopped
* If ``None``, do nothing with regards to the running state of the
container
source : None
Can be either a string containing an image alias:
"xenial/amd64"
or an dict with type "image" with alias:
{"type": "image",
"alias": "xenial/amd64"}
or image with "fingerprint":
{"type": "image",
"fingerprint": "SHA-256"}
or image with "properties":
{"type": "image",
"properties": {
"os": "ubuntu",
"release": "14.04",
"architecture": "x86_64"
}}
or none:
{"type": "none"}
or copy:
{"type": "copy",
"source": "my-old-container"}
profiles : ['default']
List of profiles to apply on this container
config :
A config dict or None (None = unset).
Can also be a list:
[{'key': 'boot.autostart', 'value': 1},
{'key': 'security.privileged', 'value': '1'}]
devices :
A device dict or None (None = unset).
architecture : 'x86_64'
Can be one of the following:
* unknown
* i686
* x86_64
* armv7l
* aarch64
* ppc
* ppc64
* ppc64le
* s390x
ephemeral : False
Destroy this container after stop?
restart_on_change : False
Restart the container when we detect changes on the config or
its devices?
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/lxd_container.py#L57-L360
|
[
"def _error(ret, err_msg):\n ret['result'] = False\n ret['comment'] = err_msg\n if 'changes' not in ret:\n ret['changes'] = {}\n return ret\n",
"def _unchanged(ret, msg):\n ret['result'] = None\n ret['comment'] = msg\n if 'changes' not in ret:\n ret['changes'] = {}\n return ret\n",
"def _success(ret, success_msg):\n ret['result'] = True\n ret['comment'] = success_msg\n if 'changes' not in ret:\n ret['changes'] = {}\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Manage LXD containers.
.. versionadded:: 2019.2.0
.. note:
- `pylxd`_ version 2 is required to let this work,
currently only available via pip.
To install on Ubuntu:
$ apt-get install libssl-dev python-pip
$ pip install -U pylxd
- you need lxd installed on the minion
for the init() and version() methods.
- for the config_get() and config_get() methods
you need to have lxd-client installed.
.. _: https://github.com/lxc/pylxd/blob/master/doc/source/installation.rst
:maintainer: René Jochum <rene@jochums.at>
:maturity: new
:depends: python-pylxd
:platform: Linux
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import salt libs
from salt.exceptions import CommandExecutionError
from salt.exceptions import SaltInvocationError
import salt.ext.six as six
from salt.ext.six.moves import map
__docformat__ = 'restructuredtext en'
__virtualname__ = 'lxd_container'
# Keep in sync with: https://github.com/lxc/lxd/blob/master/shared/status.go
CONTAINER_STATUS_RUNNING = 103
CONTAINER_STATUS_FROZEN = 110
CONTAINER_STATUS_STOPPED = 102
def __virtual__():
'''
Only load if the lxd module is available in __salt__
'''
return __virtualname__ if 'lxd.version' in __salt__ else False
def absent(name,
stop=False,
remote_addr=None,
cert=None,
key=None,
verify_cert=True):
'''
Ensure a LXD container is not present, destroying it if present
name :
The name of the container to destroy
stop :
stop before destroying
default: false
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
'''
ret = {
'name': name,
'stop': stop,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert,
'changes': {}
}
try:
container = __salt__['lxd.container_get'](
name, remote_addr, cert, key, verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Container not found
return _success(ret, 'Container "{0}" not found.'.format(name))
if __opts__['test']:
ret['changes'] = {
'removed':
'Container "{0}" would get deleted.'.format(name)
}
return _unchanged(ret, ret['changes']['removed'])
if stop and container.status_code == CONTAINER_STATUS_RUNNING:
container.stop(wait=True)
container.delete(wait=True)
ret['changes']['deleted'] = \
'Container "{0}" has been deleted.'.format(name)
return _success(ret, ret['changes']['deleted'])
def running(name,
restart=False,
remote_addr=None,
cert=None,
key=None,
verify_cert=True):
'''
Ensure a LXD container is running and restart it if restart is True
name :
The name of the container to start/restart.
restart :
restart the container if it is already started.
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
'''
ret = {
'name': name,
'restart': restart,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert,
'changes': {}
}
try:
container = __salt__['lxd.container_get'](
name, remote_addr, cert, key, verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Container not found
return _error(ret, 'Container "{0}" not found'.format(name))
is_running = container.status_code == CONTAINER_STATUS_RUNNING
if is_running:
if not restart:
return _success(
ret,
'The container "{0}" is already running'.format(name)
)
else:
if __opts__['test']:
ret['changes']['restarted'] = (
'Would restart the container "{0}"'.format(name)
)
return _unchanged(ret, ret['changes']['restarted'])
else:
container.restart(wait=True)
ret['changes']['restarted'] = (
'Restarted the container "{0}"'.format(name)
)
return _success(ret, ret['changes']['restarted'])
if __opts__['test']:
ret['changes']['started'] = (
'Would start the container "{0}"'.format(name)
)
return _unchanged(ret, ret['changes']['started'])
container.start(wait=True)
ret['changes']['started'] = (
'Started the container "{0}"'.format(name)
)
return _success(ret, ret['changes']['started'])
def frozen(name,
start=True,
remote_addr=None,
cert=None,
key=None,
verify_cert=True):
'''
Ensure a LXD container is frozen, start and freeze it if start is true
name :
The name of the container to freeze
start :
start and freeze it
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
'''
ret = {
'name': name,
'start': start,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert,
'changes': {}
}
try:
container = __salt__['lxd.container_get'](
name, remote_addr, cert, key, verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Container not found
return _error(ret, 'Container "{0}" not found'.format(name))
if container.status_code == CONTAINER_STATUS_FROZEN:
return _success(ret, 'Container "{0}" is alredy frozen'.format(name))
is_running = container.status_code == CONTAINER_STATUS_RUNNING
if not is_running and not start:
return _error(ret, (
'Container "{0}" is not running and start is False, '
'cannot freeze it').format(name)
)
elif not is_running and start:
if __opts__['test']:
ret['changes']['started'] = (
'Would start the container "{0}" and freeze it after'
.format(name)
)
return _unchanged(ret, ret['changes']['started'])
else:
container.start(wait=True)
ret['changes']['started'] = (
'Start the container "{0}"'
.format(name)
)
if __opts__['test']:
ret['changes']['frozen'] = (
'Would freeze the container "{0}"'.format(name)
)
return _unchanged(ret, ret['changes']['frozen'])
container.freeze(wait=True)
ret['changes']['frozen'] = (
'Froze the container "{0}"'.format(name)
)
return _success(ret, ret['changes']['frozen'])
def stopped(name,
kill=False,
remote_addr=None,
cert=None,
key=None,
verify_cert=True):
'''
Ensure a LXD container is stopped, kill it if kill is true else stop it
name :
The name of the container to stop
kill :
kill if true
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
'''
ret = {
'name': name,
'kill': kill,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert,
'changes': {}
}
try:
container = __salt__['lxd.container_get'](
name, remote_addr, cert, key, verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Container not found
return _error(ret, 'Container "{0}" not found'.format(name))
if container.status_code == CONTAINER_STATUS_STOPPED:
return _success(ret, 'Container "{0}" is already stopped'.format(name))
if __opts__['test']:
ret['changes']['stopped'] = \
'Would stop the container "{0}"'.format(name)
return _unchanged(ret, ret['changes']['stopped'])
container.stop(force=kill, wait=True)
ret['changes']['stopped'] = \
'Stopped the container "{0}"'.format(name)
return _success(ret, ret['changes']['stopped'])
def migrated(name,
remote_addr,
cert,
key,
verify_cert,
src_remote_addr,
stop_and_start=False,
src_cert=None,
src_key=None,
src_verify_cert=None):
''' Ensure a container is migrated to another host
If the container is running, it either must be shut down
first (use stop_and_start=True) or criu must be installed
on the source and destination machines.
For this operation both certs need to be authenticated,
use :mod:`lxd.authenticate <salt.states.lxd.authenticate`
to authenticate your cert(s).
name :
The container to migrate
remote_addr :
An URL to the destination remote Server
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
src_remote_addr :
An URL to the source remote Server
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
stop_and_start:
Stop before migrating and start after
src_cert :
PEM Formatted SSL Zertifikate, if None we copy "cert"
Examples:
~/.config/lxc/client.crt
src_key :
PEM Formatted SSL Key, if None we copy "key"
Examples:
~/.config/lxc/client.key
src_verify_cert :
Wherever to verify the cert, if None we copy "verify_cert"
'''
ret = {
'name': name,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert,
'src_remote_addr': src_remote_addr,
'src_and_start': stop_and_start,
'src_cert': src_cert,
'src_key': src_key,
'changes': {}
}
dest_container = None
try:
dest_container = __salt__['lxd.container_get'](
name, remote_addr, cert, key,
verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Destination container not found
pass
if dest_container is not None:
return _success(
ret,
'Container "{0}" exists on the destination'.format(name)
)
if src_verify_cert is None:
src_verify_cert = verify_cert
try:
__salt__['lxd.container_get'](
name, src_remote_addr, src_cert, src_key, src_verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Container not found
return _error(ret, 'Source Container "{0}" not found'.format(name))
if __opts__['test']:
ret['changes']['migrated'] = (
'Would migrate the container "{0}" from "{1}" to "{2}"'
).format(name, src_remote_addr, remote_addr)
return _unchanged(ret, ret['changes']['migrated'])
try:
__salt__['lxd.container_migrate'](
name, stop_and_start, remote_addr, cert, key,
verify_cert, src_remote_addr, src_cert, src_key, src_verify_cert
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
ret['changes']['migrated'] = (
'Migrated the container "{0}" from "{1}" to "{2}"'
).format(name, src_remote_addr, remote_addr)
return _success(ret, ret['changes']['migrated'])
def _success(ret, success_msg):
ret['result'] = True
ret['comment'] = success_msg
if 'changes' not in ret:
ret['changes'] = {}
return ret
def _unchanged(ret, msg):
ret['result'] = None
ret['comment'] = msg
if 'changes' not in ret:
ret['changes'] = {}
return ret
def _error(ret, err_msg):
ret['result'] = False
ret['comment'] = err_msg
if 'changes' not in ret:
ret['changes'] = {}
return ret
|
saltstack/salt
|
salt/states/lxd_container.py
|
absent
|
python
|
def absent(name,
stop=False,
remote_addr=None,
cert=None,
key=None,
verify_cert=True):
'''
Ensure a LXD container is not present, destroying it if present
name :
The name of the container to destroy
stop :
stop before destroying
default: false
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
'''
ret = {
'name': name,
'stop': stop,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert,
'changes': {}
}
try:
container = __salt__['lxd.container_get'](
name, remote_addr, cert, key, verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Container not found
return _success(ret, 'Container "{0}" not found.'.format(name))
if __opts__['test']:
ret['changes'] = {
'removed':
'Container "{0}" would get deleted.'.format(name)
}
return _unchanged(ret, ret['changes']['removed'])
if stop and container.status_code == CONTAINER_STATUS_RUNNING:
container.stop(wait=True)
container.delete(wait=True)
ret['changes']['deleted'] = \
'Container "{0}" has been deleted.'.format(name)
return _success(ret, ret['changes']['deleted'])
|
Ensure a LXD container is not present, destroying it if present
name :
The name of the container to destroy
stop :
stop before destroying
default: false
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/lxd_container.py#L363-L440
|
[
"def _error(ret, err_msg):\n ret['result'] = False\n ret['comment'] = err_msg\n if 'changes' not in ret:\n ret['changes'] = {}\n return ret\n",
"def _unchanged(ret, msg):\n ret['result'] = None\n ret['comment'] = msg\n if 'changes' not in ret:\n ret['changes'] = {}\n return ret\n",
"def _success(ret, success_msg):\n ret['result'] = True\n ret['comment'] = success_msg\n if 'changes' not in ret:\n ret['changes'] = {}\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Manage LXD containers.
.. versionadded:: 2019.2.0
.. note:
- `pylxd`_ version 2 is required to let this work,
currently only available via pip.
To install on Ubuntu:
$ apt-get install libssl-dev python-pip
$ pip install -U pylxd
- you need lxd installed on the minion
for the init() and version() methods.
- for the config_get() and config_get() methods
you need to have lxd-client installed.
.. _: https://github.com/lxc/pylxd/blob/master/doc/source/installation.rst
:maintainer: René Jochum <rene@jochums.at>
:maturity: new
:depends: python-pylxd
:platform: Linux
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import salt libs
from salt.exceptions import CommandExecutionError
from salt.exceptions import SaltInvocationError
import salt.ext.six as six
from salt.ext.six.moves import map
__docformat__ = 'restructuredtext en'
__virtualname__ = 'lxd_container'
# Keep in sync with: https://github.com/lxc/lxd/blob/master/shared/status.go
CONTAINER_STATUS_RUNNING = 103
CONTAINER_STATUS_FROZEN = 110
CONTAINER_STATUS_STOPPED = 102
def __virtual__():
'''
Only load if the lxd module is available in __salt__
'''
return __virtualname__ if 'lxd.version' in __salt__ else False
def present(name,
running=None,
source=None,
profiles=None,
config=None,
devices=None,
architecture='x86_64',
ephemeral=False,
restart_on_change=False,
remote_addr=None,
cert=None,
key=None,
verify_cert=True):
'''
Create the named container if it does not exist
name
The name of the container to be created
running : None
* If ``True``, ensure that the container is running
* If ``False``, ensure that the container is stopped
* If ``None``, do nothing with regards to the running state of the
container
source : None
Can be either a string containing an image alias:
"xenial/amd64"
or an dict with type "image" with alias:
{"type": "image",
"alias": "xenial/amd64"}
or image with "fingerprint":
{"type": "image",
"fingerprint": "SHA-256"}
or image with "properties":
{"type": "image",
"properties": {
"os": "ubuntu",
"release": "14.04",
"architecture": "x86_64"
}}
or none:
{"type": "none"}
or copy:
{"type": "copy",
"source": "my-old-container"}
profiles : ['default']
List of profiles to apply on this container
config :
A config dict or None (None = unset).
Can also be a list:
[{'key': 'boot.autostart', 'value': 1},
{'key': 'security.privileged', 'value': '1'}]
devices :
A device dict or None (None = unset).
architecture : 'x86_64'
Can be one of the following:
* unknown
* i686
* x86_64
* armv7l
* aarch64
* ppc
* ppc64
* ppc64le
* s390x
ephemeral : False
Destroy this container after stop?
restart_on_change : False
Restart the container when we detect changes on the config or
its devices?
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
'''
if profiles is None:
profiles = ['default']
if source is None:
source = {}
ret = {
'name': name,
'running': running,
'profiles': profiles,
'source': source,
'config': config,
'devices': devices,
'architecture': architecture,
'ephemeral': ephemeral,
'restart_on_change': restart_on_change,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert,
'changes': {}
}
container = None
try:
container = __salt__['lxd.container_get'](
name, remote_addr, cert, key, verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Profile not found
pass
if container is None:
if __opts__['test']:
# Test is on, just return that we would create the container
msg = 'Would create the container "{0}"'.format(name)
ret['changes'] = {
'created': msg
}
if running is True:
msg = msg + ' and start it.'
ret['changes']['started'] = (
'Would start the container "{0}"'.format(name)
)
ret['changes'] = {'created': msg}
return _unchanged(ret, msg)
# create the container
try:
__salt__['lxd.container_create'](
name,
source,
profiles,
config,
devices,
architecture,
ephemeral,
True, # Wait
remote_addr,
cert,
key,
verify_cert
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
msg = 'Created the container "{0}"'.format(name)
ret['changes'] = {
'created': msg
}
if running is True:
try:
__salt__['lxd.container_start'](
name,
remote_addr,
cert,
key,
verify_cert
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
msg = msg + ' and started it.'
ret['changes'] = {
'started': 'Started the container "{0}"'.format(name)
}
return _success(ret, msg)
# Container exists, lets check for differences
new_profiles = set(map(six.text_type, profiles))
old_profiles = set(map(six.text_type, container.profiles))
container_changed = False
profile_changes = []
# Removed profiles
for k in old_profiles.difference(new_profiles):
if not __opts__['test']:
profile_changes.append('Removed profile "{0}"'.format(k))
old_profiles.discard(k)
else:
profile_changes.append('Would remove profile "{0}"'.format(k))
# Added profiles
for k in new_profiles.difference(old_profiles):
if not __opts__['test']:
profile_changes.append('Added profile "{0}"'.format(k))
old_profiles.add(k)
else:
profile_changes.append('Would add profile "{0}"'.format(k))
if profile_changes:
container_changed = True
ret['changes']['profiles'] = profile_changes
container.profiles = list(old_profiles)
# Config and devices changes
config, devices = __salt__['lxd.normalize_input_values'](
config,
devices
)
changes = __salt__['lxd.sync_config_devices'](
container, config, devices, __opts__['test']
)
if changes:
container_changed = True
ret['changes'].update(changes)
is_running = \
container.status_code == CONTAINER_STATUS_RUNNING
if not __opts__['test']:
try:
__salt__['lxd.pylxd_save_object'](container)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
if running != is_running:
if running is True:
if __opts__['test']:
changes['running'] = 'Would start the container'
return _unchanged(
ret,
('Container "{0}" would get changed '
'and started.').format(name)
)
else:
container.start(wait=True)
changes['running'] = 'Started the container'
elif running is False:
if __opts__['test']:
changes['stopped'] = 'Would stopped the container'
return _unchanged(
ret,
('Container "{0}" would get changed '
'and stopped.').format(name)
)
else:
container.stop(wait=True)
changes['stopped'] = 'Stopped the container'
if ((running is True or running is None) and
is_running and
restart_on_change and
container_changed):
if __opts__['test']:
changes['restarted'] = 'Would restart the container'
return _unchanged(
ret,
'Would restart the container "{0}"'.format(name)
)
else:
container.restart(wait=True)
changes['restarted'] = (
'Container "{0}" has been restarted'.format(name)
)
return _success(
ret,
'Container "{0}" has been restarted'.format(name)
)
if not container_changed:
return _success(ret, 'No changes')
if __opts__['test']:
return _unchanged(
ret,
'Container "{0}" would get changed.'.format(name)
)
return _success(ret, '{0} changes'.format(len(ret['changes'].keys())))
def running(name,
restart=False,
remote_addr=None,
cert=None,
key=None,
verify_cert=True):
'''
Ensure a LXD container is running and restart it if restart is True
name :
The name of the container to start/restart.
restart :
restart the container if it is already started.
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
'''
ret = {
'name': name,
'restart': restart,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert,
'changes': {}
}
try:
container = __salt__['lxd.container_get'](
name, remote_addr, cert, key, verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Container not found
return _error(ret, 'Container "{0}" not found'.format(name))
is_running = container.status_code == CONTAINER_STATUS_RUNNING
if is_running:
if not restart:
return _success(
ret,
'The container "{0}" is already running'.format(name)
)
else:
if __opts__['test']:
ret['changes']['restarted'] = (
'Would restart the container "{0}"'.format(name)
)
return _unchanged(ret, ret['changes']['restarted'])
else:
container.restart(wait=True)
ret['changes']['restarted'] = (
'Restarted the container "{0}"'.format(name)
)
return _success(ret, ret['changes']['restarted'])
if __opts__['test']:
ret['changes']['started'] = (
'Would start the container "{0}"'.format(name)
)
return _unchanged(ret, ret['changes']['started'])
container.start(wait=True)
ret['changes']['started'] = (
'Started the container "{0}"'.format(name)
)
return _success(ret, ret['changes']['started'])
def frozen(name,
start=True,
remote_addr=None,
cert=None,
key=None,
verify_cert=True):
'''
Ensure a LXD container is frozen, start and freeze it if start is true
name :
The name of the container to freeze
start :
start and freeze it
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
'''
ret = {
'name': name,
'start': start,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert,
'changes': {}
}
try:
container = __salt__['lxd.container_get'](
name, remote_addr, cert, key, verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Container not found
return _error(ret, 'Container "{0}" not found'.format(name))
if container.status_code == CONTAINER_STATUS_FROZEN:
return _success(ret, 'Container "{0}" is alredy frozen'.format(name))
is_running = container.status_code == CONTAINER_STATUS_RUNNING
if not is_running and not start:
return _error(ret, (
'Container "{0}" is not running and start is False, '
'cannot freeze it').format(name)
)
elif not is_running and start:
if __opts__['test']:
ret['changes']['started'] = (
'Would start the container "{0}" and freeze it after'
.format(name)
)
return _unchanged(ret, ret['changes']['started'])
else:
container.start(wait=True)
ret['changes']['started'] = (
'Start the container "{0}"'
.format(name)
)
if __opts__['test']:
ret['changes']['frozen'] = (
'Would freeze the container "{0}"'.format(name)
)
return _unchanged(ret, ret['changes']['frozen'])
container.freeze(wait=True)
ret['changes']['frozen'] = (
'Froze the container "{0}"'.format(name)
)
return _success(ret, ret['changes']['frozen'])
def stopped(name,
kill=False,
remote_addr=None,
cert=None,
key=None,
verify_cert=True):
'''
Ensure a LXD container is stopped, kill it if kill is true else stop it
name :
The name of the container to stop
kill :
kill if true
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
'''
ret = {
'name': name,
'kill': kill,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert,
'changes': {}
}
try:
container = __salt__['lxd.container_get'](
name, remote_addr, cert, key, verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Container not found
return _error(ret, 'Container "{0}" not found'.format(name))
if container.status_code == CONTAINER_STATUS_STOPPED:
return _success(ret, 'Container "{0}" is already stopped'.format(name))
if __opts__['test']:
ret['changes']['stopped'] = \
'Would stop the container "{0}"'.format(name)
return _unchanged(ret, ret['changes']['stopped'])
container.stop(force=kill, wait=True)
ret['changes']['stopped'] = \
'Stopped the container "{0}"'.format(name)
return _success(ret, ret['changes']['stopped'])
def migrated(name,
remote_addr,
cert,
key,
verify_cert,
src_remote_addr,
stop_and_start=False,
src_cert=None,
src_key=None,
src_verify_cert=None):
''' Ensure a container is migrated to another host
If the container is running, it either must be shut down
first (use stop_and_start=True) or criu must be installed
on the source and destination machines.
For this operation both certs need to be authenticated,
use :mod:`lxd.authenticate <salt.states.lxd.authenticate`
to authenticate your cert(s).
name :
The container to migrate
remote_addr :
An URL to the destination remote Server
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
src_remote_addr :
An URL to the source remote Server
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
stop_and_start:
Stop before migrating and start after
src_cert :
PEM Formatted SSL Zertifikate, if None we copy "cert"
Examples:
~/.config/lxc/client.crt
src_key :
PEM Formatted SSL Key, if None we copy "key"
Examples:
~/.config/lxc/client.key
src_verify_cert :
Wherever to verify the cert, if None we copy "verify_cert"
'''
ret = {
'name': name,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert,
'src_remote_addr': src_remote_addr,
'src_and_start': stop_and_start,
'src_cert': src_cert,
'src_key': src_key,
'changes': {}
}
dest_container = None
try:
dest_container = __salt__['lxd.container_get'](
name, remote_addr, cert, key,
verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Destination container not found
pass
if dest_container is not None:
return _success(
ret,
'Container "{0}" exists on the destination'.format(name)
)
if src_verify_cert is None:
src_verify_cert = verify_cert
try:
__salt__['lxd.container_get'](
name, src_remote_addr, src_cert, src_key, src_verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Container not found
return _error(ret, 'Source Container "{0}" not found'.format(name))
if __opts__['test']:
ret['changes']['migrated'] = (
'Would migrate the container "{0}" from "{1}" to "{2}"'
).format(name, src_remote_addr, remote_addr)
return _unchanged(ret, ret['changes']['migrated'])
try:
__salt__['lxd.container_migrate'](
name, stop_and_start, remote_addr, cert, key,
verify_cert, src_remote_addr, src_cert, src_key, src_verify_cert
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
ret['changes']['migrated'] = (
'Migrated the container "{0}" from "{1}" to "{2}"'
).format(name, src_remote_addr, remote_addr)
return _success(ret, ret['changes']['migrated'])
def _success(ret, success_msg):
ret['result'] = True
ret['comment'] = success_msg
if 'changes' not in ret:
ret['changes'] = {}
return ret
def _unchanged(ret, msg):
ret['result'] = None
ret['comment'] = msg
if 'changes' not in ret:
ret['changes'] = {}
return ret
def _error(ret, err_msg):
ret['result'] = False
ret['comment'] = err_msg
if 'changes' not in ret:
ret['changes'] = {}
return ret
|
saltstack/salt
|
salt/states/lxd_container.py
|
running
|
python
|
def running(name,
restart=False,
remote_addr=None,
cert=None,
key=None,
verify_cert=True):
'''
Ensure a LXD container is running and restart it if restart is True
name :
The name of the container to start/restart.
restart :
restart the container if it is already started.
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
'''
ret = {
'name': name,
'restart': restart,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert,
'changes': {}
}
try:
container = __salt__['lxd.container_get'](
name, remote_addr, cert, key, verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Container not found
return _error(ret, 'Container "{0}" not found'.format(name))
is_running = container.status_code == CONTAINER_STATUS_RUNNING
if is_running:
if not restart:
return _success(
ret,
'The container "{0}" is already running'.format(name)
)
else:
if __opts__['test']:
ret['changes']['restarted'] = (
'Would restart the container "{0}"'.format(name)
)
return _unchanged(ret, ret['changes']['restarted'])
else:
container.restart(wait=True)
ret['changes']['restarted'] = (
'Restarted the container "{0}"'.format(name)
)
return _success(ret, ret['changes']['restarted'])
if __opts__['test']:
ret['changes']['started'] = (
'Would start the container "{0}"'.format(name)
)
return _unchanged(ret, ret['changes']['started'])
container.start(wait=True)
ret['changes']['started'] = (
'Started the container "{0}"'.format(name)
)
return _success(ret, ret['changes']['started'])
|
Ensure a LXD container is running and restart it if restart is True
name :
The name of the container to start/restart.
restart :
restart the container if it is already started.
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/lxd_container.py#L443-L536
|
[
"def _error(ret, err_msg):\n ret['result'] = False\n ret['comment'] = err_msg\n if 'changes' not in ret:\n ret['changes'] = {}\n return ret\n",
"def _unchanged(ret, msg):\n ret['result'] = None\n ret['comment'] = msg\n if 'changes' not in ret:\n ret['changes'] = {}\n return ret\n",
"def _success(ret, success_msg):\n ret['result'] = True\n ret['comment'] = success_msg\n if 'changes' not in ret:\n ret['changes'] = {}\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Manage LXD containers.
.. versionadded:: 2019.2.0
.. note:
- `pylxd`_ version 2 is required to let this work,
currently only available via pip.
To install on Ubuntu:
$ apt-get install libssl-dev python-pip
$ pip install -U pylxd
- you need lxd installed on the minion
for the init() and version() methods.
- for the config_get() and config_get() methods
you need to have lxd-client installed.
.. _: https://github.com/lxc/pylxd/blob/master/doc/source/installation.rst
:maintainer: René Jochum <rene@jochums.at>
:maturity: new
:depends: python-pylxd
:platform: Linux
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import salt libs
from salt.exceptions import CommandExecutionError
from salt.exceptions import SaltInvocationError
import salt.ext.six as six
from salt.ext.six.moves import map
__docformat__ = 'restructuredtext en'
__virtualname__ = 'lxd_container'
# Keep in sync with: https://github.com/lxc/lxd/blob/master/shared/status.go
CONTAINER_STATUS_RUNNING = 103
CONTAINER_STATUS_FROZEN = 110
CONTAINER_STATUS_STOPPED = 102
def __virtual__():
'''
Only load if the lxd module is available in __salt__
'''
return __virtualname__ if 'lxd.version' in __salt__ else False
def present(name,
running=None,
source=None,
profiles=None,
config=None,
devices=None,
architecture='x86_64',
ephemeral=False,
restart_on_change=False,
remote_addr=None,
cert=None,
key=None,
verify_cert=True):
'''
Create the named container if it does not exist
name
The name of the container to be created
running : None
* If ``True``, ensure that the container is running
* If ``False``, ensure that the container is stopped
* If ``None``, do nothing with regards to the running state of the
container
source : None
Can be either a string containing an image alias:
"xenial/amd64"
or an dict with type "image" with alias:
{"type": "image",
"alias": "xenial/amd64"}
or image with "fingerprint":
{"type": "image",
"fingerprint": "SHA-256"}
or image with "properties":
{"type": "image",
"properties": {
"os": "ubuntu",
"release": "14.04",
"architecture": "x86_64"
}}
or none:
{"type": "none"}
or copy:
{"type": "copy",
"source": "my-old-container"}
profiles : ['default']
List of profiles to apply on this container
config :
A config dict or None (None = unset).
Can also be a list:
[{'key': 'boot.autostart', 'value': 1},
{'key': 'security.privileged', 'value': '1'}]
devices :
A device dict or None (None = unset).
architecture : 'x86_64'
Can be one of the following:
* unknown
* i686
* x86_64
* armv7l
* aarch64
* ppc
* ppc64
* ppc64le
* s390x
ephemeral : False
Destroy this container after stop?
restart_on_change : False
Restart the container when we detect changes on the config or
its devices?
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
'''
if profiles is None:
profiles = ['default']
if source is None:
source = {}
ret = {
'name': name,
'running': running,
'profiles': profiles,
'source': source,
'config': config,
'devices': devices,
'architecture': architecture,
'ephemeral': ephemeral,
'restart_on_change': restart_on_change,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert,
'changes': {}
}
container = None
try:
container = __salt__['lxd.container_get'](
name, remote_addr, cert, key, verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Profile not found
pass
if container is None:
if __opts__['test']:
# Test is on, just return that we would create the container
msg = 'Would create the container "{0}"'.format(name)
ret['changes'] = {
'created': msg
}
if running is True:
msg = msg + ' and start it.'
ret['changes']['started'] = (
'Would start the container "{0}"'.format(name)
)
ret['changes'] = {'created': msg}
return _unchanged(ret, msg)
# create the container
try:
__salt__['lxd.container_create'](
name,
source,
profiles,
config,
devices,
architecture,
ephemeral,
True, # Wait
remote_addr,
cert,
key,
verify_cert
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
msg = 'Created the container "{0}"'.format(name)
ret['changes'] = {
'created': msg
}
if running is True:
try:
__salt__['lxd.container_start'](
name,
remote_addr,
cert,
key,
verify_cert
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
msg = msg + ' and started it.'
ret['changes'] = {
'started': 'Started the container "{0}"'.format(name)
}
return _success(ret, msg)
# Container exists, lets check for differences
new_profiles = set(map(six.text_type, profiles))
old_profiles = set(map(six.text_type, container.profiles))
container_changed = False
profile_changes = []
# Removed profiles
for k in old_profiles.difference(new_profiles):
if not __opts__['test']:
profile_changes.append('Removed profile "{0}"'.format(k))
old_profiles.discard(k)
else:
profile_changes.append('Would remove profile "{0}"'.format(k))
# Added profiles
for k in new_profiles.difference(old_profiles):
if not __opts__['test']:
profile_changes.append('Added profile "{0}"'.format(k))
old_profiles.add(k)
else:
profile_changes.append('Would add profile "{0}"'.format(k))
if profile_changes:
container_changed = True
ret['changes']['profiles'] = profile_changes
container.profiles = list(old_profiles)
# Config and devices changes
config, devices = __salt__['lxd.normalize_input_values'](
config,
devices
)
changes = __salt__['lxd.sync_config_devices'](
container, config, devices, __opts__['test']
)
if changes:
container_changed = True
ret['changes'].update(changes)
is_running = \
container.status_code == CONTAINER_STATUS_RUNNING
if not __opts__['test']:
try:
__salt__['lxd.pylxd_save_object'](container)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
if running != is_running:
if running is True:
if __opts__['test']:
changes['running'] = 'Would start the container'
return _unchanged(
ret,
('Container "{0}" would get changed '
'and started.').format(name)
)
else:
container.start(wait=True)
changes['running'] = 'Started the container'
elif running is False:
if __opts__['test']:
changes['stopped'] = 'Would stopped the container'
return _unchanged(
ret,
('Container "{0}" would get changed '
'and stopped.').format(name)
)
else:
container.stop(wait=True)
changes['stopped'] = 'Stopped the container'
if ((running is True or running is None) and
is_running and
restart_on_change and
container_changed):
if __opts__['test']:
changes['restarted'] = 'Would restart the container'
return _unchanged(
ret,
'Would restart the container "{0}"'.format(name)
)
else:
container.restart(wait=True)
changes['restarted'] = (
'Container "{0}" has been restarted'.format(name)
)
return _success(
ret,
'Container "{0}" has been restarted'.format(name)
)
if not container_changed:
return _success(ret, 'No changes')
if __opts__['test']:
return _unchanged(
ret,
'Container "{0}" would get changed.'.format(name)
)
return _success(ret, '{0} changes'.format(len(ret['changes'].keys())))
def absent(name,
stop=False,
remote_addr=None,
cert=None,
key=None,
verify_cert=True):
'''
Ensure a LXD container is not present, destroying it if present
name :
The name of the container to destroy
stop :
stop before destroying
default: false
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
'''
ret = {
'name': name,
'stop': stop,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert,
'changes': {}
}
try:
container = __salt__['lxd.container_get'](
name, remote_addr, cert, key, verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Container not found
return _success(ret, 'Container "{0}" not found.'.format(name))
if __opts__['test']:
ret['changes'] = {
'removed':
'Container "{0}" would get deleted.'.format(name)
}
return _unchanged(ret, ret['changes']['removed'])
if stop and container.status_code == CONTAINER_STATUS_RUNNING:
container.stop(wait=True)
container.delete(wait=True)
ret['changes']['deleted'] = \
'Container "{0}" has been deleted.'.format(name)
return _success(ret, ret['changes']['deleted'])
def frozen(name,
start=True,
remote_addr=None,
cert=None,
key=None,
verify_cert=True):
'''
Ensure a LXD container is frozen, start and freeze it if start is true
name :
The name of the container to freeze
start :
start and freeze it
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
'''
ret = {
'name': name,
'start': start,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert,
'changes': {}
}
try:
container = __salt__['lxd.container_get'](
name, remote_addr, cert, key, verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Container not found
return _error(ret, 'Container "{0}" not found'.format(name))
if container.status_code == CONTAINER_STATUS_FROZEN:
return _success(ret, 'Container "{0}" is alredy frozen'.format(name))
is_running = container.status_code == CONTAINER_STATUS_RUNNING
if not is_running and not start:
return _error(ret, (
'Container "{0}" is not running and start is False, '
'cannot freeze it').format(name)
)
elif not is_running and start:
if __opts__['test']:
ret['changes']['started'] = (
'Would start the container "{0}" and freeze it after'
.format(name)
)
return _unchanged(ret, ret['changes']['started'])
else:
container.start(wait=True)
ret['changes']['started'] = (
'Start the container "{0}"'
.format(name)
)
if __opts__['test']:
ret['changes']['frozen'] = (
'Would freeze the container "{0}"'.format(name)
)
return _unchanged(ret, ret['changes']['frozen'])
container.freeze(wait=True)
ret['changes']['frozen'] = (
'Froze the container "{0}"'.format(name)
)
return _success(ret, ret['changes']['frozen'])
def stopped(name,
kill=False,
remote_addr=None,
cert=None,
key=None,
verify_cert=True):
'''
Ensure a LXD container is stopped, kill it if kill is true else stop it
name :
The name of the container to stop
kill :
kill if true
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
'''
ret = {
'name': name,
'kill': kill,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert,
'changes': {}
}
try:
container = __salt__['lxd.container_get'](
name, remote_addr, cert, key, verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Container not found
return _error(ret, 'Container "{0}" not found'.format(name))
if container.status_code == CONTAINER_STATUS_STOPPED:
return _success(ret, 'Container "{0}" is already stopped'.format(name))
if __opts__['test']:
ret['changes']['stopped'] = \
'Would stop the container "{0}"'.format(name)
return _unchanged(ret, ret['changes']['stopped'])
container.stop(force=kill, wait=True)
ret['changes']['stopped'] = \
'Stopped the container "{0}"'.format(name)
return _success(ret, ret['changes']['stopped'])
def migrated(name,
remote_addr,
cert,
key,
verify_cert,
src_remote_addr,
stop_and_start=False,
src_cert=None,
src_key=None,
src_verify_cert=None):
''' Ensure a container is migrated to another host
If the container is running, it either must be shut down
first (use stop_and_start=True) or criu must be installed
on the source and destination machines.
For this operation both certs need to be authenticated,
use :mod:`lxd.authenticate <salt.states.lxd.authenticate`
to authenticate your cert(s).
name :
The container to migrate
remote_addr :
An URL to the destination remote Server
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
src_remote_addr :
An URL to the source remote Server
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
stop_and_start:
Stop before migrating and start after
src_cert :
PEM Formatted SSL Zertifikate, if None we copy "cert"
Examples:
~/.config/lxc/client.crt
src_key :
PEM Formatted SSL Key, if None we copy "key"
Examples:
~/.config/lxc/client.key
src_verify_cert :
Wherever to verify the cert, if None we copy "verify_cert"
'''
ret = {
'name': name,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert,
'src_remote_addr': src_remote_addr,
'src_and_start': stop_and_start,
'src_cert': src_cert,
'src_key': src_key,
'changes': {}
}
dest_container = None
try:
dest_container = __salt__['lxd.container_get'](
name, remote_addr, cert, key,
verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Destination container not found
pass
if dest_container is not None:
return _success(
ret,
'Container "{0}" exists on the destination'.format(name)
)
if src_verify_cert is None:
src_verify_cert = verify_cert
try:
__salt__['lxd.container_get'](
name, src_remote_addr, src_cert, src_key, src_verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Container not found
return _error(ret, 'Source Container "{0}" not found'.format(name))
if __opts__['test']:
ret['changes']['migrated'] = (
'Would migrate the container "{0}" from "{1}" to "{2}"'
).format(name, src_remote_addr, remote_addr)
return _unchanged(ret, ret['changes']['migrated'])
try:
__salt__['lxd.container_migrate'](
name, stop_and_start, remote_addr, cert, key,
verify_cert, src_remote_addr, src_cert, src_key, src_verify_cert
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
ret['changes']['migrated'] = (
'Migrated the container "{0}" from "{1}" to "{2}"'
).format(name, src_remote_addr, remote_addr)
return _success(ret, ret['changes']['migrated'])
def _success(ret, success_msg):
ret['result'] = True
ret['comment'] = success_msg
if 'changes' not in ret:
ret['changes'] = {}
return ret
def _unchanged(ret, msg):
ret['result'] = None
ret['comment'] = msg
if 'changes' not in ret:
ret['changes'] = {}
return ret
def _error(ret, err_msg):
ret['result'] = False
ret['comment'] = err_msg
if 'changes' not in ret:
ret['changes'] = {}
return ret
|
saltstack/salt
|
salt/states/lxd_container.py
|
stopped
|
python
|
def stopped(name,
kill=False,
remote_addr=None,
cert=None,
key=None,
verify_cert=True):
'''
Ensure a LXD container is stopped, kill it if kill is true else stop it
name :
The name of the container to stop
kill :
kill if true
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
'''
ret = {
'name': name,
'kill': kill,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert,
'changes': {}
}
try:
container = __salt__['lxd.container_get'](
name, remote_addr, cert, key, verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Container not found
return _error(ret, 'Container "{0}" not found'.format(name))
if container.status_code == CONTAINER_STATUS_STOPPED:
return _success(ret, 'Container "{0}" is already stopped'.format(name))
if __opts__['test']:
ret['changes']['stopped'] = \
'Would stop the container "{0}"'.format(name)
return _unchanged(ret, ret['changes']['stopped'])
container.stop(force=kill, wait=True)
ret['changes']['stopped'] = \
'Stopped the container "{0}"'.format(name)
return _success(ret, ret['changes']['stopped'])
|
Ensure a LXD container is stopped, kill it if kill is true else stop it
name :
The name of the container to stop
kill :
kill if true
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/lxd_container.py#L640-L713
|
[
"def _error(ret, err_msg):\n ret['result'] = False\n ret['comment'] = err_msg\n if 'changes' not in ret:\n ret['changes'] = {}\n return ret\n",
"def _unchanged(ret, msg):\n ret['result'] = None\n ret['comment'] = msg\n if 'changes' not in ret:\n ret['changes'] = {}\n return ret\n",
"def _success(ret, success_msg):\n ret['result'] = True\n ret['comment'] = success_msg\n if 'changes' not in ret:\n ret['changes'] = {}\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Manage LXD containers.
.. versionadded:: 2019.2.0
.. note:
- `pylxd`_ version 2 is required to let this work,
currently only available via pip.
To install on Ubuntu:
$ apt-get install libssl-dev python-pip
$ pip install -U pylxd
- you need lxd installed on the minion
for the init() and version() methods.
- for the config_get() and config_get() methods
you need to have lxd-client installed.
.. _: https://github.com/lxc/pylxd/blob/master/doc/source/installation.rst
:maintainer: René Jochum <rene@jochums.at>
:maturity: new
:depends: python-pylxd
:platform: Linux
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import salt libs
from salt.exceptions import CommandExecutionError
from salt.exceptions import SaltInvocationError
import salt.ext.six as six
from salt.ext.six.moves import map
__docformat__ = 'restructuredtext en'
__virtualname__ = 'lxd_container'
# Keep in sync with: https://github.com/lxc/lxd/blob/master/shared/status.go
CONTAINER_STATUS_RUNNING = 103
CONTAINER_STATUS_FROZEN = 110
CONTAINER_STATUS_STOPPED = 102
def __virtual__():
'''
Only load if the lxd module is available in __salt__
'''
return __virtualname__ if 'lxd.version' in __salt__ else False
def present(name,
running=None,
source=None,
profiles=None,
config=None,
devices=None,
architecture='x86_64',
ephemeral=False,
restart_on_change=False,
remote_addr=None,
cert=None,
key=None,
verify_cert=True):
'''
Create the named container if it does not exist
name
The name of the container to be created
running : None
* If ``True``, ensure that the container is running
* If ``False``, ensure that the container is stopped
* If ``None``, do nothing with regards to the running state of the
container
source : None
Can be either a string containing an image alias:
"xenial/amd64"
or an dict with type "image" with alias:
{"type": "image",
"alias": "xenial/amd64"}
or image with "fingerprint":
{"type": "image",
"fingerprint": "SHA-256"}
or image with "properties":
{"type": "image",
"properties": {
"os": "ubuntu",
"release": "14.04",
"architecture": "x86_64"
}}
or none:
{"type": "none"}
or copy:
{"type": "copy",
"source": "my-old-container"}
profiles : ['default']
List of profiles to apply on this container
config :
A config dict or None (None = unset).
Can also be a list:
[{'key': 'boot.autostart', 'value': 1},
{'key': 'security.privileged', 'value': '1'}]
devices :
A device dict or None (None = unset).
architecture : 'x86_64'
Can be one of the following:
* unknown
* i686
* x86_64
* armv7l
* aarch64
* ppc
* ppc64
* ppc64le
* s390x
ephemeral : False
Destroy this container after stop?
restart_on_change : False
Restart the container when we detect changes on the config or
its devices?
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
'''
if profiles is None:
profiles = ['default']
if source is None:
source = {}
ret = {
'name': name,
'running': running,
'profiles': profiles,
'source': source,
'config': config,
'devices': devices,
'architecture': architecture,
'ephemeral': ephemeral,
'restart_on_change': restart_on_change,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert,
'changes': {}
}
container = None
try:
container = __salt__['lxd.container_get'](
name, remote_addr, cert, key, verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Profile not found
pass
if container is None:
if __opts__['test']:
# Test is on, just return that we would create the container
msg = 'Would create the container "{0}"'.format(name)
ret['changes'] = {
'created': msg
}
if running is True:
msg = msg + ' and start it.'
ret['changes']['started'] = (
'Would start the container "{0}"'.format(name)
)
ret['changes'] = {'created': msg}
return _unchanged(ret, msg)
# create the container
try:
__salt__['lxd.container_create'](
name,
source,
profiles,
config,
devices,
architecture,
ephemeral,
True, # Wait
remote_addr,
cert,
key,
verify_cert
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
msg = 'Created the container "{0}"'.format(name)
ret['changes'] = {
'created': msg
}
if running is True:
try:
__salt__['lxd.container_start'](
name,
remote_addr,
cert,
key,
verify_cert
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
msg = msg + ' and started it.'
ret['changes'] = {
'started': 'Started the container "{0}"'.format(name)
}
return _success(ret, msg)
# Container exists, lets check for differences
new_profiles = set(map(six.text_type, profiles))
old_profiles = set(map(six.text_type, container.profiles))
container_changed = False
profile_changes = []
# Removed profiles
for k in old_profiles.difference(new_profiles):
if not __opts__['test']:
profile_changes.append('Removed profile "{0}"'.format(k))
old_profiles.discard(k)
else:
profile_changes.append('Would remove profile "{0}"'.format(k))
# Added profiles
for k in new_profiles.difference(old_profiles):
if not __opts__['test']:
profile_changes.append('Added profile "{0}"'.format(k))
old_profiles.add(k)
else:
profile_changes.append('Would add profile "{0}"'.format(k))
if profile_changes:
container_changed = True
ret['changes']['profiles'] = profile_changes
container.profiles = list(old_profiles)
# Config and devices changes
config, devices = __salt__['lxd.normalize_input_values'](
config,
devices
)
changes = __salt__['lxd.sync_config_devices'](
container, config, devices, __opts__['test']
)
if changes:
container_changed = True
ret['changes'].update(changes)
is_running = \
container.status_code == CONTAINER_STATUS_RUNNING
if not __opts__['test']:
try:
__salt__['lxd.pylxd_save_object'](container)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
if running != is_running:
if running is True:
if __opts__['test']:
changes['running'] = 'Would start the container'
return _unchanged(
ret,
('Container "{0}" would get changed '
'and started.').format(name)
)
else:
container.start(wait=True)
changes['running'] = 'Started the container'
elif running is False:
if __opts__['test']:
changes['stopped'] = 'Would stopped the container'
return _unchanged(
ret,
('Container "{0}" would get changed '
'and stopped.').format(name)
)
else:
container.stop(wait=True)
changes['stopped'] = 'Stopped the container'
if ((running is True or running is None) and
is_running and
restart_on_change and
container_changed):
if __opts__['test']:
changes['restarted'] = 'Would restart the container'
return _unchanged(
ret,
'Would restart the container "{0}"'.format(name)
)
else:
container.restart(wait=True)
changes['restarted'] = (
'Container "{0}" has been restarted'.format(name)
)
return _success(
ret,
'Container "{0}" has been restarted'.format(name)
)
if not container_changed:
return _success(ret, 'No changes')
if __opts__['test']:
return _unchanged(
ret,
'Container "{0}" would get changed.'.format(name)
)
return _success(ret, '{0} changes'.format(len(ret['changes'].keys())))
def absent(name,
stop=False,
remote_addr=None,
cert=None,
key=None,
verify_cert=True):
'''
Ensure a LXD container is not present, destroying it if present
name :
The name of the container to destroy
stop :
stop before destroying
default: false
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
'''
ret = {
'name': name,
'stop': stop,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert,
'changes': {}
}
try:
container = __salt__['lxd.container_get'](
name, remote_addr, cert, key, verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Container not found
return _success(ret, 'Container "{0}" not found.'.format(name))
if __opts__['test']:
ret['changes'] = {
'removed':
'Container "{0}" would get deleted.'.format(name)
}
return _unchanged(ret, ret['changes']['removed'])
if stop and container.status_code == CONTAINER_STATUS_RUNNING:
container.stop(wait=True)
container.delete(wait=True)
ret['changes']['deleted'] = \
'Container "{0}" has been deleted.'.format(name)
return _success(ret, ret['changes']['deleted'])
def running(name,
restart=False,
remote_addr=None,
cert=None,
key=None,
verify_cert=True):
'''
Ensure a LXD container is running and restart it if restart is True
name :
The name of the container to start/restart.
restart :
restart the container if it is already started.
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
'''
ret = {
'name': name,
'restart': restart,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert,
'changes': {}
}
try:
container = __salt__['lxd.container_get'](
name, remote_addr, cert, key, verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Container not found
return _error(ret, 'Container "{0}" not found'.format(name))
is_running = container.status_code == CONTAINER_STATUS_RUNNING
if is_running:
if not restart:
return _success(
ret,
'The container "{0}" is already running'.format(name)
)
else:
if __opts__['test']:
ret['changes']['restarted'] = (
'Would restart the container "{0}"'.format(name)
)
return _unchanged(ret, ret['changes']['restarted'])
else:
container.restart(wait=True)
ret['changes']['restarted'] = (
'Restarted the container "{0}"'.format(name)
)
return _success(ret, ret['changes']['restarted'])
if __opts__['test']:
ret['changes']['started'] = (
'Would start the container "{0}"'.format(name)
)
return _unchanged(ret, ret['changes']['started'])
container.start(wait=True)
ret['changes']['started'] = (
'Started the container "{0}"'.format(name)
)
return _success(ret, ret['changes']['started'])
def frozen(name,
start=True,
remote_addr=None,
cert=None,
key=None,
verify_cert=True):
'''
Ensure a LXD container is frozen, start and freeze it if start is true
name :
The name of the container to freeze
start :
start and freeze it
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
'''
ret = {
'name': name,
'start': start,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert,
'changes': {}
}
try:
container = __salt__['lxd.container_get'](
name, remote_addr, cert, key, verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Container not found
return _error(ret, 'Container "{0}" not found'.format(name))
if container.status_code == CONTAINER_STATUS_FROZEN:
return _success(ret, 'Container "{0}" is alredy frozen'.format(name))
is_running = container.status_code == CONTAINER_STATUS_RUNNING
if not is_running and not start:
return _error(ret, (
'Container "{0}" is not running and start is False, '
'cannot freeze it').format(name)
)
elif not is_running and start:
if __opts__['test']:
ret['changes']['started'] = (
'Would start the container "{0}" and freeze it after'
.format(name)
)
return _unchanged(ret, ret['changes']['started'])
else:
container.start(wait=True)
ret['changes']['started'] = (
'Start the container "{0}"'
.format(name)
)
if __opts__['test']:
ret['changes']['frozen'] = (
'Would freeze the container "{0}"'.format(name)
)
return _unchanged(ret, ret['changes']['frozen'])
container.freeze(wait=True)
ret['changes']['frozen'] = (
'Froze the container "{0}"'.format(name)
)
return _success(ret, ret['changes']['frozen'])
def migrated(name,
remote_addr,
cert,
key,
verify_cert,
src_remote_addr,
stop_and_start=False,
src_cert=None,
src_key=None,
src_verify_cert=None):
''' Ensure a container is migrated to another host
If the container is running, it either must be shut down
first (use stop_and_start=True) or criu must be installed
on the source and destination machines.
For this operation both certs need to be authenticated,
use :mod:`lxd.authenticate <salt.states.lxd.authenticate`
to authenticate your cert(s).
name :
The container to migrate
remote_addr :
An URL to the destination remote Server
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
src_remote_addr :
An URL to the source remote Server
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
stop_and_start:
Stop before migrating and start after
src_cert :
PEM Formatted SSL Zertifikate, if None we copy "cert"
Examples:
~/.config/lxc/client.crt
src_key :
PEM Formatted SSL Key, if None we copy "key"
Examples:
~/.config/lxc/client.key
src_verify_cert :
Wherever to verify the cert, if None we copy "verify_cert"
'''
ret = {
'name': name,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert,
'src_remote_addr': src_remote_addr,
'src_and_start': stop_and_start,
'src_cert': src_cert,
'src_key': src_key,
'changes': {}
}
dest_container = None
try:
dest_container = __salt__['lxd.container_get'](
name, remote_addr, cert, key,
verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Destination container not found
pass
if dest_container is not None:
return _success(
ret,
'Container "{0}" exists on the destination'.format(name)
)
if src_verify_cert is None:
src_verify_cert = verify_cert
try:
__salt__['lxd.container_get'](
name, src_remote_addr, src_cert, src_key, src_verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Container not found
return _error(ret, 'Source Container "{0}" not found'.format(name))
if __opts__['test']:
ret['changes']['migrated'] = (
'Would migrate the container "{0}" from "{1}" to "{2}"'
).format(name, src_remote_addr, remote_addr)
return _unchanged(ret, ret['changes']['migrated'])
try:
__salt__['lxd.container_migrate'](
name, stop_and_start, remote_addr, cert, key,
verify_cert, src_remote_addr, src_cert, src_key, src_verify_cert
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
ret['changes']['migrated'] = (
'Migrated the container "{0}" from "{1}" to "{2}"'
).format(name, src_remote_addr, remote_addr)
return _success(ret, ret['changes']['migrated'])
def _success(ret, success_msg):
ret['result'] = True
ret['comment'] = success_msg
if 'changes' not in ret:
ret['changes'] = {}
return ret
def _unchanged(ret, msg):
ret['result'] = None
ret['comment'] = msg
if 'changes' not in ret:
ret['changes'] = {}
return ret
def _error(ret, err_msg):
ret['result'] = False
ret['comment'] = err_msg
if 'changes' not in ret:
ret['changes'] = {}
return ret
|
saltstack/salt
|
salt/states/lxd_container.py
|
migrated
|
python
|
def migrated(name,
remote_addr,
cert,
key,
verify_cert,
src_remote_addr,
stop_and_start=False,
src_cert=None,
src_key=None,
src_verify_cert=None):
''' Ensure a container is migrated to another host
If the container is running, it either must be shut down
first (use stop_and_start=True) or criu must be installed
on the source and destination machines.
For this operation both certs need to be authenticated,
use :mod:`lxd.authenticate <salt.states.lxd.authenticate`
to authenticate your cert(s).
name :
The container to migrate
remote_addr :
An URL to the destination remote Server
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
src_remote_addr :
An URL to the source remote Server
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
stop_and_start:
Stop before migrating and start after
src_cert :
PEM Formatted SSL Zertifikate, if None we copy "cert"
Examples:
~/.config/lxc/client.crt
src_key :
PEM Formatted SSL Key, if None we copy "key"
Examples:
~/.config/lxc/client.key
src_verify_cert :
Wherever to verify the cert, if None we copy "verify_cert"
'''
ret = {
'name': name,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert,
'src_remote_addr': src_remote_addr,
'src_and_start': stop_and_start,
'src_cert': src_cert,
'src_key': src_key,
'changes': {}
}
dest_container = None
try:
dest_container = __salt__['lxd.container_get'](
name, remote_addr, cert, key,
verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Destination container not found
pass
if dest_container is not None:
return _success(
ret,
'Container "{0}" exists on the destination'.format(name)
)
if src_verify_cert is None:
src_verify_cert = verify_cert
try:
__salt__['lxd.container_get'](
name, src_remote_addr, src_cert, src_key, src_verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Container not found
return _error(ret, 'Source Container "{0}" not found'.format(name))
if __opts__['test']:
ret['changes']['migrated'] = (
'Would migrate the container "{0}" from "{1}" to "{2}"'
).format(name, src_remote_addr, remote_addr)
return _unchanged(ret, ret['changes']['migrated'])
try:
__salt__['lxd.container_migrate'](
name, stop_and_start, remote_addr, cert, key,
verify_cert, src_remote_addr, src_cert, src_key, src_verify_cert
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
ret['changes']['migrated'] = (
'Migrated the container "{0}" from "{1}" to "{2}"'
).format(name, src_remote_addr, remote_addr)
return _success(ret, ret['changes']['migrated'])
|
Ensure a container is migrated to another host
If the container is running, it either must be shut down
first (use stop_and_start=True) or criu must be installed
on the source and destination machines.
For this operation both certs need to be authenticated,
use :mod:`lxd.authenticate <salt.states.lxd.authenticate`
to authenticate your cert(s).
name :
The container to migrate
remote_addr :
An URL to the destination remote Server
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
src_remote_addr :
An URL to the source remote Server
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
stop_and_start:
Stop before migrating and start after
src_cert :
PEM Formatted SSL Zertifikate, if None we copy "cert"
Examples:
~/.config/lxc/client.crt
src_key :
PEM Formatted SSL Key, if None we copy "key"
Examples:
~/.config/lxc/client.key
src_verify_cert :
Wherever to verify the cert, if None we copy "verify_cert"
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/lxd_container.py#L716-L852
|
[
"def _error(ret, err_msg):\n ret['result'] = False\n ret['comment'] = err_msg\n if 'changes' not in ret:\n ret['changes'] = {}\n return ret\n",
"def _unchanged(ret, msg):\n ret['result'] = None\n ret['comment'] = msg\n if 'changes' not in ret:\n ret['changes'] = {}\n return ret\n",
"def _success(ret, success_msg):\n ret['result'] = True\n ret['comment'] = success_msg\n if 'changes' not in ret:\n ret['changes'] = {}\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Manage LXD containers.
.. versionadded:: 2019.2.0
.. note:
- `pylxd`_ version 2 is required to let this work,
currently only available via pip.
To install on Ubuntu:
$ apt-get install libssl-dev python-pip
$ pip install -U pylxd
- you need lxd installed on the minion
for the init() and version() methods.
- for the config_get() and config_get() methods
you need to have lxd-client installed.
.. _: https://github.com/lxc/pylxd/blob/master/doc/source/installation.rst
:maintainer: René Jochum <rene@jochums.at>
:maturity: new
:depends: python-pylxd
:platform: Linux
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import salt libs
from salt.exceptions import CommandExecutionError
from salt.exceptions import SaltInvocationError
import salt.ext.six as six
from salt.ext.six.moves import map
__docformat__ = 'restructuredtext en'
__virtualname__ = 'lxd_container'
# Keep in sync with: https://github.com/lxc/lxd/blob/master/shared/status.go
CONTAINER_STATUS_RUNNING = 103
CONTAINER_STATUS_FROZEN = 110
CONTAINER_STATUS_STOPPED = 102
def __virtual__():
'''
Only load if the lxd module is available in __salt__
'''
return __virtualname__ if 'lxd.version' in __salt__ else False
def present(name,
running=None,
source=None,
profiles=None,
config=None,
devices=None,
architecture='x86_64',
ephemeral=False,
restart_on_change=False,
remote_addr=None,
cert=None,
key=None,
verify_cert=True):
'''
Create the named container if it does not exist
name
The name of the container to be created
running : None
* If ``True``, ensure that the container is running
* If ``False``, ensure that the container is stopped
* If ``None``, do nothing with regards to the running state of the
container
source : None
Can be either a string containing an image alias:
"xenial/amd64"
or an dict with type "image" with alias:
{"type": "image",
"alias": "xenial/amd64"}
or image with "fingerprint":
{"type": "image",
"fingerprint": "SHA-256"}
or image with "properties":
{"type": "image",
"properties": {
"os": "ubuntu",
"release": "14.04",
"architecture": "x86_64"
}}
or none:
{"type": "none"}
or copy:
{"type": "copy",
"source": "my-old-container"}
profiles : ['default']
List of profiles to apply on this container
config :
A config dict or None (None = unset).
Can also be a list:
[{'key': 'boot.autostart', 'value': 1},
{'key': 'security.privileged', 'value': '1'}]
devices :
A device dict or None (None = unset).
architecture : 'x86_64'
Can be one of the following:
* unknown
* i686
* x86_64
* armv7l
* aarch64
* ppc
* ppc64
* ppc64le
* s390x
ephemeral : False
Destroy this container after stop?
restart_on_change : False
Restart the container when we detect changes on the config or
its devices?
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
'''
if profiles is None:
profiles = ['default']
if source is None:
source = {}
ret = {
'name': name,
'running': running,
'profiles': profiles,
'source': source,
'config': config,
'devices': devices,
'architecture': architecture,
'ephemeral': ephemeral,
'restart_on_change': restart_on_change,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert,
'changes': {}
}
container = None
try:
container = __salt__['lxd.container_get'](
name, remote_addr, cert, key, verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Profile not found
pass
if container is None:
if __opts__['test']:
# Test is on, just return that we would create the container
msg = 'Would create the container "{0}"'.format(name)
ret['changes'] = {
'created': msg
}
if running is True:
msg = msg + ' and start it.'
ret['changes']['started'] = (
'Would start the container "{0}"'.format(name)
)
ret['changes'] = {'created': msg}
return _unchanged(ret, msg)
# create the container
try:
__salt__['lxd.container_create'](
name,
source,
profiles,
config,
devices,
architecture,
ephemeral,
True, # Wait
remote_addr,
cert,
key,
verify_cert
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
msg = 'Created the container "{0}"'.format(name)
ret['changes'] = {
'created': msg
}
if running is True:
try:
__salt__['lxd.container_start'](
name,
remote_addr,
cert,
key,
verify_cert
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
msg = msg + ' and started it.'
ret['changes'] = {
'started': 'Started the container "{0}"'.format(name)
}
return _success(ret, msg)
# Container exists, lets check for differences
new_profiles = set(map(six.text_type, profiles))
old_profiles = set(map(six.text_type, container.profiles))
container_changed = False
profile_changes = []
# Removed profiles
for k in old_profiles.difference(new_profiles):
if not __opts__['test']:
profile_changes.append('Removed profile "{0}"'.format(k))
old_profiles.discard(k)
else:
profile_changes.append('Would remove profile "{0}"'.format(k))
# Added profiles
for k in new_profiles.difference(old_profiles):
if not __opts__['test']:
profile_changes.append('Added profile "{0}"'.format(k))
old_profiles.add(k)
else:
profile_changes.append('Would add profile "{0}"'.format(k))
if profile_changes:
container_changed = True
ret['changes']['profiles'] = profile_changes
container.profiles = list(old_profiles)
# Config and devices changes
config, devices = __salt__['lxd.normalize_input_values'](
config,
devices
)
changes = __salt__['lxd.sync_config_devices'](
container, config, devices, __opts__['test']
)
if changes:
container_changed = True
ret['changes'].update(changes)
is_running = \
container.status_code == CONTAINER_STATUS_RUNNING
if not __opts__['test']:
try:
__salt__['lxd.pylxd_save_object'](container)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
if running != is_running:
if running is True:
if __opts__['test']:
changes['running'] = 'Would start the container'
return _unchanged(
ret,
('Container "{0}" would get changed '
'and started.').format(name)
)
else:
container.start(wait=True)
changes['running'] = 'Started the container'
elif running is False:
if __opts__['test']:
changes['stopped'] = 'Would stopped the container'
return _unchanged(
ret,
('Container "{0}" would get changed '
'and stopped.').format(name)
)
else:
container.stop(wait=True)
changes['stopped'] = 'Stopped the container'
if ((running is True or running is None) and
is_running and
restart_on_change and
container_changed):
if __opts__['test']:
changes['restarted'] = 'Would restart the container'
return _unchanged(
ret,
'Would restart the container "{0}"'.format(name)
)
else:
container.restart(wait=True)
changes['restarted'] = (
'Container "{0}" has been restarted'.format(name)
)
return _success(
ret,
'Container "{0}" has been restarted'.format(name)
)
if not container_changed:
return _success(ret, 'No changes')
if __opts__['test']:
return _unchanged(
ret,
'Container "{0}" would get changed.'.format(name)
)
return _success(ret, '{0} changes'.format(len(ret['changes'].keys())))
def absent(name,
stop=False,
remote_addr=None,
cert=None,
key=None,
verify_cert=True):
'''
Ensure a LXD container is not present, destroying it if present
name :
The name of the container to destroy
stop :
stop before destroying
default: false
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
'''
ret = {
'name': name,
'stop': stop,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert,
'changes': {}
}
try:
container = __salt__['lxd.container_get'](
name, remote_addr, cert, key, verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Container not found
return _success(ret, 'Container "{0}" not found.'.format(name))
if __opts__['test']:
ret['changes'] = {
'removed':
'Container "{0}" would get deleted.'.format(name)
}
return _unchanged(ret, ret['changes']['removed'])
if stop and container.status_code == CONTAINER_STATUS_RUNNING:
container.stop(wait=True)
container.delete(wait=True)
ret['changes']['deleted'] = \
'Container "{0}" has been deleted.'.format(name)
return _success(ret, ret['changes']['deleted'])
def running(name,
restart=False,
remote_addr=None,
cert=None,
key=None,
verify_cert=True):
'''
Ensure a LXD container is running and restart it if restart is True
name :
The name of the container to start/restart.
restart :
restart the container if it is already started.
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
'''
ret = {
'name': name,
'restart': restart,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert,
'changes': {}
}
try:
container = __salt__['lxd.container_get'](
name, remote_addr, cert, key, verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Container not found
return _error(ret, 'Container "{0}" not found'.format(name))
is_running = container.status_code == CONTAINER_STATUS_RUNNING
if is_running:
if not restart:
return _success(
ret,
'The container "{0}" is already running'.format(name)
)
else:
if __opts__['test']:
ret['changes']['restarted'] = (
'Would restart the container "{0}"'.format(name)
)
return _unchanged(ret, ret['changes']['restarted'])
else:
container.restart(wait=True)
ret['changes']['restarted'] = (
'Restarted the container "{0}"'.format(name)
)
return _success(ret, ret['changes']['restarted'])
if __opts__['test']:
ret['changes']['started'] = (
'Would start the container "{0}"'.format(name)
)
return _unchanged(ret, ret['changes']['started'])
container.start(wait=True)
ret['changes']['started'] = (
'Started the container "{0}"'.format(name)
)
return _success(ret, ret['changes']['started'])
def frozen(name,
start=True,
remote_addr=None,
cert=None,
key=None,
verify_cert=True):
'''
Ensure a LXD container is frozen, start and freeze it if start is true
name :
The name of the container to freeze
start :
start and freeze it
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
'''
ret = {
'name': name,
'start': start,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert,
'changes': {}
}
try:
container = __salt__['lxd.container_get'](
name, remote_addr, cert, key, verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Container not found
return _error(ret, 'Container "{0}" not found'.format(name))
if container.status_code == CONTAINER_STATUS_FROZEN:
return _success(ret, 'Container "{0}" is alredy frozen'.format(name))
is_running = container.status_code == CONTAINER_STATUS_RUNNING
if not is_running and not start:
return _error(ret, (
'Container "{0}" is not running and start is False, '
'cannot freeze it').format(name)
)
elif not is_running and start:
if __opts__['test']:
ret['changes']['started'] = (
'Would start the container "{0}" and freeze it after'
.format(name)
)
return _unchanged(ret, ret['changes']['started'])
else:
container.start(wait=True)
ret['changes']['started'] = (
'Start the container "{0}"'
.format(name)
)
if __opts__['test']:
ret['changes']['frozen'] = (
'Would freeze the container "{0}"'.format(name)
)
return _unchanged(ret, ret['changes']['frozen'])
container.freeze(wait=True)
ret['changes']['frozen'] = (
'Froze the container "{0}"'.format(name)
)
return _success(ret, ret['changes']['frozen'])
def stopped(name,
kill=False,
remote_addr=None,
cert=None,
key=None,
verify_cert=True):
'''
Ensure a LXD container is stopped, kill it if kill is true else stop it
name :
The name of the container to stop
kill :
kill if true
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
'''
ret = {
'name': name,
'kill': kill,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert,
'changes': {}
}
try:
container = __salt__['lxd.container_get'](
name, remote_addr, cert, key, verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Container not found
return _error(ret, 'Container "{0}" not found'.format(name))
if container.status_code == CONTAINER_STATUS_STOPPED:
return _success(ret, 'Container "{0}" is already stopped'.format(name))
if __opts__['test']:
ret['changes']['stopped'] = \
'Would stop the container "{0}"'.format(name)
return _unchanged(ret, ret['changes']['stopped'])
container.stop(force=kill, wait=True)
ret['changes']['stopped'] = \
'Stopped the container "{0}"'.format(name)
return _success(ret, ret['changes']['stopped'])
def _success(ret, success_msg):
ret['result'] = True
ret['comment'] = success_msg
if 'changes' not in ret:
ret['changes'] = {}
return ret
def _unchanged(ret, msg):
ret['result'] = None
ret['comment'] = msg
if 'changes' not in ret:
ret['changes'] = {}
return ret
def _error(ret, err_msg):
ret['result'] = False
ret['comment'] = err_msg
if 'changes' not in ret:
ret['changes'] = {}
return ret
|
saltstack/salt
|
salt/modules/bcache.py
|
uuid
|
python
|
def uuid(dev=None):
'''
Return the bcache UUID of a block device.
If no device is given, the Cache UUID is returned.
CLI example:
.. code-block:: bash
salt '*' bcache.uuid
salt '*' bcache.uuid /dev/sda
salt '*' bcache.uuid bcache0
'''
try:
if dev is None:
# take the only directory in /sys/fs/bcache and return it's basename
return list(salt.utils.path.os_walk('/sys/fs/bcache/'))[0][1][0]
else:
# basename of the /sys/block/{dev}/bcache/cache symlink target
return os.path.basename(_bcsys(dev, 'cache'))
except Exception:
return False
|
Return the bcache UUID of a block device.
If no device is given, the Cache UUID is returned.
CLI example:
.. code-block:: bash
salt '*' bcache.uuid
salt '*' bcache.uuid /dev/sda
salt '*' bcache.uuid bcache0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bcache.py#L57-L79
|
[
"def os_walk(top, *args, **kwargs):\n '''\n This is a helper than ensures that all paths returned from os.walk are\n unicode.\n '''\n if six.PY2 and salt.utils.platform.is_windows():\n top_query = top\n else:\n top_query = salt.utils.stringutils.to_str(top)\n for item in os.walk(top_query, *args, **kwargs):\n yield salt.utils.data.decode(item, preserve_tuples=True)\n",
"def _bcsys(dev, name, value=None, log_lvl=None, log_msg=None):\n '''\n Simple wrapper to interface with backing devs SysFS\n '''\n return _sysfs_attr([_bcpath(dev), name], value, log_lvl, log_msg)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for managing BCache sets
BCache is a block-level caching mechanism similar to ZFS L2ARC/ZIL, dm-cache and fscache.
It works by formatting one block device as a cache set, then adding backend devices
(which need to be formatted as such) to the set and activating them.
It's available in Linux mainline kernel since 3.10
https://www.kernel.org/doc/Documentation/bcache.txt
This module needs the bcache userspace tools to function.
.. versionadded: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import time
import re
from salt.ext import six
# Import salt libs
import salt.utils.path
log = logging.getLogger(__name__)
LOG = {
'trace': logging.TRACE,
'debug': logging.DEBUG,
'info': logging.INFO,
'warn': logging.WARNING,
'error': logging.ERROR,
'crit': logging.CRITICAL,
}
__func_alias__ = {
'attach_': 'attach',
'config_': 'config',
'super_': 'super',
}
HAS_BLKDISCARD = salt.utils.path.which('blkdiscard') is not None
def __virtual__():
'''
Only work when make-bcache is installed
'''
return salt.utils.path.which('make-bcache') is not None
def attach_(dev=None):
'''
Attach a backing devices to a cache set
If no dev is given, all backing devices will be attached.
CLI example:
.. code-block:: bash
salt '*' bcache.attach sdc
salt '*' bcache.attach /dev/bcache1
:return: bool or None if nuttin' happened
'''
cache = uuid()
if not cache:
log.error('No cache to attach %s to', dev)
return False
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = attach_(dev)
return res if res else None
bcache = uuid(dev)
if bcache:
if bcache == cache:
log.info('%s is already attached to bcache %s, doing nothing', dev, cache)
return None
elif not detach(dev):
return False
log.debug('Attaching %s to bcache %s', dev, cache)
if not _bcsys(dev, 'attach', cache,
'error', 'Error attaching {0} to bcache {1}'.format(dev, cache)):
return False
return _wait(lambda: uuid(dev) == cache,
'error', '{0} received attach to bcache {1}, but did not comply'.format(dev, cache))
def detach(dev=None):
'''
Detach a backing device(s) from a cache set
If no dev is given, all backing devices will be attached.
Detaching a backing device will flush it's write cache.
This should leave the underlying device in a consistent state, but might take a while.
CLI example:
.. code-block:: bash
salt '*' bcache.detach sdc
salt '*' bcache.detach bcache1
'''
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = detach(dev)
return res if res else None
log.debug('Detaching %s', dev)
if not _bcsys(dev, 'detach', 'goaway', 'error', 'Error detaching {0}'.format(dev)):
return False
return _wait(lambda: uuid(dev) is False, 'error', '{0} received detach, but did not comply'.format(dev), 300)
def start():
'''
Trigger a start of the full bcache system through udev.
CLI example:
.. code-block:: bash
salt '*' bcache.start
'''
if not _run_all('udevadm trigger', 'error', 'Error starting bcache: %s'):
return False
elif not _wait(lambda: uuid() is not False, 'warn', 'Bcache system started, but no active cache set found.'):
return False
return True
def stop(dev=None):
'''
Stop a bcache device
If no device is given, all backing devices will be detached from the cache, which will subsequently be stopped.
.. warning::
'Stop' on an individual backing device means hard-stop;
no attempt at flushing will be done and the bcache device will seemingly 'disappear' from the device lists
CLI example:
.. code-block:: bash
salt '*' bcache.stop
'''
if dev is not None:
log.warning('Stopping %s, device will only reappear after reregistering!', dev)
if not _bcsys(dev, 'stop', 'goaway', 'error', 'Error stopping {0}'.format(dev)):
return False
return _wait(lambda: _sysfs_attr(_bcpath(dev)) is False, 'error', 'Device {0} did not stop'.format(dev), 300)
else:
cache = uuid()
if not cache:
log.warning('bcache already stopped?')
return None
if not _alltrue(detach()):
return False
elif not _fssys('stop', 'goaway', 'error', 'Error stopping cache'):
return False
return _wait(lambda: uuid() is False, 'error', 'Cache did not stop', 300)
def back_make(dev, cache_mode='writeback', force=False, attach=True, bucket_size=None):
'''
Create a backing device for attachment to a set.
Because the block size must be the same, a cache set already needs to exist.
CLI example:
.. code-block:: bash
salt '*' bcache.back_make sdc cache_mode=writeback attach=True
:param cache_mode: writethrough, writeback, writearound or none.
:param force: Overwrite existing bcaches
:param attach: Immediately attach the backing device to the set
:param bucket_size: Size of a bucket (see kernel doc)
'''
# pylint: disable=too-many-return-statements
cache = uuid()
if not cache:
log.error('No bcache set found')
return False
elif _sysfs_attr(_bcpath(dev)):
if not force:
log.error('%s already contains a bcache. Wipe it manually or use force', dev)
return False
elif uuid(dev) and not detach(dev):
return False
elif not stop(dev):
return False
dev = _devpath(dev)
block_size = _size_map(_fssys('block_size'))
# You might want to override, we pick the cache set's as sane default
if bucket_size is None:
bucket_size = _size_map(_fssys('bucket_size'))
cmd = 'make-bcache --block {0} --bucket {1} --{2} --bdev {3}'.format(block_size, bucket_size, cache_mode, dev)
if force:
cmd += ' --wipe-bcache'
if not _run_all(cmd, 'error', 'Error creating backing device {0}: %s'.format(dev)):
return False
elif not _sysfs_attr('fs/bcache/register', _devpath(dev),
'error', 'Error registering backing device {0}'.format(dev)):
return False
elif not _wait(lambda: _sysfs_attr(_bcpath(dev)) is not False,
'error', 'Backing device {0} did not register'.format(dev)):
return False
elif attach:
return attach_(dev)
return True
def cache_make(dev, reserved=None, force=False, block_size=None, bucket_size=None, attach=True):
'''
Create BCache cache on a block device.
If blkdiscard is available the entire device will be properly cleared in advance.
CLI example:
.. code-block:: bash
salt '*' bcache.cache_make sdb reserved=10% block_size=4096
:param reserved: if dev is a full device, create a partition table with this size empty.
.. note::
this increases the amount of reserved space available to SSD garbage collectors,
potentially (vastly) increasing performance
:param block_size: Block size of the cache; defaults to devices' logical block size
:param force: Overwrite existing BCache sets
:param attach: Attach all existing backend devices immediately
'''
# TODO: multiple devs == md jbod
# pylint: disable=too-many-return-statements
# ---------------- Preflight checks ----------------
cache = uuid()
if cache:
if not force:
log.error('BCache cache %s is already on the system', cache)
return False
cache = _bdev()
dev = _devbase(dev)
udev = __salt__['udev.env'](dev)
if ('ID_FS_TYPE' in udev or (udev.get('DEVTYPE', None) != 'partition' and 'ID_PART_TABLE_TYPE' in udev)) \
and not force:
log.error('%s already contains data, wipe first or force', dev)
return False
elif reserved is not None and udev.get('DEVTYPE', None) != 'disk':
log.error('Need a partitionable blockdev for reserved to work')
return False
_, block, bucket = _sizes(dev)
if bucket_size is None:
bucket_size = bucket
# TODO: bucket from _sizes() makes no sense
bucket_size = False
if block_size is None:
block_size = block
# ---------------- Still here, start doing destructive stuff ----------------
if cache:
if not stop():
return False
# Wipe the current cache device as well,
# forever ruining any chance of it accidentally popping up again
elif not _wipe(cache):
return False
# Can't do enough wiping
if not _wipe(dev):
return False
if reserved:
cmd = 'parted -m -s -a optimal -- ' \
'/dev/{0} mklabel gpt mkpart bcache-reserved 1M {1} mkpart bcache {1} 100%'.format(dev, reserved)
# if wipe was incomplete & part layout remains the same,
# this is one condition set where udev would make it accidentally popup again
if not _run_all(cmd, 'error', 'Error creating bcache partitions on {0}: %s'.format(dev)):
return False
dev = '{0}2'.format(dev)
# ---------------- Finally, create a cache ----------------
cmd = 'make-bcache --cache /dev/{0} --block {1} --wipe-bcache'.format(dev, block_size)
# Actually bucket_size should always have a value, but for testing 0 is possible as well
if bucket_size:
cmd += ' --bucket {0}'.format(bucket_size)
if not _run_all(cmd, 'error', 'Error creating cache {0}: %s'.format(dev)):
return False
elif not _wait(lambda: uuid() is not False,
'error', 'Cache {0} seemingly created OK, but FS did not activate'.format(dev)):
return False
if attach:
return _alltrue(attach_())
else:
return True
def config_(dev=None, **kwargs):
'''
Show or update config of a bcache device.
If no device is given, operate on the cache set itself.
CLI example:
.. code-block:: bash
salt '*' bcache.config
salt '*' bcache.config bcache1
salt '*' bcache.config errors=panic journal_delay_ms=150
salt '*' bcache.config bcache1 cache_mode=writeback writeback_percent=15
:return: config or True/False
'''
if dev is None:
spath = _fspath()
else:
spath = _bcpath(dev)
# filter out 'hidden' kwargs added by our favourite orchestration system
updates = dict([(key, val) for key, val in kwargs.items() if not key.startswith('__')])
if updates:
endres = 0
for key, val in updates.items():
endres += _sysfs_attr([spath, key], val,
'warn', 'Failed to update {0} with {1}'.format(os.path.join(spath, key), val))
return endres > 0
else:
result = {}
data = _sysfs_parse(spath, config=True, internals=True, options=True)
for key in ('other_ro', 'inter_ro'):
if key in data:
del data[key]
for key in data:
result.update(data[key])
return result
def status(stats=False, config=False, internals=False, superblock=False, alldevs=False):
'''
Show the full status of the BCache system and optionally all it's involved devices
CLI example:
.. code-block:: bash
salt '*' bcache.status
salt '*' bcache.status stats=True
salt '*' bcache.status internals=True alldevs=True
:param stats: include statistics
:param config: include settings
:param internals: include internals
:param superblock: include superblock
'''
bdevs = []
for _, links, _ in salt.utils.path.os_walk('/sys/block/'):
for block in links:
if 'bcache' in block:
continue
for spath, sdirs, _ in salt.utils.path.os_walk('/sys/block/{0}'.format(block), followlinks=False):
if 'bcache' in sdirs:
bdevs.append(os.path.basename(spath))
statii = {}
for bcache in bdevs:
statii[bcache] = device(bcache, stats, config, internals, superblock)
cuuid = uuid()
cdev = _bdev()
if cdev:
count = 0
for dev in statii:
if dev != cdev:
# it's a backing dev
if statii[dev]['cache'] == cuuid:
count += 1
statii[cdev]['attached_backing_devices'] = count
if not alldevs:
statii = statii[cdev]
return statii
def device(dev, stats=False, config=False, internals=False, superblock=False):
'''
Check the state of a single bcache device
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc stats=True
:param stats: include statistics
:param settings: include all settings
:param internals: include all internals
:param superblock: include superblock info
'''
result = {}
if not _sysfs_attr(_bcpath(dev), None, 'error', '{0} is not a bcache fo any kind'.format(dev)):
return False
elif _bcsys(dev, 'set'):
# ---------------- It's the cache itself ----------------
result['uuid'] = uuid()
base_attr = ['block_size', 'bucket_size', 'cache_available_percent', 'cache_replacement_policy', 'congested']
# ---------------- Parse through both the blockdev & the FS ----------------
result.update(_sysfs_parse(_bcpath(dev), base_attr, stats, config, internals))
result.update(_sysfs_parse(_fspath(), base_attr, stats, config, internals))
result.update(result.pop('base'))
else:
# ---------------- It's a backing device ----------------
back_uuid = uuid(dev)
if back_uuid is not None:
result['cache'] = back_uuid
try:
result['dev'] = os.path.basename(_bcsys(dev, 'dev'))
except Exception:
pass
result['bdev'] = _bdev(dev)
base_attr = ['cache_mode', 'running', 'state', 'writeback_running']
base_path = _bcpath(dev)
result.update(_sysfs_parse(base_path, base_attr, stats, config, internals))
result.update(result.pop('base'))
# ---------------- Modifications ----------------
state = [result['state']]
if result.pop('running'):
state.append('running')
else:
state.append('stopped')
if 'writeback_running' in result:
if result.pop('writeback_running'):
state.append('writeback_running')
else:
state.append('writeback_stopped')
result['state'] = state
# ---------------- Statistics ----------------
if 'stats' in result:
replre = r'(stats|cache)_'
statres = result['stats']
for attr in result['stats']:
if '/' not in attr:
key = re.sub(replre, '', attr)
statres[key] = statres.pop(attr)
else:
stat, key = attr.split('/', 1)
stat = re.sub(replre, '', stat)
key = re.sub(replre, '', key)
if stat not in statres:
statres[stat] = {}
statres[stat][key] = statres.pop(attr)
result['stats'] = statres
# ---------------- Internals ----------------
if internals:
interres = result.pop('inter_ro', {})
interres.update(result.pop('inter_rw', {}))
if interres:
for key in interres:
if key.startswith('internal'):
nkey = re.sub(r'internal[s/]*', '', key)
interres[nkey] = interres.pop(key)
key = nkey
if key.startswith(('btree', 'writeback')):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in interres:
interres[mkey] = {}
interres[mkey][skey] = interres.pop(key)
result['internals'] = interres
# ---------------- Config ----------------
if config:
configres = result['config']
for key in configres:
if key.startswith('writeback'):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in configres:
configres[mkey] = {}
configres[mkey][skey] = configres.pop(key)
result['config'] = configres
# ---------------- Superblock ----------------
if superblock:
result['superblock'] = super_(dev)
return result
def super_(dev):
'''
Read out BCache SuperBlock
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc
'''
dev = _devpath(dev)
ret = {}
res = _run_all('bcache-super-show {0}'.format(dev), 'error', 'Error reading superblock on {0}: %s'.format(dev))
if not res:
return False
for line in res.splitlines(): # pylint: disable=no-member
line = line.strip()
if not line:
continue
key, val = [val.strip() for val in re.split(r'[\s]+', line, maxsplit=1)]
if not (key and val):
continue
mval = None
if ' ' in val:
rval, mval = [val.strip() for val in re.split(r'[\s]+', val, maxsplit=1)]
mval = mval[1:-1]
else:
rval = val
try:
rval = int(rval)
except Exception:
try:
rval = float(rval)
except Exception:
if rval == 'yes':
rval = True
elif rval == 'no':
rval = False
pkey, key = re.split(r'\.', key, maxsplit=1)
if pkey not in ret:
ret[pkey] = {}
if mval is not None:
ret[pkey][key] = (rval, mval)
else:
ret[pkey][key] = rval
return ret
# -------------------------------- HELPER FUNCTIONS --------------------------------
def _devbase(dev):
'''
Basename of just about any dev
'''
dev = os.path.realpath(os.path.expandvars(dev))
dev = os.path.basename(dev)
return dev
def _devpath(dev):
'''
Return /dev name of just about any dev
:return: /dev/devicename
'''
return os.path.join('/dev', _devbase(dev))
def _syspath(dev):
'''
Full SysFS path of a device
'''
dev = _devbase(dev)
dev = re.sub(r'^([vhs][a-z]+)([0-9]+)', r'\1/\1\2', dev)
# name = re.sub(r'^([a-z]+)(?<!(bcache|md|dm))([0-9]+)', r'\1/\1\2', name)
return os.path.join('/sys/block/', dev)
def _bdev(dev=None):
'''
Resolve a bcacheX or cache to a real dev
:return: basename of bcache dev
'''
if dev is None:
dev = _fssys('cache0')
else:
dev = _bcpath(dev)
if not dev:
return False
else:
return _devbase(os.path.dirname(dev))
def _bcpath(dev):
'''
Full SysFS path of a bcache device
'''
return os.path.join(_syspath(dev), 'bcache')
def _fspath():
'''
:return: path of active bcache
'''
cuuid = uuid()
if not cuuid:
return False
else:
return os.path.join('/sys/fs/bcache/', cuuid)
def _fssys(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with bcache SysFS
'''
fspath = _fspath()
if not fspath:
return False
else:
return _sysfs_attr([fspath, name], value, log_lvl, log_msg)
def _bcsys(dev, name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with backing devs SysFS
'''
return _sysfs_attr([_bcpath(dev), name], value, log_lvl, log_msg)
def _sysfs_attr(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper with logging around sysfs.attr
'''
if isinstance(name, six.string_types):
name = [name]
res = __salt__['sysfs.attr'](os.path.join(*name), value)
if not res and log_lvl is not None and log_msg is not None:
log.log(LOG[log_lvl], log_msg)
return res
def _sysfs_parse(path, base_attr=None, stats=False, config=False, internals=False, options=False):
'''
Helper function for parsing BCache's SysFS interface
'''
result = {}
# ---------------- Parse through the interfaces list ----------------
intfs = __salt__['sysfs.interfaces'](path)
# Actions, we ignore
del intfs['w']
# -------- Sorting hat --------
binkeys = []
if internals:
binkeys.extend(['inter_ro', 'inter_rw'])
if config:
binkeys.append('config')
if stats:
binkeys.append('stats')
bintf = {}
for key in binkeys:
bintf[key] = []
for intf in intfs['r']:
if intf.startswith('internal'):
key = 'inter_ro'
elif 'stats' in intf:
key = 'stats'
else:
# What to do with these???
# I'll utilize 'inter_ro' as 'misc' as well
key = 'inter_ro'
if key in bintf:
bintf[key].append(intf)
for intf in intfs['rw']:
if intf.startswith('internal'):
key = 'inter_rw'
else:
key = 'config'
if key in bintf:
bintf[key].append(intf)
if base_attr is not None:
for intf in bintf:
bintf[intf] = [sintf for sintf in bintf[intf] if sintf not in base_attr]
bintf['base'] = base_attr
mods = {
'stats': ['internal/bset_tree_stats', 'writeback_rate_debug', 'metadata_written', 'nbuckets', 'written',
'average_key_size', 'btree_cache_size'],
}
for modt, modlist in mods.items():
found = []
if modt not in bintf:
continue
for mod in modlist:
for intflist in bintf.values():
if mod in intflist:
found.append(mod)
intflist.remove(mod)
bintf[modt] += found
# -------- Fetch SysFS vals --------
bintflist = [intf for iflist in bintf.values() for intf in iflist]
result.update(__salt__['sysfs.read'](bintflist, path))
# -------- Parse through well known string lists --------
for strlist in ('writeback_rate_debug', 'internal/bset_tree_stats', 'priority_stats'):
if strlist in result:
listres = {}
for line in result[strlist].split('\n'):
key, val = line.split(':', 1)
val = val.strip()
try:
val = int(val)
except Exception:
try:
val = float(val)
except Exception:
pass
listres[key.strip()] = val
result[strlist] = listres
# -------- Parse through selection lists --------
if not options:
for sellist in ('cache_mode', 'cache_replacement_policy', 'errors'):
if sellist in result:
result[sellist] = re.search(r'\[(.+)\]', result[sellist]).groups()[0]
# -------- Parse through well known bools --------
for boolkey in ('running', 'writeback_running', 'congested'):
if boolkey in result:
result[boolkey] = bool(result[boolkey])
# -------- Recategorize results --------
bresult = {}
for iftype, intflist in bintf.items():
ifres = {}
for intf in intflist:
if intf in result:
ifres[intf] = result.pop(intf)
if ifres:
bresult[iftype] = ifres
return bresult
def _size_map(size):
'''
Map Bcache's size strings to real bytes
'''
try:
# I know, I know, EAFP.
# But everything else is reason for None
if not isinstance(size, int):
if re.search(r'[Kk]', size):
size = 1024 * float(re.sub(r'[Kk]', '', size))
elif re.search(r'[Mm]', size):
size = 1024**2 * float(re.sub(r'[Mm]', '', size))
size = int(size)
return size
except Exception:
return None
def _sizes(dev):
'''
Return neigh useless sizing info about a blockdev
:return: (total size in blocks, blocksize, maximum discard size in bytes)
'''
dev = _devbase(dev)
# standarization yay
block_sizes = ('hw_sector_size', 'minimum_io_size', 'physical_block_size', 'logical_block_size')
discard_sizes = ('discard_max_bytes', 'discard_max_hw_bytes', )
sysfs = __salt__['sysfs.read'](
('size',
'queue/hw_sector_size', '../queue/hw_sector_size',
'queue/discard_max_bytes', '../queue/discard_max_bytes'),
root=_syspath(dev))
# TODO: makes no sense
# First of all, it has to be a power of 2
# Secondly, this returns 4GiB - 512b on Intel 3500's for some weird reason
# discard_granularity seems in bytes, resolves to 512b ???
# max_hw_sectors_kb???
# There's also discard_max_hw_bytes more recently
# See: https://www.kernel.org/doc/Documentation/block/queue-sysfs.txt
# Also, I cant find any docs yet regarding bucket sizes;
# it's supposed to be discard_max_hw_bytes,
# but no way to figure that one reliably out apparently
discard = sysfs.get('queue/discard_max_bytes', sysfs.get('../queue/discard_max_bytes', None))
block = sysfs.get('queue/hw_sector_size', sysfs.get('../queue/hw_sector_size', None))
return 512*sysfs['size'], block, discard
def _wipe(dev):
'''
REALLY DESTRUCTIVE STUFF RIGHT AHEAD
'''
endres = 0
dev = _devbase(dev)
size, block, discard = _sizes(dev)
if discard is None:
log.error('Unable to read SysFS props for %s', dev)
return None
elif not discard:
log.warning('%s seems unable to discard', dev)
wiper = 'dd'
elif not HAS_BLKDISCARD:
log.warning('blkdiscard binary not available, properly wipe the dev manually for optimal results')
wiper = 'dd'
else:
wiper = 'blkdiscard'
wipe_failmsg = 'Error wiping {0}: %s'.format(dev)
if wiper == 'dd':
blocks = 4
cmd = 'dd if=/dev/zero of=/dev/{0} bs=1M count={1}'.format(dev, blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# Some stuff (<cough>GPT</cough>) writes stuff at the end of a dev as well
cmd += ' seek={0}'.format((size/1024**2) - blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
elif wiper == 'blkdiscard':
cmd = 'blkdiscard /dev/{0}'.format(dev)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# TODO: fix annoying bug failing blkdiscard by trying to discard 1 sector past blkdev
endres = 1
return endres > 0
def _wait(lfunc, log_lvl=None, log_msg=None, tries=10):
'''
Wait for lfunc to be True
:return: True if lfunc succeeded within tries, False if it didn't
'''
i = 0
while i < tries:
time.sleep(1)
if lfunc():
return True
else:
i += 1
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg)
return False
def _run_all(cmd, log_lvl=None, log_msg=None, exitcode=0):
'''
Simple wrapper around cmd.run_all
log_msg can contain {0} for stderr
:return: True or stdout, False if retcode wasn't exitcode
'''
res = __salt__['cmd.run_all'](cmd)
if res['retcode'] == exitcode:
if res['stdout']:
return res['stdout']
else:
return True
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg, res['stderr'])
return False
def _alltrue(resdict):
if resdict is None:
return True
return len([val for val in resdict.values() if val]) > 0
|
saltstack/salt
|
salt/modules/bcache.py
|
attach_
|
python
|
def attach_(dev=None):
'''
Attach a backing devices to a cache set
If no dev is given, all backing devices will be attached.
CLI example:
.. code-block:: bash
salt '*' bcache.attach sdc
salt '*' bcache.attach /dev/bcache1
:return: bool or None if nuttin' happened
'''
cache = uuid()
if not cache:
log.error('No cache to attach %s to', dev)
return False
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = attach_(dev)
return res if res else None
bcache = uuid(dev)
if bcache:
if bcache == cache:
log.info('%s is already attached to bcache %s, doing nothing', dev, cache)
return None
elif not detach(dev):
return False
log.debug('Attaching %s to bcache %s', dev, cache)
if not _bcsys(dev, 'attach', cache,
'error', 'Error attaching {0} to bcache {1}'.format(dev, cache)):
return False
return _wait(lambda: uuid(dev) == cache,
'error', '{0} received attach to bcache {1}, but did not comply'.format(dev, cache))
|
Attach a backing devices to a cache set
If no dev is given, all backing devices will be attached.
CLI example:
.. code-block:: bash
salt '*' bcache.attach sdc
salt '*' bcache.attach /dev/bcache1
:return: bool or None if nuttin' happened
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bcache.py#L82-L125
|
[
"def detach(dev=None):\n '''\n Detach a backing device(s) from a cache set\n If no dev is given, all backing devices will be attached.\n\n Detaching a backing device will flush it's write cache.\n This should leave the underlying device in a consistent state, but might take a while.\n\n CLI example:\n\n .. code-block:: bash\n\n salt '*' bcache.detach sdc\n salt '*' bcache.detach bcache1\n\n '''\n if dev is None:\n res = {}\n for dev, data in status(alldevs=True).items():\n if 'cache' in data:\n res[dev] = detach(dev)\n\n return res if res else None\n\n log.debug('Detaching %s', dev)\n if not _bcsys(dev, 'detach', 'goaway', 'error', 'Error detaching {0}'.format(dev)):\n return False\n return _wait(lambda: uuid(dev) is False, 'error', '{0} received detach, but did not comply'.format(dev), 300)\n",
"def status(stats=False, config=False, internals=False, superblock=False, alldevs=False):\n '''\n Show the full status of the BCache system and optionally all it's involved devices\n\n CLI example:\n\n .. code-block:: bash\n\n salt '*' bcache.status\n salt '*' bcache.status stats=True\n salt '*' bcache.status internals=True alldevs=True\n\n :param stats: include statistics\n :param config: include settings\n :param internals: include internals\n :param superblock: include superblock\n '''\n bdevs = []\n for _, links, _ in salt.utils.path.os_walk('/sys/block/'):\n for block in links:\n if 'bcache' in block:\n continue\n\n for spath, sdirs, _ in salt.utils.path.os_walk('/sys/block/{0}'.format(block), followlinks=False):\n if 'bcache' in sdirs:\n bdevs.append(os.path.basename(spath))\n statii = {}\n for bcache in bdevs:\n statii[bcache] = device(bcache, stats, config, internals, superblock)\n\n cuuid = uuid()\n cdev = _bdev()\n if cdev:\n count = 0\n for dev in statii:\n if dev != cdev:\n # it's a backing dev\n if statii[dev]['cache'] == cuuid:\n count += 1\n statii[cdev]['attached_backing_devices'] = count\n\n if not alldevs:\n statii = statii[cdev]\n\n return statii\n",
"def uuid(dev=None):\n '''\n Return the bcache UUID of a block device.\n If no device is given, the Cache UUID is returned.\n\n CLI example:\n\n .. code-block:: bash\n\n salt '*' bcache.uuid\n salt '*' bcache.uuid /dev/sda\n salt '*' bcache.uuid bcache0\n\n '''\n try:\n if dev is None:\n # take the only directory in /sys/fs/bcache and return it's basename\n return list(salt.utils.path.os_walk('/sys/fs/bcache/'))[0][1][0]\n else:\n # basename of the /sys/block/{dev}/bcache/cache symlink target\n return os.path.basename(_bcsys(dev, 'cache'))\n except Exception:\n return False\n",
"def _wait(lfunc, log_lvl=None, log_msg=None, tries=10):\n '''\n Wait for lfunc to be True\n :return: True if lfunc succeeded within tries, False if it didn't\n '''\n i = 0\n while i < tries:\n time.sleep(1)\n\n if lfunc():\n return True\n else:\n i += 1\n if log_lvl is not None:\n log.log(LOG[log_lvl], log_msg)\n return False\n",
"def attach_(dev=None):\n '''\n Attach a backing devices to a cache set\n If no dev is given, all backing devices will be attached.\n\n CLI example:\n\n .. code-block:: bash\n\n salt '*' bcache.attach sdc\n salt '*' bcache.attach /dev/bcache1\n\n\n :return: bool or None if nuttin' happened\n '''\n cache = uuid()\n if not cache:\n log.error('No cache to attach %s to', dev)\n return False\n\n if dev is None:\n res = {}\n for dev, data in status(alldevs=True).items():\n if 'cache' in data:\n res[dev] = attach_(dev)\n\n return res if res else None\n\n bcache = uuid(dev)\n if bcache:\n if bcache == cache:\n log.info('%s is already attached to bcache %s, doing nothing', dev, cache)\n return None\n elif not detach(dev):\n return False\n\n log.debug('Attaching %s to bcache %s', dev, cache)\n\n if not _bcsys(dev, 'attach', cache,\n 'error', 'Error attaching {0} to bcache {1}'.format(dev, cache)):\n return False\n\n return _wait(lambda: uuid(dev) == cache,\n 'error', '{0} received attach to bcache {1}, but did not comply'.format(dev, cache))\n",
"def _bcsys(dev, name, value=None, log_lvl=None, log_msg=None):\n '''\n Simple wrapper to interface with backing devs SysFS\n '''\n return _sysfs_attr([_bcpath(dev), name], value, log_lvl, log_msg)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for managing BCache sets
BCache is a block-level caching mechanism similar to ZFS L2ARC/ZIL, dm-cache and fscache.
It works by formatting one block device as a cache set, then adding backend devices
(which need to be formatted as such) to the set and activating them.
It's available in Linux mainline kernel since 3.10
https://www.kernel.org/doc/Documentation/bcache.txt
This module needs the bcache userspace tools to function.
.. versionadded: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import time
import re
from salt.ext import six
# Import salt libs
import salt.utils.path
log = logging.getLogger(__name__)
LOG = {
'trace': logging.TRACE,
'debug': logging.DEBUG,
'info': logging.INFO,
'warn': logging.WARNING,
'error': logging.ERROR,
'crit': logging.CRITICAL,
}
__func_alias__ = {
'attach_': 'attach',
'config_': 'config',
'super_': 'super',
}
HAS_BLKDISCARD = salt.utils.path.which('blkdiscard') is not None
def __virtual__():
'''
Only work when make-bcache is installed
'''
return salt.utils.path.which('make-bcache') is not None
def uuid(dev=None):
'''
Return the bcache UUID of a block device.
If no device is given, the Cache UUID is returned.
CLI example:
.. code-block:: bash
salt '*' bcache.uuid
salt '*' bcache.uuid /dev/sda
salt '*' bcache.uuid bcache0
'''
try:
if dev is None:
# take the only directory in /sys/fs/bcache and return it's basename
return list(salt.utils.path.os_walk('/sys/fs/bcache/'))[0][1][0]
else:
# basename of the /sys/block/{dev}/bcache/cache symlink target
return os.path.basename(_bcsys(dev, 'cache'))
except Exception:
return False
def detach(dev=None):
'''
Detach a backing device(s) from a cache set
If no dev is given, all backing devices will be attached.
Detaching a backing device will flush it's write cache.
This should leave the underlying device in a consistent state, but might take a while.
CLI example:
.. code-block:: bash
salt '*' bcache.detach sdc
salt '*' bcache.detach bcache1
'''
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = detach(dev)
return res if res else None
log.debug('Detaching %s', dev)
if not _bcsys(dev, 'detach', 'goaway', 'error', 'Error detaching {0}'.format(dev)):
return False
return _wait(lambda: uuid(dev) is False, 'error', '{0} received detach, but did not comply'.format(dev), 300)
def start():
'''
Trigger a start of the full bcache system through udev.
CLI example:
.. code-block:: bash
salt '*' bcache.start
'''
if not _run_all('udevadm trigger', 'error', 'Error starting bcache: %s'):
return False
elif not _wait(lambda: uuid() is not False, 'warn', 'Bcache system started, but no active cache set found.'):
return False
return True
def stop(dev=None):
'''
Stop a bcache device
If no device is given, all backing devices will be detached from the cache, which will subsequently be stopped.
.. warning::
'Stop' on an individual backing device means hard-stop;
no attempt at flushing will be done and the bcache device will seemingly 'disappear' from the device lists
CLI example:
.. code-block:: bash
salt '*' bcache.stop
'''
if dev is not None:
log.warning('Stopping %s, device will only reappear after reregistering!', dev)
if not _bcsys(dev, 'stop', 'goaway', 'error', 'Error stopping {0}'.format(dev)):
return False
return _wait(lambda: _sysfs_attr(_bcpath(dev)) is False, 'error', 'Device {0} did not stop'.format(dev), 300)
else:
cache = uuid()
if not cache:
log.warning('bcache already stopped?')
return None
if not _alltrue(detach()):
return False
elif not _fssys('stop', 'goaway', 'error', 'Error stopping cache'):
return False
return _wait(lambda: uuid() is False, 'error', 'Cache did not stop', 300)
def back_make(dev, cache_mode='writeback', force=False, attach=True, bucket_size=None):
'''
Create a backing device for attachment to a set.
Because the block size must be the same, a cache set already needs to exist.
CLI example:
.. code-block:: bash
salt '*' bcache.back_make sdc cache_mode=writeback attach=True
:param cache_mode: writethrough, writeback, writearound or none.
:param force: Overwrite existing bcaches
:param attach: Immediately attach the backing device to the set
:param bucket_size: Size of a bucket (see kernel doc)
'''
# pylint: disable=too-many-return-statements
cache = uuid()
if not cache:
log.error('No bcache set found')
return False
elif _sysfs_attr(_bcpath(dev)):
if not force:
log.error('%s already contains a bcache. Wipe it manually or use force', dev)
return False
elif uuid(dev) and not detach(dev):
return False
elif not stop(dev):
return False
dev = _devpath(dev)
block_size = _size_map(_fssys('block_size'))
# You might want to override, we pick the cache set's as sane default
if bucket_size is None:
bucket_size = _size_map(_fssys('bucket_size'))
cmd = 'make-bcache --block {0} --bucket {1} --{2} --bdev {3}'.format(block_size, bucket_size, cache_mode, dev)
if force:
cmd += ' --wipe-bcache'
if not _run_all(cmd, 'error', 'Error creating backing device {0}: %s'.format(dev)):
return False
elif not _sysfs_attr('fs/bcache/register', _devpath(dev),
'error', 'Error registering backing device {0}'.format(dev)):
return False
elif not _wait(lambda: _sysfs_attr(_bcpath(dev)) is not False,
'error', 'Backing device {0} did not register'.format(dev)):
return False
elif attach:
return attach_(dev)
return True
def cache_make(dev, reserved=None, force=False, block_size=None, bucket_size=None, attach=True):
'''
Create BCache cache on a block device.
If blkdiscard is available the entire device will be properly cleared in advance.
CLI example:
.. code-block:: bash
salt '*' bcache.cache_make sdb reserved=10% block_size=4096
:param reserved: if dev is a full device, create a partition table with this size empty.
.. note::
this increases the amount of reserved space available to SSD garbage collectors,
potentially (vastly) increasing performance
:param block_size: Block size of the cache; defaults to devices' logical block size
:param force: Overwrite existing BCache sets
:param attach: Attach all existing backend devices immediately
'''
# TODO: multiple devs == md jbod
# pylint: disable=too-many-return-statements
# ---------------- Preflight checks ----------------
cache = uuid()
if cache:
if not force:
log.error('BCache cache %s is already on the system', cache)
return False
cache = _bdev()
dev = _devbase(dev)
udev = __salt__['udev.env'](dev)
if ('ID_FS_TYPE' in udev or (udev.get('DEVTYPE', None) != 'partition' and 'ID_PART_TABLE_TYPE' in udev)) \
and not force:
log.error('%s already contains data, wipe first or force', dev)
return False
elif reserved is not None and udev.get('DEVTYPE', None) != 'disk':
log.error('Need a partitionable blockdev for reserved to work')
return False
_, block, bucket = _sizes(dev)
if bucket_size is None:
bucket_size = bucket
# TODO: bucket from _sizes() makes no sense
bucket_size = False
if block_size is None:
block_size = block
# ---------------- Still here, start doing destructive stuff ----------------
if cache:
if not stop():
return False
# Wipe the current cache device as well,
# forever ruining any chance of it accidentally popping up again
elif not _wipe(cache):
return False
# Can't do enough wiping
if not _wipe(dev):
return False
if reserved:
cmd = 'parted -m -s -a optimal -- ' \
'/dev/{0} mklabel gpt mkpart bcache-reserved 1M {1} mkpart bcache {1} 100%'.format(dev, reserved)
# if wipe was incomplete & part layout remains the same,
# this is one condition set where udev would make it accidentally popup again
if not _run_all(cmd, 'error', 'Error creating bcache partitions on {0}: %s'.format(dev)):
return False
dev = '{0}2'.format(dev)
# ---------------- Finally, create a cache ----------------
cmd = 'make-bcache --cache /dev/{0} --block {1} --wipe-bcache'.format(dev, block_size)
# Actually bucket_size should always have a value, but for testing 0 is possible as well
if bucket_size:
cmd += ' --bucket {0}'.format(bucket_size)
if not _run_all(cmd, 'error', 'Error creating cache {0}: %s'.format(dev)):
return False
elif not _wait(lambda: uuid() is not False,
'error', 'Cache {0} seemingly created OK, but FS did not activate'.format(dev)):
return False
if attach:
return _alltrue(attach_())
else:
return True
def config_(dev=None, **kwargs):
'''
Show or update config of a bcache device.
If no device is given, operate on the cache set itself.
CLI example:
.. code-block:: bash
salt '*' bcache.config
salt '*' bcache.config bcache1
salt '*' bcache.config errors=panic journal_delay_ms=150
salt '*' bcache.config bcache1 cache_mode=writeback writeback_percent=15
:return: config or True/False
'''
if dev is None:
spath = _fspath()
else:
spath = _bcpath(dev)
# filter out 'hidden' kwargs added by our favourite orchestration system
updates = dict([(key, val) for key, val in kwargs.items() if not key.startswith('__')])
if updates:
endres = 0
for key, val in updates.items():
endres += _sysfs_attr([spath, key], val,
'warn', 'Failed to update {0} with {1}'.format(os.path.join(spath, key), val))
return endres > 0
else:
result = {}
data = _sysfs_parse(spath, config=True, internals=True, options=True)
for key in ('other_ro', 'inter_ro'):
if key in data:
del data[key]
for key in data:
result.update(data[key])
return result
def status(stats=False, config=False, internals=False, superblock=False, alldevs=False):
'''
Show the full status of the BCache system and optionally all it's involved devices
CLI example:
.. code-block:: bash
salt '*' bcache.status
salt '*' bcache.status stats=True
salt '*' bcache.status internals=True alldevs=True
:param stats: include statistics
:param config: include settings
:param internals: include internals
:param superblock: include superblock
'''
bdevs = []
for _, links, _ in salt.utils.path.os_walk('/sys/block/'):
for block in links:
if 'bcache' in block:
continue
for spath, sdirs, _ in salt.utils.path.os_walk('/sys/block/{0}'.format(block), followlinks=False):
if 'bcache' in sdirs:
bdevs.append(os.path.basename(spath))
statii = {}
for bcache in bdevs:
statii[bcache] = device(bcache, stats, config, internals, superblock)
cuuid = uuid()
cdev = _bdev()
if cdev:
count = 0
for dev in statii:
if dev != cdev:
# it's a backing dev
if statii[dev]['cache'] == cuuid:
count += 1
statii[cdev]['attached_backing_devices'] = count
if not alldevs:
statii = statii[cdev]
return statii
def device(dev, stats=False, config=False, internals=False, superblock=False):
'''
Check the state of a single bcache device
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc stats=True
:param stats: include statistics
:param settings: include all settings
:param internals: include all internals
:param superblock: include superblock info
'''
result = {}
if not _sysfs_attr(_bcpath(dev), None, 'error', '{0} is not a bcache fo any kind'.format(dev)):
return False
elif _bcsys(dev, 'set'):
# ---------------- It's the cache itself ----------------
result['uuid'] = uuid()
base_attr = ['block_size', 'bucket_size', 'cache_available_percent', 'cache_replacement_policy', 'congested']
# ---------------- Parse through both the blockdev & the FS ----------------
result.update(_sysfs_parse(_bcpath(dev), base_attr, stats, config, internals))
result.update(_sysfs_parse(_fspath(), base_attr, stats, config, internals))
result.update(result.pop('base'))
else:
# ---------------- It's a backing device ----------------
back_uuid = uuid(dev)
if back_uuid is not None:
result['cache'] = back_uuid
try:
result['dev'] = os.path.basename(_bcsys(dev, 'dev'))
except Exception:
pass
result['bdev'] = _bdev(dev)
base_attr = ['cache_mode', 'running', 'state', 'writeback_running']
base_path = _bcpath(dev)
result.update(_sysfs_parse(base_path, base_attr, stats, config, internals))
result.update(result.pop('base'))
# ---------------- Modifications ----------------
state = [result['state']]
if result.pop('running'):
state.append('running')
else:
state.append('stopped')
if 'writeback_running' in result:
if result.pop('writeback_running'):
state.append('writeback_running')
else:
state.append('writeback_stopped')
result['state'] = state
# ---------------- Statistics ----------------
if 'stats' in result:
replre = r'(stats|cache)_'
statres = result['stats']
for attr in result['stats']:
if '/' not in attr:
key = re.sub(replre, '', attr)
statres[key] = statres.pop(attr)
else:
stat, key = attr.split('/', 1)
stat = re.sub(replre, '', stat)
key = re.sub(replre, '', key)
if stat not in statres:
statres[stat] = {}
statres[stat][key] = statres.pop(attr)
result['stats'] = statres
# ---------------- Internals ----------------
if internals:
interres = result.pop('inter_ro', {})
interres.update(result.pop('inter_rw', {}))
if interres:
for key in interres:
if key.startswith('internal'):
nkey = re.sub(r'internal[s/]*', '', key)
interres[nkey] = interres.pop(key)
key = nkey
if key.startswith(('btree', 'writeback')):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in interres:
interres[mkey] = {}
interres[mkey][skey] = interres.pop(key)
result['internals'] = interres
# ---------------- Config ----------------
if config:
configres = result['config']
for key in configres:
if key.startswith('writeback'):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in configres:
configres[mkey] = {}
configres[mkey][skey] = configres.pop(key)
result['config'] = configres
# ---------------- Superblock ----------------
if superblock:
result['superblock'] = super_(dev)
return result
def super_(dev):
'''
Read out BCache SuperBlock
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc
'''
dev = _devpath(dev)
ret = {}
res = _run_all('bcache-super-show {0}'.format(dev), 'error', 'Error reading superblock on {0}: %s'.format(dev))
if not res:
return False
for line in res.splitlines(): # pylint: disable=no-member
line = line.strip()
if not line:
continue
key, val = [val.strip() for val in re.split(r'[\s]+', line, maxsplit=1)]
if not (key and val):
continue
mval = None
if ' ' in val:
rval, mval = [val.strip() for val in re.split(r'[\s]+', val, maxsplit=1)]
mval = mval[1:-1]
else:
rval = val
try:
rval = int(rval)
except Exception:
try:
rval = float(rval)
except Exception:
if rval == 'yes':
rval = True
elif rval == 'no':
rval = False
pkey, key = re.split(r'\.', key, maxsplit=1)
if pkey not in ret:
ret[pkey] = {}
if mval is not None:
ret[pkey][key] = (rval, mval)
else:
ret[pkey][key] = rval
return ret
# -------------------------------- HELPER FUNCTIONS --------------------------------
def _devbase(dev):
'''
Basename of just about any dev
'''
dev = os.path.realpath(os.path.expandvars(dev))
dev = os.path.basename(dev)
return dev
def _devpath(dev):
'''
Return /dev name of just about any dev
:return: /dev/devicename
'''
return os.path.join('/dev', _devbase(dev))
def _syspath(dev):
'''
Full SysFS path of a device
'''
dev = _devbase(dev)
dev = re.sub(r'^([vhs][a-z]+)([0-9]+)', r'\1/\1\2', dev)
# name = re.sub(r'^([a-z]+)(?<!(bcache|md|dm))([0-9]+)', r'\1/\1\2', name)
return os.path.join('/sys/block/', dev)
def _bdev(dev=None):
'''
Resolve a bcacheX or cache to a real dev
:return: basename of bcache dev
'''
if dev is None:
dev = _fssys('cache0')
else:
dev = _bcpath(dev)
if not dev:
return False
else:
return _devbase(os.path.dirname(dev))
def _bcpath(dev):
'''
Full SysFS path of a bcache device
'''
return os.path.join(_syspath(dev), 'bcache')
def _fspath():
'''
:return: path of active bcache
'''
cuuid = uuid()
if not cuuid:
return False
else:
return os.path.join('/sys/fs/bcache/', cuuid)
def _fssys(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with bcache SysFS
'''
fspath = _fspath()
if not fspath:
return False
else:
return _sysfs_attr([fspath, name], value, log_lvl, log_msg)
def _bcsys(dev, name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with backing devs SysFS
'''
return _sysfs_attr([_bcpath(dev), name], value, log_lvl, log_msg)
def _sysfs_attr(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper with logging around sysfs.attr
'''
if isinstance(name, six.string_types):
name = [name]
res = __salt__['sysfs.attr'](os.path.join(*name), value)
if not res and log_lvl is not None and log_msg is not None:
log.log(LOG[log_lvl], log_msg)
return res
def _sysfs_parse(path, base_attr=None, stats=False, config=False, internals=False, options=False):
'''
Helper function for parsing BCache's SysFS interface
'''
result = {}
# ---------------- Parse through the interfaces list ----------------
intfs = __salt__['sysfs.interfaces'](path)
# Actions, we ignore
del intfs['w']
# -------- Sorting hat --------
binkeys = []
if internals:
binkeys.extend(['inter_ro', 'inter_rw'])
if config:
binkeys.append('config')
if stats:
binkeys.append('stats')
bintf = {}
for key in binkeys:
bintf[key] = []
for intf in intfs['r']:
if intf.startswith('internal'):
key = 'inter_ro'
elif 'stats' in intf:
key = 'stats'
else:
# What to do with these???
# I'll utilize 'inter_ro' as 'misc' as well
key = 'inter_ro'
if key in bintf:
bintf[key].append(intf)
for intf in intfs['rw']:
if intf.startswith('internal'):
key = 'inter_rw'
else:
key = 'config'
if key in bintf:
bintf[key].append(intf)
if base_attr is not None:
for intf in bintf:
bintf[intf] = [sintf for sintf in bintf[intf] if sintf not in base_attr]
bintf['base'] = base_attr
mods = {
'stats': ['internal/bset_tree_stats', 'writeback_rate_debug', 'metadata_written', 'nbuckets', 'written',
'average_key_size', 'btree_cache_size'],
}
for modt, modlist in mods.items():
found = []
if modt not in bintf:
continue
for mod in modlist:
for intflist in bintf.values():
if mod in intflist:
found.append(mod)
intflist.remove(mod)
bintf[modt] += found
# -------- Fetch SysFS vals --------
bintflist = [intf for iflist in bintf.values() for intf in iflist]
result.update(__salt__['sysfs.read'](bintflist, path))
# -------- Parse through well known string lists --------
for strlist in ('writeback_rate_debug', 'internal/bset_tree_stats', 'priority_stats'):
if strlist in result:
listres = {}
for line in result[strlist].split('\n'):
key, val = line.split(':', 1)
val = val.strip()
try:
val = int(val)
except Exception:
try:
val = float(val)
except Exception:
pass
listres[key.strip()] = val
result[strlist] = listres
# -------- Parse through selection lists --------
if not options:
for sellist in ('cache_mode', 'cache_replacement_policy', 'errors'):
if sellist in result:
result[sellist] = re.search(r'\[(.+)\]', result[sellist]).groups()[0]
# -------- Parse through well known bools --------
for boolkey in ('running', 'writeback_running', 'congested'):
if boolkey in result:
result[boolkey] = bool(result[boolkey])
# -------- Recategorize results --------
bresult = {}
for iftype, intflist in bintf.items():
ifres = {}
for intf in intflist:
if intf in result:
ifres[intf] = result.pop(intf)
if ifres:
bresult[iftype] = ifres
return bresult
def _size_map(size):
'''
Map Bcache's size strings to real bytes
'''
try:
# I know, I know, EAFP.
# But everything else is reason for None
if not isinstance(size, int):
if re.search(r'[Kk]', size):
size = 1024 * float(re.sub(r'[Kk]', '', size))
elif re.search(r'[Mm]', size):
size = 1024**2 * float(re.sub(r'[Mm]', '', size))
size = int(size)
return size
except Exception:
return None
def _sizes(dev):
'''
Return neigh useless sizing info about a blockdev
:return: (total size in blocks, blocksize, maximum discard size in bytes)
'''
dev = _devbase(dev)
# standarization yay
block_sizes = ('hw_sector_size', 'minimum_io_size', 'physical_block_size', 'logical_block_size')
discard_sizes = ('discard_max_bytes', 'discard_max_hw_bytes', )
sysfs = __salt__['sysfs.read'](
('size',
'queue/hw_sector_size', '../queue/hw_sector_size',
'queue/discard_max_bytes', '../queue/discard_max_bytes'),
root=_syspath(dev))
# TODO: makes no sense
# First of all, it has to be a power of 2
# Secondly, this returns 4GiB - 512b on Intel 3500's for some weird reason
# discard_granularity seems in bytes, resolves to 512b ???
# max_hw_sectors_kb???
# There's also discard_max_hw_bytes more recently
# See: https://www.kernel.org/doc/Documentation/block/queue-sysfs.txt
# Also, I cant find any docs yet regarding bucket sizes;
# it's supposed to be discard_max_hw_bytes,
# but no way to figure that one reliably out apparently
discard = sysfs.get('queue/discard_max_bytes', sysfs.get('../queue/discard_max_bytes', None))
block = sysfs.get('queue/hw_sector_size', sysfs.get('../queue/hw_sector_size', None))
return 512*sysfs['size'], block, discard
def _wipe(dev):
'''
REALLY DESTRUCTIVE STUFF RIGHT AHEAD
'''
endres = 0
dev = _devbase(dev)
size, block, discard = _sizes(dev)
if discard is None:
log.error('Unable to read SysFS props for %s', dev)
return None
elif not discard:
log.warning('%s seems unable to discard', dev)
wiper = 'dd'
elif not HAS_BLKDISCARD:
log.warning('blkdiscard binary not available, properly wipe the dev manually for optimal results')
wiper = 'dd'
else:
wiper = 'blkdiscard'
wipe_failmsg = 'Error wiping {0}: %s'.format(dev)
if wiper == 'dd':
blocks = 4
cmd = 'dd if=/dev/zero of=/dev/{0} bs=1M count={1}'.format(dev, blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# Some stuff (<cough>GPT</cough>) writes stuff at the end of a dev as well
cmd += ' seek={0}'.format((size/1024**2) - blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
elif wiper == 'blkdiscard':
cmd = 'blkdiscard /dev/{0}'.format(dev)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# TODO: fix annoying bug failing blkdiscard by trying to discard 1 sector past blkdev
endres = 1
return endres > 0
def _wait(lfunc, log_lvl=None, log_msg=None, tries=10):
'''
Wait for lfunc to be True
:return: True if lfunc succeeded within tries, False if it didn't
'''
i = 0
while i < tries:
time.sleep(1)
if lfunc():
return True
else:
i += 1
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg)
return False
def _run_all(cmd, log_lvl=None, log_msg=None, exitcode=0):
'''
Simple wrapper around cmd.run_all
log_msg can contain {0} for stderr
:return: True or stdout, False if retcode wasn't exitcode
'''
res = __salt__['cmd.run_all'](cmd)
if res['retcode'] == exitcode:
if res['stdout']:
return res['stdout']
else:
return True
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg, res['stderr'])
return False
def _alltrue(resdict):
if resdict is None:
return True
return len([val for val in resdict.values() if val]) > 0
|
saltstack/salt
|
salt/modules/bcache.py
|
detach
|
python
|
def detach(dev=None):
'''
Detach a backing device(s) from a cache set
If no dev is given, all backing devices will be attached.
Detaching a backing device will flush it's write cache.
This should leave the underlying device in a consistent state, but might take a while.
CLI example:
.. code-block:: bash
salt '*' bcache.detach sdc
salt '*' bcache.detach bcache1
'''
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = detach(dev)
return res if res else None
log.debug('Detaching %s', dev)
if not _bcsys(dev, 'detach', 'goaway', 'error', 'Error detaching {0}'.format(dev)):
return False
return _wait(lambda: uuid(dev) is False, 'error', '{0} received detach, but did not comply'.format(dev), 300)
|
Detach a backing device(s) from a cache set
If no dev is given, all backing devices will be attached.
Detaching a backing device will flush it's write cache.
This should leave the underlying device in a consistent state, but might take a while.
CLI example:
.. code-block:: bash
salt '*' bcache.detach sdc
salt '*' bcache.detach bcache1
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bcache.py#L128-L155
|
[
"def detach(dev=None):\n '''\n Detach a backing device(s) from a cache set\n If no dev is given, all backing devices will be attached.\n\n Detaching a backing device will flush it's write cache.\n This should leave the underlying device in a consistent state, but might take a while.\n\n CLI example:\n\n .. code-block:: bash\n\n salt '*' bcache.detach sdc\n salt '*' bcache.detach bcache1\n\n '''\n if dev is None:\n res = {}\n for dev, data in status(alldevs=True).items():\n if 'cache' in data:\n res[dev] = detach(dev)\n\n return res if res else None\n\n log.debug('Detaching %s', dev)\n if not _bcsys(dev, 'detach', 'goaway', 'error', 'Error detaching {0}'.format(dev)):\n return False\n return _wait(lambda: uuid(dev) is False, 'error', '{0} received detach, but did not comply'.format(dev), 300)\n",
"def status(stats=False, config=False, internals=False, superblock=False, alldevs=False):\n '''\n Show the full status of the BCache system and optionally all it's involved devices\n\n CLI example:\n\n .. code-block:: bash\n\n salt '*' bcache.status\n salt '*' bcache.status stats=True\n salt '*' bcache.status internals=True alldevs=True\n\n :param stats: include statistics\n :param config: include settings\n :param internals: include internals\n :param superblock: include superblock\n '''\n bdevs = []\n for _, links, _ in salt.utils.path.os_walk('/sys/block/'):\n for block in links:\n if 'bcache' in block:\n continue\n\n for spath, sdirs, _ in salt.utils.path.os_walk('/sys/block/{0}'.format(block), followlinks=False):\n if 'bcache' in sdirs:\n bdevs.append(os.path.basename(spath))\n statii = {}\n for bcache in bdevs:\n statii[bcache] = device(bcache, stats, config, internals, superblock)\n\n cuuid = uuid()\n cdev = _bdev()\n if cdev:\n count = 0\n for dev in statii:\n if dev != cdev:\n # it's a backing dev\n if statii[dev]['cache'] == cuuid:\n count += 1\n statii[cdev]['attached_backing_devices'] = count\n\n if not alldevs:\n statii = statii[cdev]\n\n return statii\n",
"def _wait(lfunc, log_lvl=None, log_msg=None, tries=10):\n '''\n Wait for lfunc to be True\n :return: True if lfunc succeeded within tries, False if it didn't\n '''\n i = 0\n while i < tries:\n time.sleep(1)\n\n if lfunc():\n return True\n else:\n i += 1\n if log_lvl is not None:\n log.log(LOG[log_lvl], log_msg)\n return False\n",
"def _bcsys(dev, name, value=None, log_lvl=None, log_msg=None):\n '''\n Simple wrapper to interface with backing devs SysFS\n '''\n return _sysfs_attr([_bcpath(dev), name], value, log_lvl, log_msg)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for managing BCache sets
BCache is a block-level caching mechanism similar to ZFS L2ARC/ZIL, dm-cache and fscache.
It works by formatting one block device as a cache set, then adding backend devices
(which need to be formatted as such) to the set and activating them.
It's available in Linux mainline kernel since 3.10
https://www.kernel.org/doc/Documentation/bcache.txt
This module needs the bcache userspace tools to function.
.. versionadded: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import time
import re
from salt.ext import six
# Import salt libs
import salt.utils.path
log = logging.getLogger(__name__)
LOG = {
'trace': logging.TRACE,
'debug': logging.DEBUG,
'info': logging.INFO,
'warn': logging.WARNING,
'error': logging.ERROR,
'crit': logging.CRITICAL,
}
__func_alias__ = {
'attach_': 'attach',
'config_': 'config',
'super_': 'super',
}
HAS_BLKDISCARD = salt.utils.path.which('blkdiscard') is not None
def __virtual__():
'''
Only work when make-bcache is installed
'''
return salt.utils.path.which('make-bcache') is not None
def uuid(dev=None):
'''
Return the bcache UUID of a block device.
If no device is given, the Cache UUID is returned.
CLI example:
.. code-block:: bash
salt '*' bcache.uuid
salt '*' bcache.uuid /dev/sda
salt '*' bcache.uuid bcache0
'''
try:
if dev is None:
# take the only directory in /sys/fs/bcache and return it's basename
return list(salt.utils.path.os_walk('/sys/fs/bcache/'))[0][1][0]
else:
# basename of the /sys/block/{dev}/bcache/cache symlink target
return os.path.basename(_bcsys(dev, 'cache'))
except Exception:
return False
def attach_(dev=None):
'''
Attach a backing devices to a cache set
If no dev is given, all backing devices will be attached.
CLI example:
.. code-block:: bash
salt '*' bcache.attach sdc
salt '*' bcache.attach /dev/bcache1
:return: bool or None if nuttin' happened
'''
cache = uuid()
if not cache:
log.error('No cache to attach %s to', dev)
return False
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = attach_(dev)
return res if res else None
bcache = uuid(dev)
if bcache:
if bcache == cache:
log.info('%s is already attached to bcache %s, doing nothing', dev, cache)
return None
elif not detach(dev):
return False
log.debug('Attaching %s to bcache %s', dev, cache)
if not _bcsys(dev, 'attach', cache,
'error', 'Error attaching {0} to bcache {1}'.format(dev, cache)):
return False
return _wait(lambda: uuid(dev) == cache,
'error', '{0} received attach to bcache {1}, but did not comply'.format(dev, cache))
def start():
'''
Trigger a start of the full bcache system through udev.
CLI example:
.. code-block:: bash
salt '*' bcache.start
'''
if not _run_all('udevadm trigger', 'error', 'Error starting bcache: %s'):
return False
elif not _wait(lambda: uuid() is not False, 'warn', 'Bcache system started, but no active cache set found.'):
return False
return True
def stop(dev=None):
'''
Stop a bcache device
If no device is given, all backing devices will be detached from the cache, which will subsequently be stopped.
.. warning::
'Stop' on an individual backing device means hard-stop;
no attempt at flushing will be done and the bcache device will seemingly 'disappear' from the device lists
CLI example:
.. code-block:: bash
salt '*' bcache.stop
'''
if dev is not None:
log.warning('Stopping %s, device will only reappear after reregistering!', dev)
if not _bcsys(dev, 'stop', 'goaway', 'error', 'Error stopping {0}'.format(dev)):
return False
return _wait(lambda: _sysfs_attr(_bcpath(dev)) is False, 'error', 'Device {0} did not stop'.format(dev), 300)
else:
cache = uuid()
if not cache:
log.warning('bcache already stopped?')
return None
if not _alltrue(detach()):
return False
elif not _fssys('stop', 'goaway', 'error', 'Error stopping cache'):
return False
return _wait(lambda: uuid() is False, 'error', 'Cache did not stop', 300)
def back_make(dev, cache_mode='writeback', force=False, attach=True, bucket_size=None):
'''
Create a backing device for attachment to a set.
Because the block size must be the same, a cache set already needs to exist.
CLI example:
.. code-block:: bash
salt '*' bcache.back_make sdc cache_mode=writeback attach=True
:param cache_mode: writethrough, writeback, writearound or none.
:param force: Overwrite existing bcaches
:param attach: Immediately attach the backing device to the set
:param bucket_size: Size of a bucket (see kernel doc)
'''
# pylint: disable=too-many-return-statements
cache = uuid()
if not cache:
log.error('No bcache set found')
return False
elif _sysfs_attr(_bcpath(dev)):
if not force:
log.error('%s already contains a bcache. Wipe it manually or use force', dev)
return False
elif uuid(dev) and not detach(dev):
return False
elif not stop(dev):
return False
dev = _devpath(dev)
block_size = _size_map(_fssys('block_size'))
# You might want to override, we pick the cache set's as sane default
if bucket_size is None:
bucket_size = _size_map(_fssys('bucket_size'))
cmd = 'make-bcache --block {0} --bucket {1} --{2} --bdev {3}'.format(block_size, bucket_size, cache_mode, dev)
if force:
cmd += ' --wipe-bcache'
if not _run_all(cmd, 'error', 'Error creating backing device {0}: %s'.format(dev)):
return False
elif not _sysfs_attr('fs/bcache/register', _devpath(dev),
'error', 'Error registering backing device {0}'.format(dev)):
return False
elif not _wait(lambda: _sysfs_attr(_bcpath(dev)) is not False,
'error', 'Backing device {0} did not register'.format(dev)):
return False
elif attach:
return attach_(dev)
return True
def cache_make(dev, reserved=None, force=False, block_size=None, bucket_size=None, attach=True):
'''
Create BCache cache on a block device.
If blkdiscard is available the entire device will be properly cleared in advance.
CLI example:
.. code-block:: bash
salt '*' bcache.cache_make sdb reserved=10% block_size=4096
:param reserved: if dev is a full device, create a partition table with this size empty.
.. note::
this increases the amount of reserved space available to SSD garbage collectors,
potentially (vastly) increasing performance
:param block_size: Block size of the cache; defaults to devices' logical block size
:param force: Overwrite existing BCache sets
:param attach: Attach all existing backend devices immediately
'''
# TODO: multiple devs == md jbod
# pylint: disable=too-many-return-statements
# ---------------- Preflight checks ----------------
cache = uuid()
if cache:
if not force:
log.error('BCache cache %s is already on the system', cache)
return False
cache = _bdev()
dev = _devbase(dev)
udev = __salt__['udev.env'](dev)
if ('ID_FS_TYPE' in udev or (udev.get('DEVTYPE', None) != 'partition' and 'ID_PART_TABLE_TYPE' in udev)) \
and not force:
log.error('%s already contains data, wipe first or force', dev)
return False
elif reserved is not None and udev.get('DEVTYPE', None) != 'disk':
log.error('Need a partitionable blockdev for reserved to work')
return False
_, block, bucket = _sizes(dev)
if bucket_size is None:
bucket_size = bucket
# TODO: bucket from _sizes() makes no sense
bucket_size = False
if block_size is None:
block_size = block
# ---------------- Still here, start doing destructive stuff ----------------
if cache:
if not stop():
return False
# Wipe the current cache device as well,
# forever ruining any chance of it accidentally popping up again
elif not _wipe(cache):
return False
# Can't do enough wiping
if not _wipe(dev):
return False
if reserved:
cmd = 'parted -m -s -a optimal -- ' \
'/dev/{0} mklabel gpt mkpart bcache-reserved 1M {1} mkpart bcache {1} 100%'.format(dev, reserved)
# if wipe was incomplete & part layout remains the same,
# this is one condition set where udev would make it accidentally popup again
if not _run_all(cmd, 'error', 'Error creating bcache partitions on {0}: %s'.format(dev)):
return False
dev = '{0}2'.format(dev)
# ---------------- Finally, create a cache ----------------
cmd = 'make-bcache --cache /dev/{0} --block {1} --wipe-bcache'.format(dev, block_size)
# Actually bucket_size should always have a value, but for testing 0 is possible as well
if bucket_size:
cmd += ' --bucket {0}'.format(bucket_size)
if not _run_all(cmd, 'error', 'Error creating cache {0}: %s'.format(dev)):
return False
elif not _wait(lambda: uuid() is not False,
'error', 'Cache {0} seemingly created OK, but FS did not activate'.format(dev)):
return False
if attach:
return _alltrue(attach_())
else:
return True
def config_(dev=None, **kwargs):
'''
Show or update config of a bcache device.
If no device is given, operate on the cache set itself.
CLI example:
.. code-block:: bash
salt '*' bcache.config
salt '*' bcache.config bcache1
salt '*' bcache.config errors=panic journal_delay_ms=150
salt '*' bcache.config bcache1 cache_mode=writeback writeback_percent=15
:return: config or True/False
'''
if dev is None:
spath = _fspath()
else:
spath = _bcpath(dev)
# filter out 'hidden' kwargs added by our favourite orchestration system
updates = dict([(key, val) for key, val in kwargs.items() if not key.startswith('__')])
if updates:
endres = 0
for key, val in updates.items():
endres += _sysfs_attr([spath, key], val,
'warn', 'Failed to update {0} with {1}'.format(os.path.join(spath, key), val))
return endres > 0
else:
result = {}
data = _sysfs_parse(spath, config=True, internals=True, options=True)
for key in ('other_ro', 'inter_ro'):
if key in data:
del data[key]
for key in data:
result.update(data[key])
return result
def status(stats=False, config=False, internals=False, superblock=False, alldevs=False):
'''
Show the full status of the BCache system and optionally all it's involved devices
CLI example:
.. code-block:: bash
salt '*' bcache.status
salt '*' bcache.status stats=True
salt '*' bcache.status internals=True alldevs=True
:param stats: include statistics
:param config: include settings
:param internals: include internals
:param superblock: include superblock
'''
bdevs = []
for _, links, _ in salt.utils.path.os_walk('/sys/block/'):
for block in links:
if 'bcache' in block:
continue
for spath, sdirs, _ in salt.utils.path.os_walk('/sys/block/{0}'.format(block), followlinks=False):
if 'bcache' in sdirs:
bdevs.append(os.path.basename(spath))
statii = {}
for bcache in bdevs:
statii[bcache] = device(bcache, stats, config, internals, superblock)
cuuid = uuid()
cdev = _bdev()
if cdev:
count = 0
for dev in statii:
if dev != cdev:
# it's a backing dev
if statii[dev]['cache'] == cuuid:
count += 1
statii[cdev]['attached_backing_devices'] = count
if not alldevs:
statii = statii[cdev]
return statii
def device(dev, stats=False, config=False, internals=False, superblock=False):
'''
Check the state of a single bcache device
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc stats=True
:param stats: include statistics
:param settings: include all settings
:param internals: include all internals
:param superblock: include superblock info
'''
result = {}
if not _sysfs_attr(_bcpath(dev), None, 'error', '{0} is not a bcache fo any kind'.format(dev)):
return False
elif _bcsys(dev, 'set'):
# ---------------- It's the cache itself ----------------
result['uuid'] = uuid()
base_attr = ['block_size', 'bucket_size', 'cache_available_percent', 'cache_replacement_policy', 'congested']
# ---------------- Parse through both the blockdev & the FS ----------------
result.update(_sysfs_parse(_bcpath(dev), base_attr, stats, config, internals))
result.update(_sysfs_parse(_fspath(), base_attr, stats, config, internals))
result.update(result.pop('base'))
else:
# ---------------- It's a backing device ----------------
back_uuid = uuid(dev)
if back_uuid is not None:
result['cache'] = back_uuid
try:
result['dev'] = os.path.basename(_bcsys(dev, 'dev'))
except Exception:
pass
result['bdev'] = _bdev(dev)
base_attr = ['cache_mode', 'running', 'state', 'writeback_running']
base_path = _bcpath(dev)
result.update(_sysfs_parse(base_path, base_attr, stats, config, internals))
result.update(result.pop('base'))
# ---------------- Modifications ----------------
state = [result['state']]
if result.pop('running'):
state.append('running')
else:
state.append('stopped')
if 'writeback_running' in result:
if result.pop('writeback_running'):
state.append('writeback_running')
else:
state.append('writeback_stopped')
result['state'] = state
# ---------------- Statistics ----------------
if 'stats' in result:
replre = r'(stats|cache)_'
statres = result['stats']
for attr in result['stats']:
if '/' not in attr:
key = re.sub(replre, '', attr)
statres[key] = statres.pop(attr)
else:
stat, key = attr.split('/', 1)
stat = re.sub(replre, '', stat)
key = re.sub(replre, '', key)
if stat not in statres:
statres[stat] = {}
statres[stat][key] = statres.pop(attr)
result['stats'] = statres
# ---------------- Internals ----------------
if internals:
interres = result.pop('inter_ro', {})
interres.update(result.pop('inter_rw', {}))
if interres:
for key in interres:
if key.startswith('internal'):
nkey = re.sub(r'internal[s/]*', '', key)
interres[nkey] = interres.pop(key)
key = nkey
if key.startswith(('btree', 'writeback')):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in interres:
interres[mkey] = {}
interres[mkey][skey] = interres.pop(key)
result['internals'] = interres
# ---------------- Config ----------------
if config:
configres = result['config']
for key in configres:
if key.startswith('writeback'):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in configres:
configres[mkey] = {}
configres[mkey][skey] = configres.pop(key)
result['config'] = configres
# ---------------- Superblock ----------------
if superblock:
result['superblock'] = super_(dev)
return result
def super_(dev):
'''
Read out BCache SuperBlock
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc
'''
dev = _devpath(dev)
ret = {}
res = _run_all('bcache-super-show {0}'.format(dev), 'error', 'Error reading superblock on {0}: %s'.format(dev))
if not res:
return False
for line in res.splitlines(): # pylint: disable=no-member
line = line.strip()
if not line:
continue
key, val = [val.strip() for val in re.split(r'[\s]+', line, maxsplit=1)]
if not (key and val):
continue
mval = None
if ' ' in val:
rval, mval = [val.strip() for val in re.split(r'[\s]+', val, maxsplit=1)]
mval = mval[1:-1]
else:
rval = val
try:
rval = int(rval)
except Exception:
try:
rval = float(rval)
except Exception:
if rval == 'yes':
rval = True
elif rval == 'no':
rval = False
pkey, key = re.split(r'\.', key, maxsplit=1)
if pkey not in ret:
ret[pkey] = {}
if mval is not None:
ret[pkey][key] = (rval, mval)
else:
ret[pkey][key] = rval
return ret
# -------------------------------- HELPER FUNCTIONS --------------------------------
def _devbase(dev):
'''
Basename of just about any dev
'''
dev = os.path.realpath(os.path.expandvars(dev))
dev = os.path.basename(dev)
return dev
def _devpath(dev):
'''
Return /dev name of just about any dev
:return: /dev/devicename
'''
return os.path.join('/dev', _devbase(dev))
def _syspath(dev):
'''
Full SysFS path of a device
'''
dev = _devbase(dev)
dev = re.sub(r'^([vhs][a-z]+)([0-9]+)', r'\1/\1\2', dev)
# name = re.sub(r'^([a-z]+)(?<!(bcache|md|dm))([0-9]+)', r'\1/\1\2', name)
return os.path.join('/sys/block/', dev)
def _bdev(dev=None):
'''
Resolve a bcacheX or cache to a real dev
:return: basename of bcache dev
'''
if dev is None:
dev = _fssys('cache0')
else:
dev = _bcpath(dev)
if not dev:
return False
else:
return _devbase(os.path.dirname(dev))
def _bcpath(dev):
'''
Full SysFS path of a bcache device
'''
return os.path.join(_syspath(dev), 'bcache')
def _fspath():
'''
:return: path of active bcache
'''
cuuid = uuid()
if not cuuid:
return False
else:
return os.path.join('/sys/fs/bcache/', cuuid)
def _fssys(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with bcache SysFS
'''
fspath = _fspath()
if not fspath:
return False
else:
return _sysfs_attr([fspath, name], value, log_lvl, log_msg)
def _bcsys(dev, name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with backing devs SysFS
'''
return _sysfs_attr([_bcpath(dev), name], value, log_lvl, log_msg)
def _sysfs_attr(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper with logging around sysfs.attr
'''
if isinstance(name, six.string_types):
name = [name]
res = __salt__['sysfs.attr'](os.path.join(*name), value)
if not res and log_lvl is not None and log_msg is not None:
log.log(LOG[log_lvl], log_msg)
return res
def _sysfs_parse(path, base_attr=None, stats=False, config=False, internals=False, options=False):
'''
Helper function for parsing BCache's SysFS interface
'''
result = {}
# ---------------- Parse through the interfaces list ----------------
intfs = __salt__['sysfs.interfaces'](path)
# Actions, we ignore
del intfs['w']
# -------- Sorting hat --------
binkeys = []
if internals:
binkeys.extend(['inter_ro', 'inter_rw'])
if config:
binkeys.append('config')
if stats:
binkeys.append('stats')
bintf = {}
for key in binkeys:
bintf[key] = []
for intf in intfs['r']:
if intf.startswith('internal'):
key = 'inter_ro'
elif 'stats' in intf:
key = 'stats'
else:
# What to do with these???
# I'll utilize 'inter_ro' as 'misc' as well
key = 'inter_ro'
if key in bintf:
bintf[key].append(intf)
for intf in intfs['rw']:
if intf.startswith('internal'):
key = 'inter_rw'
else:
key = 'config'
if key in bintf:
bintf[key].append(intf)
if base_attr is not None:
for intf in bintf:
bintf[intf] = [sintf for sintf in bintf[intf] if sintf not in base_attr]
bintf['base'] = base_attr
mods = {
'stats': ['internal/bset_tree_stats', 'writeback_rate_debug', 'metadata_written', 'nbuckets', 'written',
'average_key_size', 'btree_cache_size'],
}
for modt, modlist in mods.items():
found = []
if modt not in bintf:
continue
for mod in modlist:
for intflist in bintf.values():
if mod in intflist:
found.append(mod)
intflist.remove(mod)
bintf[modt] += found
# -------- Fetch SysFS vals --------
bintflist = [intf for iflist in bintf.values() for intf in iflist]
result.update(__salt__['sysfs.read'](bintflist, path))
# -------- Parse through well known string lists --------
for strlist in ('writeback_rate_debug', 'internal/bset_tree_stats', 'priority_stats'):
if strlist in result:
listres = {}
for line in result[strlist].split('\n'):
key, val = line.split(':', 1)
val = val.strip()
try:
val = int(val)
except Exception:
try:
val = float(val)
except Exception:
pass
listres[key.strip()] = val
result[strlist] = listres
# -------- Parse through selection lists --------
if not options:
for sellist in ('cache_mode', 'cache_replacement_policy', 'errors'):
if sellist in result:
result[sellist] = re.search(r'\[(.+)\]', result[sellist]).groups()[0]
# -------- Parse through well known bools --------
for boolkey in ('running', 'writeback_running', 'congested'):
if boolkey in result:
result[boolkey] = bool(result[boolkey])
# -------- Recategorize results --------
bresult = {}
for iftype, intflist in bintf.items():
ifres = {}
for intf in intflist:
if intf in result:
ifres[intf] = result.pop(intf)
if ifres:
bresult[iftype] = ifres
return bresult
def _size_map(size):
'''
Map Bcache's size strings to real bytes
'''
try:
# I know, I know, EAFP.
# But everything else is reason for None
if not isinstance(size, int):
if re.search(r'[Kk]', size):
size = 1024 * float(re.sub(r'[Kk]', '', size))
elif re.search(r'[Mm]', size):
size = 1024**2 * float(re.sub(r'[Mm]', '', size))
size = int(size)
return size
except Exception:
return None
def _sizes(dev):
'''
Return neigh useless sizing info about a blockdev
:return: (total size in blocks, blocksize, maximum discard size in bytes)
'''
dev = _devbase(dev)
# standarization yay
block_sizes = ('hw_sector_size', 'minimum_io_size', 'physical_block_size', 'logical_block_size')
discard_sizes = ('discard_max_bytes', 'discard_max_hw_bytes', )
sysfs = __salt__['sysfs.read'](
('size',
'queue/hw_sector_size', '../queue/hw_sector_size',
'queue/discard_max_bytes', '../queue/discard_max_bytes'),
root=_syspath(dev))
# TODO: makes no sense
# First of all, it has to be a power of 2
# Secondly, this returns 4GiB - 512b on Intel 3500's for some weird reason
# discard_granularity seems in bytes, resolves to 512b ???
# max_hw_sectors_kb???
# There's also discard_max_hw_bytes more recently
# See: https://www.kernel.org/doc/Documentation/block/queue-sysfs.txt
# Also, I cant find any docs yet regarding bucket sizes;
# it's supposed to be discard_max_hw_bytes,
# but no way to figure that one reliably out apparently
discard = sysfs.get('queue/discard_max_bytes', sysfs.get('../queue/discard_max_bytes', None))
block = sysfs.get('queue/hw_sector_size', sysfs.get('../queue/hw_sector_size', None))
return 512*sysfs['size'], block, discard
def _wipe(dev):
'''
REALLY DESTRUCTIVE STUFF RIGHT AHEAD
'''
endres = 0
dev = _devbase(dev)
size, block, discard = _sizes(dev)
if discard is None:
log.error('Unable to read SysFS props for %s', dev)
return None
elif not discard:
log.warning('%s seems unable to discard', dev)
wiper = 'dd'
elif not HAS_BLKDISCARD:
log.warning('blkdiscard binary not available, properly wipe the dev manually for optimal results')
wiper = 'dd'
else:
wiper = 'blkdiscard'
wipe_failmsg = 'Error wiping {0}: %s'.format(dev)
if wiper == 'dd':
blocks = 4
cmd = 'dd if=/dev/zero of=/dev/{0} bs=1M count={1}'.format(dev, blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# Some stuff (<cough>GPT</cough>) writes stuff at the end of a dev as well
cmd += ' seek={0}'.format((size/1024**2) - blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
elif wiper == 'blkdiscard':
cmd = 'blkdiscard /dev/{0}'.format(dev)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# TODO: fix annoying bug failing blkdiscard by trying to discard 1 sector past blkdev
endres = 1
return endres > 0
def _wait(lfunc, log_lvl=None, log_msg=None, tries=10):
'''
Wait for lfunc to be True
:return: True if lfunc succeeded within tries, False if it didn't
'''
i = 0
while i < tries:
time.sleep(1)
if lfunc():
return True
else:
i += 1
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg)
return False
def _run_all(cmd, log_lvl=None, log_msg=None, exitcode=0):
'''
Simple wrapper around cmd.run_all
log_msg can contain {0} for stderr
:return: True or stdout, False if retcode wasn't exitcode
'''
res = __salt__['cmd.run_all'](cmd)
if res['retcode'] == exitcode:
if res['stdout']:
return res['stdout']
else:
return True
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg, res['stderr'])
return False
def _alltrue(resdict):
if resdict is None:
return True
return len([val for val in resdict.values() if val]) > 0
|
saltstack/salt
|
salt/modules/bcache.py
|
stop
|
python
|
def stop(dev=None):
'''
Stop a bcache device
If no device is given, all backing devices will be detached from the cache, which will subsequently be stopped.
.. warning::
'Stop' on an individual backing device means hard-stop;
no attempt at flushing will be done and the bcache device will seemingly 'disappear' from the device lists
CLI example:
.. code-block:: bash
salt '*' bcache.stop
'''
if dev is not None:
log.warning('Stopping %s, device will only reappear after reregistering!', dev)
if not _bcsys(dev, 'stop', 'goaway', 'error', 'Error stopping {0}'.format(dev)):
return False
return _wait(lambda: _sysfs_attr(_bcpath(dev)) is False, 'error', 'Device {0} did not stop'.format(dev), 300)
else:
cache = uuid()
if not cache:
log.warning('bcache already stopped?')
return None
if not _alltrue(detach()):
return False
elif not _fssys('stop', 'goaway', 'error', 'Error stopping cache'):
return False
return _wait(lambda: uuid() is False, 'error', 'Cache did not stop', 300)
|
Stop a bcache device
If no device is given, all backing devices will be detached from the cache, which will subsequently be stopped.
.. warning::
'Stop' on an individual backing device means hard-stop;
no attempt at flushing will be done and the bcache device will seemingly 'disappear' from the device lists
CLI example:
.. code-block:: bash
salt '*' bcache.stop
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bcache.py#L176-L208
|
[
"def detach(dev=None):\n '''\n Detach a backing device(s) from a cache set\n If no dev is given, all backing devices will be attached.\n\n Detaching a backing device will flush it's write cache.\n This should leave the underlying device in a consistent state, but might take a while.\n\n CLI example:\n\n .. code-block:: bash\n\n salt '*' bcache.detach sdc\n salt '*' bcache.detach bcache1\n\n '''\n if dev is None:\n res = {}\n for dev, data in status(alldevs=True).items():\n if 'cache' in data:\n res[dev] = detach(dev)\n\n return res if res else None\n\n log.debug('Detaching %s', dev)\n if not _bcsys(dev, 'detach', 'goaway', 'error', 'Error detaching {0}'.format(dev)):\n return False\n return _wait(lambda: uuid(dev) is False, 'error', '{0} received detach, but did not comply'.format(dev), 300)\n",
"def uuid(dev=None):\n '''\n Return the bcache UUID of a block device.\n If no device is given, the Cache UUID is returned.\n\n CLI example:\n\n .. code-block:: bash\n\n salt '*' bcache.uuid\n salt '*' bcache.uuid /dev/sda\n salt '*' bcache.uuid bcache0\n\n '''\n try:\n if dev is None:\n # take the only directory in /sys/fs/bcache and return it's basename\n return list(salt.utils.path.os_walk('/sys/fs/bcache/'))[0][1][0]\n else:\n # basename of the /sys/block/{dev}/bcache/cache symlink target\n return os.path.basename(_bcsys(dev, 'cache'))\n except Exception:\n return False\n",
"def _wait(lfunc, log_lvl=None, log_msg=None, tries=10):\n '''\n Wait for lfunc to be True\n :return: True if lfunc succeeded within tries, False if it didn't\n '''\n i = 0\n while i < tries:\n time.sleep(1)\n\n if lfunc():\n return True\n else:\n i += 1\n if log_lvl is not None:\n log.log(LOG[log_lvl], log_msg)\n return False\n",
"def _bcsys(dev, name, value=None, log_lvl=None, log_msg=None):\n '''\n Simple wrapper to interface with backing devs SysFS\n '''\n return _sysfs_attr([_bcpath(dev), name], value, log_lvl, log_msg)\n",
"def _alltrue(resdict):\n if resdict is None:\n return True\n return len([val for val in resdict.values() if val]) > 0\n",
"def _fssys(name, value=None, log_lvl=None, log_msg=None):\n '''\n Simple wrapper to interface with bcache SysFS\n '''\n fspath = _fspath()\n if not fspath:\n return False\n else:\n return _sysfs_attr([fspath, name], value, log_lvl, log_msg)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for managing BCache sets
BCache is a block-level caching mechanism similar to ZFS L2ARC/ZIL, dm-cache and fscache.
It works by formatting one block device as a cache set, then adding backend devices
(which need to be formatted as such) to the set and activating them.
It's available in Linux mainline kernel since 3.10
https://www.kernel.org/doc/Documentation/bcache.txt
This module needs the bcache userspace tools to function.
.. versionadded: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import time
import re
from salt.ext import six
# Import salt libs
import salt.utils.path
log = logging.getLogger(__name__)
LOG = {
'trace': logging.TRACE,
'debug': logging.DEBUG,
'info': logging.INFO,
'warn': logging.WARNING,
'error': logging.ERROR,
'crit': logging.CRITICAL,
}
__func_alias__ = {
'attach_': 'attach',
'config_': 'config',
'super_': 'super',
}
HAS_BLKDISCARD = salt.utils.path.which('blkdiscard') is not None
def __virtual__():
'''
Only work when make-bcache is installed
'''
return salt.utils.path.which('make-bcache') is not None
def uuid(dev=None):
'''
Return the bcache UUID of a block device.
If no device is given, the Cache UUID is returned.
CLI example:
.. code-block:: bash
salt '*' bcache.uuid
salt '*' bcache.uuid /dev/sda
salt '*' bcache.uuid bcache0
'''
try:
if dev is None:
# take the only directory in /sys/fs/bcache and return it's basename
return list(salt.utils.path.os_walk('/sys/fs/bcache/'))[0][1][0]
else:
# basename of the /sys/block/{dev}/bcache/cache symlink target
return os.path.basename(_bcsys(dev, 'cache'))
except Exception:
return False
def attach_(dev=None):
'''
Attach a backing devices to a cache set
If no dev is given, all backing devices will be attached.
CLI example:
.. code-block:: bash
salt '*' bcache.attach sdc
salt '*' bcache.attach /dev/bcache1
:return: bool or None if nuttin' happened
'''
cache = uuid()
if not cache:
log.error('No cache to attach %s to', dev)
return False
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = attach_(dev)
return res if res else None
bcache = uuid(dev)
if bcache:
if bcache == cache:
log.info('%s is already attached to bcache %s, doing nothing', dev, cache)
return None
elif not detach(dev):
return False
log.debug('Attaching %s to bcache %s', dev, cache)
if not _bcsys(dev, 'attach', cache,
'error', 'Error attaching {0} to bcache {1}'.format(dev, cache)):
return False
return _wait(lambda: uuid(dev) == cache,
'error', '{0} received attach to bcache {1}, but did not comply'.format(dev, cache))
def detach(dev=None):
'''
Detach a backing device(s) from a cache set
If no dev is given, all backing devices will be attached.
Detaching a backing device will flush it's write cache.
This should leave the underlying device in a consistent state, but might take a while.
CLI example:
.. code-block:: bash
salt '*' bcache.detach sdc
salt '*' bcache.detach bcache1
'''
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = detach(dev)
return res if res else None
log.debug('Detaching %s', dev)
if not _bcsys(dev, 'detach', 'goaway', 'error', 'Error detaching {0}'.format(dev)):
return False
return _wait(lambda: uuid(dev) is False, 'error', '{0} received detach, but did not comply'.format(dev), 300)
def start():
'''
Trigger a start of the full bcache system through udev.
CLI example:
.. code-block:: bash
salt '*' bcache.start
'''
if not _run_all('udevadm trigger', 'error', 'Error starting bcache: %s'):
return False
elif not _wait(lambda: uuid() is not False, 'warn', 'Bcache system started, but no active cache set found.'):
return False
return True
def back_make(dev, cache_mode='writeback', force=False, attach=True, bucket_size=None):
'''
Create a backing device for attachment to a set.
Because the block size must be the same, a cache set already needs to exist.
CLI example:
.. code-block:: bash
salt '*' bcache.back_make sdc cache_mode=writeback attach=True
:param cache_mode: writethrough, writeback, writearound or none.
:param force: Overwrite existing bcaches
:param attach: Immediately attach the backing device to the set
:param bucket_size: Size of a bucket (see kernel doc)
'''
# pylint: disable=too-many-return-statements
cache = uuid()
if not cache:
log.error('No bcache set found')
return False
elif _sysfs_attr(_bcpath(dev)):
if not force:
log.error('%s already contains a bcache. Wipe it manually or use force', dev)
return False
elif uuid(dev) and not detach(dev):
return False
elif not stop(dev):
return False
dev = _devpath(dev)
block_size = _size_map(_fssys('block_size'))
# You might want to override, we pick the cache set's as sane default
if bucket_size is None:
bucket_size = _size_map(_fssys('bucket_size'))
cmd = 'make-bcache --block {0} --bucket {1} --{2} --bdev {3}'.format(block_size, bucket_size, cache_mode, dev)
if force:
cmd += ' --wipe-bcache'
if not _run_all(cmd, 'error', 'Error creating backing device {0}: %s'.format(dev)):
return False
elif not _sysfs_attr('fs/bcache/register', _devpath(dev),
'error', 'Error registering backing device {0}'.format(dev)):
return False
elif not _wait(lambda: _sysfs_attr(_bcpath(dev)) is not False,
'error', 'Backing device {0} did not register'.format(dev)):
return False
elif attach:
return attach_(dev)
return True
def cache_make(dev, reserved=None, force=False, block_size=None, bucket_size=None, attach=True):
'''
Create BCache cache on a block device.
If blkdiscard is available the entire device will be properly cleared in advance.
CLI example:
.. code-block:: bash
salt '*' bcache.cache_make sdb reserved=10% block_size=4096
:param reserved: if dev is a full device, create a partition table with this size empty.
.. note::
this increases the amount of reserved space available to SSD garbage collectors,
potentially (vastly) increasing performance
:param block_size: Block size of the cache; defaults to devices' logical block size
:param force: Overwrite existing BCache sets
:param attach: Attach all existing backend devices immediately
'''
# TODO: multiple devs == md jbod
# pylint: disable=too-many-return-statements
# ---------------- Preflight checks ----------------
cache = uuid()
if cache:
if not force:
log.error('BCache cache %s is already on the system', cache)
return False
cache = _bdev()
dev = _devbase(dev)
udev = __salt__['udev.env'](dev)
if ('ID_FS_TYPE' in udev or (udev.get('DEVTYPE', None) != 'partition' and 'ID_PART_TABLE_TYPE' in udev)) \
and not force:
log.error('%s already contains data, wipe first or force', dev)
return False
elif reserved is not None and udev.get('DEVTYPE', None) != 'disk':
log.error('Need a partitionable blockdev for reserved to work')
return False
_, block, bucket = _sizes(dev)
if bucket_size is None:
bucket_size = bucket
# TODO: bucket from _sizes() makes no sense
bucket_size = False
if block_size is None:
block_size = block
# ---------------- Still here, start doing destructive stuff ----------------
if cache:
if not stop():
return False
# Wipe the current cache device as well,
# forever ruining any chance of it accidentally popping up again
elif not _wipe(cache):
return False
# Can't do enough wiping
if not _wipe(dev):
return False
if reserved:
cmd = 'parted -m -s -a optimal -- ' \
'/dev/{0} mklabel gpt mkpart bcache-reserved 1M {1} mkpart bcache {1} 100%'.format(dev, reserved)
# if wipe was incomplete & part layout remains the same,
# this is one condition set where udev would make it accidentally popup again
if not _run_all(cmd, 'error', 'Error creating bcache partitions on {0}: %s'.format(dev)):
return False
dev = '{0}2'.format(dev)
# ---------------- Finally, create a cache ----------------
cmd = 'make-bcache --cache /dev/{0} --block {1} --wipe-bcache'.format(dev, block_size)
# Actually bucket_size should always have a value, but for testing 0 is possible as well
if bucket_size:
cmd += ' --bucket {0}'.format(bucket_size)
if not _run_all(cmd, 'error', 'Error creating cache {0}: %s'.format(dev)):
return False
elif not _wait(lambda: uuid() is not False,
'error', 'Cache {0} seemingly created OK, but FS did not activate'.format(dev)):
return False
if attach:
return _alltrue(attach_())
else:
return True
def config_(dev=None, **kwargs):
'''
Show or update config of a bcache device.
If no device is given, operate on the cache set itself.
CLI example:
.. code-block:: bash
salt '*' bcache.config
salt '*' bcache.config bcache1
salt '*' bcache.config errors=panic journal_delay_ms=150
salt '*' bcache.config bcache1 cache_mode=writeback writeback_percent=15
:return: config or True/False
'''
if dev is None:
spath = _fspath()
else:
spath = _bcpath(dev)
# filter out 'hidden' kwargs added by our favourite orchestration system
updates = dict([(key, val) for key, val in kwargs.items() if not key.startswith('__')])
if updates:
endres = 0
for key, val in updates.items():
endres += _sysfs_attr([spath, key], val,
'warn', 'Failed to update {0} with {1}'.format(os.path.join(spath, key), val))
return endres > 0
else:
result = {}
data = _sysfs_parse(spath, config=True, internals=True, options=True)
for key in ('other_ro', 'inter_ro'):
if key in data:
del data[key]
for key in data:
result.update(data[key])
return result
def status(stats=False, config=False, internals=False, superblock=False, alldevs=False):
'''
Show the full status of the BCache system and optionally all it's involved devices
CLI example:
.. code-block:: bash
salt '*' bcache.status
salt '*' bcache.status stats=True
salt '*' bcache.status internals=True alldevs=True
:param stats: include statistics
:param config: include settings
:param internals: include internals
:param superblock: include superblock
'''
bdevs = []
for _, links, _ in salt.utils.path.os_walk('/sys/block/'):
for block in links:
if 'bcache' in block:
continue
for spath, sdirs, _ in salt.utils.path.os_walk('/sys/block/{0}'.format(block), followlinks=False):
if 'bcache' in sdirs:
bdevs.append(os.path.basename(spath))
statii = {}
for bcache in bdevs:
statii[bcache] = device(bcache, stats, config, internals, superblock)
cuuid = uuid()
cdev = _bdev()
if cdev:
count = 0
for dev in statii:
if dev != cdev:
# it's a backing dev
if statii[dev]['cache'] == cuuid:
count += 1
statii[cdev]['attached_backing_devices'] = count
if not alldevs:
statii = statii[cdev]
return statii
def device(dev, stats=False, config=False, internals=False, superblock=False):
'''
Check the state of a single bcache device
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc stats=True
:param stats: include statistics
:param settings: include all settings
:param internals: include all internals
:param superblock: include superblock info
'''
result = {}
if not _sysfs_attr(_bcpath(dev), None, 'error', '{0} is not a bcache fo any kind'.format(dev)):
return False
elif _bcsys(dev, 'set'):
# ---------------- It's the cache itself ----------------
result['uuid'] = uuid()
base_attr = ['block_size', 'bucket_size', 'cache_available_percent', 'cache_replacement_policy', 'congested']
# ---------------- Parse through both the blockdev & the FS ----------------
result.update(_sysfs_parse(_bcpath(dev), base_attr, stats, config, internals))
result.update(_sysfs_parse(_fspath(), base_attr, stats, config, internals))
result.update(result.pop('base'))
else:
# ---------------- It's a backing device ----------------
back_uuid = uuid(dev)
if back_uuid is not None:
result['cache'] = back_uuid
try:
result['dev'] = os.path.basename(_bcsys(dev, 'dev'))
except Exception:
pass
result['bdev'] = _bdev(dev)
base_attr = ['cache_mode', 'running', 'state', 'writeback_running']
base_path = _bcpath(dev)
result.update(_sysfs_parse(base_path, base_attr, stats, config, internals))
result.update(result.pop('base'))
# ---------------- Modifications ----------------
state = [result['state']]
if result.pop('running'):
state.append('running')
else:
state.append('stopped')
if 'writeback_running' in result:
if result.pop('writeback_running'):
state.append('writeback_running')
else:
state.append('writeback_stopped')
result['state'] = state
# ---------------- Statistics ----------------
if 'stats' in result:
replre = r'(stats|cache)_'
statres = result['stats']
for attr in result['stats']:
if '/' not in attr:
key = re.sub(replre, '', attr)
statres[key] = statres.pop(attr)
else:
stat, key = attr.split('/', 1)
stat = re.sub(replre, '', stat)
key = re.sub(replre, '', key)
if stat not in statres:
statres[stat] = {}
statres[stat][key] = statres.pop(attr)
result['stats'] = statres
# ---------------- Internals ----------------
if internals:
interres = result.pop('inter_ro', {})
interres.update(result.pop('inter_rw', {}))
if interres:
for key in interres:
if key.startswith('internal'):
nkey = re.sub(r'internal[s/]*', '', key)
interres[nkey] = interres.pop(key)
key = nkey
if key.startswith(('btree', 'writeback')):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in interres:
interres[mkey] = {}
interres[mkey][skey] = interres.pop(key)
result['internals'] = interres
# ---------------- Config ----------------
if config:
configres = result['config']
for key in configres:
if key.startswith('writeback'):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in configres:
configres[mkey] = {}
configres[mkey][skey] = configres.pop(key)
result['config'] = configres
# ---------------- Superblock ----------------
if superblock:
result['superblock'] = super_(dev)
return result
def super_(dev):
'''
Read out BCache SuperBlock
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc
'''
dev = _devpath(dev)
ret = {}
res = _run_all('bcache-super-show {0}'.format(dev), 'error', 'Error reading superblock on {0}: %s'.format(dev))
if not res:
return False
for line in res.splitlines(): # pylint: disable=no-member
line = line.strip()
if not line:
continue
key, val = [val.strip() for val in re.split(r'[\s]+', line, maxsplit=1)]
if not (key and val):
continue
mval = None
if ' ' in val:
rval, mval = [val.strip() for val in re.split(r'[\s]+', val, maxsplit=1)]
mval = mval[1:-1]
else:
rval = val
try:
rval = int(rval)
except Exception:
try:
rval = float(rval)
except Exception:
if rval == 'yes':
rval = True
elif rval == 'no':
rval = False
pkey, key = re.split(r'\.', key, maxsplit=1)
if pkey not in ret:
ret[pkey] = {}
if mval is not None:
ret[pkey][key] = (rval, mval)
else:
ret[pkey][key] = rval
return ret
# -------------------------------- HELPER FUNCTIONS --------------------------------
def _devbase(dev):
'''
Basename of just about any dev
'''
dev = os.path.realpath(os.path.expandvars(dev))
dev = os.path.basename(dev)
return dev
def _devpath(dev):
'''
Return /dev name of just about any dev
:return: /dev/devicename
'''
return os.path.join('/dev', _devbase(dev))
def _syspath(dev):
'''
Full SysFS path of a device
'''
dev = _devbase(dev)
dev = re.sub(r'^([vhs][a-z]+)([0-9]+)', r'\1/\1\2', dev)
# name = re.sub(r'^([a-z]+)(?<!(bcache|md|dm))([0-9]+)', r'\1/\1\2', name)
return os.path.join('/sys/block/', dev)
def _bdev(dev=None):
'''
Resolve a bcacheX or cache to a real dev
:return: basename of bcache dev
'''
if dev is None:
dev = _fssys('cache0')
else:
dev = _bcpath(dev)
if not dev:
return False
else:
return _devbase(os.path.dirname(dev))
def _bcpath(dev):
'''
Full SysFS path of a bcache device
'''
return os.path.join(_syspath(dev), 'bcache')
def _fspath():
'''
:return: path of active bcache
'''
cuuid = uuid()
if not cuuid:
return False
else:
return os.path.join('/sys/fs/bcache/', cuuid)
def _fssys(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with bcache SysFS
'''
fspath = _fspath()
if not fspath:
return False
else:
return _sysfs_attr([fspath, name], value, log_lvl, log_msg)
def _bcsys(dev, name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with backing devs SysFS
'''
return _sysfs_attr([_bcpath(dev), name], value, log_lvl, log_msg)
def _sysfs_attr(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper with logging around sysfs.attr
'''
if isinstance(name, six.string_types):
name = [name]
res = __salt__['sysfs.attr'](os.path.join(*name), value)
if not res and log_lvl is not None and log_msg is not None:
log.log(LOG[log_lvl], log_msg)
return res
def _sysfs_parse(path, base_attr=None, stats=False, config=False, internals=False, options=False):
'''
Helper function for parsing BCache's SysFS interface
'''
result = {}
# ---------------- Parse through the interfaces list ----------------
intfs = __salt__['sysfs.interfaces'](path)
# Actions, we ignore
del intfs['w']
# -------- Sorting hat --------
binkeys = []
if internals:
binkeys.extend(['inter_ro', 'inter_rw'])
if config:
binkeys.append('config')
if stats:
binkeys.append('stats')
bintf = {}
for key in binkeys:
bintf[key] = []
for intf in intfs['r']:
if intf.startswith('internal'):
key = 'inter_ro'
elif 'stats' in intf:
key = 'stats'
else:
# What to do with these???
# I'll utilize 'inter_ro' as 'misc' as well
key = 'inter_ro'
if key in bintf:
bintf[key].append(intf)
for intf in intfs['rw']:
if intf.startswith('internal'):
key = 'inter_rw'
else:
key = 'config'
if key in bintf:
bintf[key].append(intf)
if base_attr is not None:
for intf in bintf:
bintf[intf] = [sintf for sintf in bintf[intf] if sintf not in base_attr]
bintf['base'] = base_attr
mods = {
'stats': ['internal/bset_tree_stats', 'writeback_rate_debug', 'metadata_written', 'nbuckets', 'written',
'average_key_size', 'btree_cache_size'],
}
for modt, modlist in mods.items():
found = []
if modt not in bintf:
continue
for mod in modlist:
for intflist in bintf.values():
if mod in intflist:
found.append(mod)
intflist.remove(mod)
bintf[modt] += found
# -------- Fetch SysFS vals --------
bintflist = [intf for iflist in bintf.values() for intf in iflist]
result.update(__salt__['sysfs.read'](bintflist, path))
# -------- Parse through well known string lists --------
for strlist in ('writeback_rate_debug', 'internal/bset_tree_stats', 'priority_stats'):
if strlist in result:
listres = {}
for line in result[strlist].split('\n'):
key, val = line.split(':', 1)
val = val.strip()
try:
val = int(val)
except Exception:
try:
val = float(val)
except Exception:
pass
listres[key.strip()] = val
result[strlist] = listres
# -------- Parse through selection lists --------
if not options:
for sellist in ('cache_mode', 'cache_replacement_policy', 'errors'):
if sellist in result:
result[sellist] = re.search(r'\[(.+)\]', result[sellist]).groups()[0]
# -------- Parse through well known bools --------
for boolkey in ('running', 'writeback_running', 'congested'):
if boolkey in result:
result[boolkey] = bool(result[boolkey])
# -------- Recategorize results --------
bresult = {}
for iftype, intflist in bintf.items():
ifres = {}
for intf in intflist:
if intf in result:
ifres[intf] = result.pop(intf)
if ifres:
bresult[iftype] = ifres
return bresult
def _size_map(size):
'''
Map Bcache's size strings to real bytes
'''
try:
# I know, I know, EAFP.
# But everything else is reason for None
if not isinstance(size, int):
if re.search(r'[Kk]', size):
size = 1024 * float(re.sub(r'[Kk]', '', size))
elif re.search(r'[Mm]', size):
size = 1024**2 * float(re.sub(r'[Mm]', '', size))
size = int(size)
return size
except Exception:
return None
def _sizes(dev):
'''
Return neigh useless sizing info about a blockdev
:return: (total size in blocks, blocksize, maximum discard size in bytes)
'''
dev = _devbase(dev)
# standarization yay
block_sizes = ('hw_sector_size', 'minimum_io_size', 'physical_block_size', 'logical_block_size')
discard_sizes = ('discard_max_bytes', 'discard_max_hw_bytes', )
sysfs = __salt__['sysfs.read'](
('size',
'queue/hw_sector_size', '../queue/hw_sector_size',
'queue/discard_max_bytes', '../queue/discard_max_bytes'),
root=_syspath(dev))
# TODO: makes no sense
# First of all, it has to be a power of 2
# Secondly, this returns 4GiB - 512b on Intel 3500's for some weird reason
# discard_granularity seems in bytes, resolves to 512b ???
# max_hw_sectors_kb???
# There's also discard_max_hw_bytes more recently
# See: https://www.kernel.org/doc/Documentation/block/queue-sysfs.txt
# Also, I cant find any docs yet regarding bucket sizes;
# it's supposed to be discard_max_hw_bytes,
# but no way to figure that one reliably out apparently
discard = sysfs.get('queue/discard_max_bytes', sysfs.get('../queue/discard_max_bytes', None))
block = sysfs.get('queue/hw_sector_size', sysfs.get('../queue/hw_sector_size', None))
return 512*sysfs['size'], block, discard
def _wipe(dev):
'''
REALLY DESTRUCTIVE STUFF RIGHT AHEAD
'''
endres = 0
dev = _devbase(dev)
size, block, discard = _sizes(dev)
if discard is None:
log.error('Unable to read SysFS props for %s', dev)
return None
elif not discard:
log.warning('%s seems unable to discard', dev)
wiper = 'dd'
elif not HAS_BLKDISCARD:
log.warning('blkdiscard binary not available, properly wipe the dev manually for optimal results')
wiper = 'dd'
else:
wiper = 'blkdiscard'
wipe_failmsg = 'Error wiping {0}: %s'.format(dev)
if wiper == 'dd':
blocks = 4
cmd = 'dd if=/dev/zero of=/dev/{0} bs=1M count={1}'.format(dev, blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# Some stuff (<cough>GPT</cough>) writes stuff at the end of a dev as well
cmd += ' seek={0}'.format((size/1024**2) - blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
elif wiper == 'blkdiscard':
cmd = 'blkdiscard /dev/{0}'.format(dev)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# TODO: fix annoying bug failing blkdiscard by trying to discard 1 sector past blkdev
endres = 1
return endres > 0
def _wait(lfunc, log_lvl=None, log_msg=None, tries=10):
'''
Wait for lfunc to be True
:return: True if lfunc succeeded within tries, False if it didn't
'''
i = 0
while i < tries:
time.sleep(1)
if lfunc():
return True
else:
i += 1
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg)
return False
def _run_all(cmd, log_lvl=None, log_msg=None, exitcode=0):
'''
Simple wrapper around cmd.run_all
log_msg can contain {0} for stderr
:return: True or stdout, False if retcode wasn't exitcode
'''
res = __salt__['cmd.run_all'](cmd)
if res['retcode'] == exitcode:
if res['stdout']:
return res['stdout']
else:
return True
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg, res['stderr'])
return False
def _alltrue(resdict):
if resdict is None:
return True
return len([val for val in resdict.values() if val]) > 0
|
saltstack/salt
|
salt/modules/bcache.py
|
back_make
|
python
|
def back_make(dev, cache_mode='writeback', force=False, attach=True, bucket_size=None):
'''
Create a backing device for attachment to a set.
Because the block size must be the same, a cache set already needs to exist.
CLI example:
.. code-block:: bash
salt '*' bcache.back_make sdc cache_mode=writeback attach=True
:param cache_mode: writethrough, writeback, writearound or none.
:param force: Overwrite existing bcaches
:param attach: Immediately attach the backing device to the set
:param bucket_size: Size of a bucket (see kernel doc)
'''
# pylint: disable=too-many-return-statements
cache = uuid()
if not cache:
log.error('No bcache set found')
return False
elif _sysfs_attr(_bcpath(dev)):
if not force:
log.error('%s already contains a bcache. Wipe it manually or use force', dev)
return False
elif uuid(dev) and not detach(dev):
return False
elif not stop(dev):
return False
dev = _devpath(dev)
block_size = _size_map(_fssys('block_size'))
# You might want to override, we pick the cache set's as sane default
if bucket_size is None:
bucket_size = _size_map(_fssys('bucket_size'))
cmd = 'make-bcache --block {0} --bucket {1} --{2} --bdev {3}'.format(block_size, bucket_size, cache_mode, dev)
if force:
cmd += ' --wipe-bcache'
if not _run_all(cmd, 'error', 'Error creating backing device {0}: %s'.format(dev)):
return False
elif not _sysfs_attr('fs/bcache/register', _devpath(dev),
'error', 'Error registering backing device {0}'.format(dev)):
return False
elif not _wait(lambda: _sysfs_attr(_bcpath(dev)) is not False,
'error', 'Backing device {0} did not register'.format(dev)):
return False
elif attach:
return attach_(dev)
return True
|
Create a backing device for attachment to a set.
Because the block size must be the same, a cache set already needs to exist.
CLI example:
.. code-block:: bash
salt '*' bcache.back_make sdc cache_mode=writeback attach=True
:param cache_mode: writethrough, writeback, writearound or none.
:param force: Overwrite existing bcaches
:param attach: Immediately attach the backing device to the set
:param bucket_size: Size of a bucket (see kernel doc)
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bcache.py#L211-L264
|
[
"def uuid(dev=None):\n '''\n Return the bcache UUID of a block device.\n If no device is given, the Cache UUID is returned.\n\n CLI example:\n\n .. code-block:: bash\n\n salt '*' bcache.uuid\n salt '*' bcache.uuid /dev/sda\n salt '*' bcache.uuid bcache0\n\n '''\n try:\n if dev is None:\n # take the only directory in /sys/fs/bcache and return it's basename\n return list(salt.utils.path.os_walk('/sys/fs/bcache/'))[0][1][0]\n else:\n # basename of the /sys/block/{dev}/bcache/cache symlink target\n return os.path.basename(_bcsys(dev, 'cache'))\n except Exception:\n return False\n",
"def _wait(lfunc, log_lvl=None, log_msg=None, tries=10):\n '''\n Wait for lfunc to be True\n :return: True if lfunc succeeded within tries, False if it didn't\n '''\n i = 0\n while i < tries:\n time.sleep(1)\n\n if lfunc():\n return True\n else:\n i += 1\n if log_lvl is not None:\n log.log(LOG[log_lvl], log_msg)\n return False\n",
"def attach_(dev=None):\n '''\n Attach a backing devices to a cache set\n If no dev is given, all backing devices will be attached.\n\n CLI example:\n\n .. code-block:: bash\n\n salt '*' bcache.attach sdc\n salt '*' bcache.attach /dev/bcache1\n\n\n :return: bool or None if nuttin' happened\n '''\n cache = uuid()\n if not cache:\n log.error('No cache to attach %s to', dev)\n return False\n\n if dev is None:\n res = {}\n for dev, data in status(alldevs=True).items():\n if 'cache' in data:\n res[dev] = attach_(dev)\n\n return res if res else None\n\n bcache = uuid(dev)\n if bcache:\n if bcache == cache:\n log.info('%s is already attached to bcache %s, doing nothing', dev, cache)\n return None\n elif not detach(dev):\n return False\n\n log.debug('Attaching %s to bcache %s', dev, cache)\n\n if not _bcsys(dev, 'attach', cache,\n 'error', 'Error attaching {0} to bcache {1}'.format(dev, cache)):\n return False\n\n return _wait(lambda: uuid(dev) == cache,\n 'error', '{0} received attach to bcache {1}, but did not comply'.format(dev, cache))\n",
"def _run_all(cmd, log_lvl=None, log_msg=None, exitcode=0):\n '''\n Simple wrapper around cmd.run_all\n log_msg can contain {0} for stderr\n :return: True or stdout, False if retcode wasn't exitcode\n '''\n res = __salt__['cmd.run_all'](cmd)\n if res['retcode'] == exitcode:\n if res['stdout']:\n return res['stdout']\n else:\n return True\n\n if log_lvl is not None:\n log.log(LOG[log_lvl], log_msg, res['stderr'])\n return False\n",
"def _sysfs_attr(name, value=None, log_lvl=None, log_msg=None):\n '''\n Simple wrapper with logging around sysfs.attr\n '''\n if isinstance(name, six.string_types):\n name = [name]\n res = __salt__['sysfs.attr'](os.path.join(*name), value)\n if not res and log_lvl is not None and log_msg is not None:\n log.log(LOG[log_lvl], log_msg)\n return res\n",
"def _bcpath(dev):\n '''\n Full SysFS path of a bcache device\n '''\n return os.path.join(_syspath(dev), 'bcache')\n",
"def _fssys(name, value=None, log_lvl=None, log_msg=None):\n '''\n Simple wrapper to interface with bcache SysFS\n '''\n fspath = _fspath()\n if not fspath:\n return False\n else:\n return _sysfs_attr([fspath, name], value, log_lvl, log_msg)\n",
"def _devpath(dev):\n '''\n Return /dev name of just about any dev\n :return: /dev/devicename\n '''\n return os.path.join('/dev', _devbase(dev))\n",
"def _size_map(size):\n '''\n Map Bcache's size strings to real bytes\n '''\n try:\n # I know, I know, EAFP.\n # But everything else is reason for None\n if not isinstance(size, int):\n if re.search(r'[Kk]', size):\n size = 1024 * float(re.sub(r'[Kk]', '', size))\n elif re.search(r'[Mm]', size):\n size = 1024**2 * float(re.sub(r'[Mm]', '', size))\n size = int(size)\n return size\n except Exception:\n return None\n"
] |
# -*- coding: utf-8 -*-
'''
Module for managing BCache sets
BCache is a block-level caching mechanism similar to ZFS L2ARC/ZIL, dm-cache and fscache.
It works by formatting one block device as a cache set, then adding backend devices
(which need to be formatted as such) to the set and activating them.
It's available in Linux mainline kernel since 3.10
https://www.kernel.org/doc/Documentation/bcache.txt
This module needs the bcache userspace tools to function.
.. versionadded: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import time
import re
from salt.ext import six
# Import salt libs
import salt.utils.path
log = logging.getLogger(__name__)
LOG = {
'trace': logging.TRACE,
'debug': logging.DEBUG,
'info': logging.INFO,
'warn': logging.WARNING,
'error': logging.ERROR,
'crit': logging.CRITICAL,
}
__func_alias__ = {
'attach_': 'attach',
'config_': 'config',
'super_': 'super',
}
HAS_BLKDISCARD = salt.utils.path.which('blkdiscard') is not None
def __virtual__():
'''
Only work when make-bcache is installed
'''
return salt.utils.path.which('make-bcache') is not None
def uuid(dev=None):
'''
Return the bcache UUID of a block device.
If no device is given, the Cache UUID is returned.
CLI example:
.. code-block:: bash
salt '*' bcache.uuid
salt '*' bcache.uuid /dev/sda
salt '*' bcache.uuid bcache0
'''
try:
if dev is None:
# take the only directory in /sys/fs/bcache and return it's basename
return list(salt.utils.path.os_walk('/sys/fs/bcache/'))[0][1][0]
else:
# basename of the /sys/block/{dev}/bcache/cache symlink target
return os.path.basename(_bcsys(dev, 'cache'))
except Exception:
return False
def attach_(dev=None):
'''
Attach a backing devices to a cache set
If no dev is given, all backing devices will be attached.
CLI example:
.. code-block:: bash
salt '*' bcache.attach sdc
salt '*' bcache.attach /dev/bcache1
:return: bool or None if nuttin' happened
'''
cache = uuid()
if not cache:
log.error('No cache to attach %s to', dev)
return False
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = attach_(dev)
return res if res else None
bcache = uuid(dev)
if bcache:
if bcache == cache:
log.info('%s is already attached to bcache %s, doing nothing', dev, cache)
return None
elif not detach(dev):
return False
log.debug('Attaching %s to bcache %s', dev, cache)
if not _bcsys(dev, 'attach', cache,
'error', 'Error attaching {0} to bcache {1}'.format(dev, cache)):
return False
return _wait(lambda: uuid(dev) == cache,
'error', '{0} received attach to bcache {1}, but did not comply'.format(dev, cache))
def detach(dev=None):
'''
Detach a backing device(s) from a cache set
If no dev is given, all backing devices will be attached.
Detaching a backing device will flush it's write cache.
This should leave the underlying device in a consistent state, but might take a while.
CLI example:
.. code-block:: bash
salt '*' bcache.detach sdc
salt '*' bcache.detach bcache1
'''
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = detach(dev)
return res if res else None
log.debug('Detaching %s', dev)
if not _bcsys(dev, 'detach', 'goaway', 'error', 'Error detaching {0}'.format(dev)):
return False
return _wait(lambda: uuid(dev) is False, 'error', '{0} received detach, but did not comply'.format(dev), 300)
def start():
'''
Trigger a start of the full bcache system through udev.
CLI example:
.. code-block:: bash
salt '*' bcache.start
'''
if not _run_all('udevadm trigger', 'error', 'Error starting bcache: %s'):
return False
elif not _wait(lambda: uuid() is not False, 'warn', 'Bcache system started, but no active cache set found.'):
return False
return True
def stop(dev=None):
'''
Stop a bcache device
If no device is given, all backing devices will be detached from the cache, which will subsequently be stopped.
.. warning::
'Stop' on an individual backing device means hard-stop;
no attempt at flushing will be done and the bcache device will seemingly 'disappear' from the device lists
CLI example:
.. code-block:: bash
salt '*' bcache.stop
'''
if dev is not None:
log.warning('Stopping %s, device will only reappear after reregistering!', dev)
if not _bcsys(dev, 'stop', 'goaway', 'error', 'Error stopping {0}'.format(dev)):
return False
return _wait(lambda: _sysfs_attr(_bcpath(dev)) is False, 'error', 'Device {0} did not stop'.format(dev), 300)
else:
cache = uuid()
if not cache:
log.warning('bcache already stopped?')
return None
if not _alltrue(detach()):
return False
elif not _fssys('stop', 'goaway', 'error', 'Error stopping cache'):
return False
return _wait(lambda: uuid() is False, 'error', 'Cache did not stop', 300)
def cache_make(dev, reserved=None, force=False, block_size=None, bucket_size=None, attach=True):
'''
Create BCache cache on a block device.
If blkdiscard is available the entire device will be properly cleared in advance.
CLI example:
.. code-block:: bash
salt '*' bcache.cache_make sdb reserved=10% block_size=4096
:param reserved: if dev is a full device, create a partition table with this size empty.
.. note::
this increases the amount of reserved space available to SSD garbage collectors,
potentially (vastly) increasing performance
:param block_size: Block size of the cache; defaults to devices' logical block size
:param force: Overwrite existing BCache sets
:param attach: Attach all existing backend devices immediately
'''
# TODO: multiple devs == md jbod
# pylint: disable=too-many-return-statements
# ---------------- Preflight checks ----------------
cache = uuid()
if cache:
if not force:
log.error('BCache cache %s is already on the system', cache)
return False
cache = _bdev()
dev = _devbase(dev)
udev = __salt__['udev.env'](dev)
if ('ID_FS_TYPE' in udev or (udev.get('DEVTYPE', None) != 'partition' and 'ID_PART_TABLE_TYPE' in udev)) \
and not force:
log.error('%s already contains data, wipe first or force', dev)
return False
elif reserved is not None and udev.get('DEVTYPE', None) != 'disk':
log.error('Need a partitionable blockdev for reserved to work')
return False
_, block, bucket = _sizes(dev)
if bucket_size is None:
bucket_size = bucket
# TODO: bucket from _sizes() makes no sense
bucket_size = False
if block_size is None:
block_size = block
# ---------------- Still here, start doing destructive stuff ----------------
if cache:
if not stop():
return False
# Wipe the current cache device as well,
# forever ruining any chance of it accidentally popping up again
elif not _wipe(cache):
return False
# Can't do enough wiping
if not _wipe(dev):
return False
if reserved:
cmd = 'parted -m -s -a optimal -- ' \
'/dev/{0} mklabel gpt mkpart bcache-reserved 1M {1} mkpart bcache {1} 100%'.format(dev, reserved)
# if wipe was incomplete & part layout remains the same,
# this is one condition set where udev would make it accidentally popup again
if not _run_all(cmd, 'error', 'Error creating bcache partitions on {0}: %s'.format(dev)):
return False
dev = '{0}2'.format(dev)
# ---------------- Finally, create a cache ----------------
cmd = 'make-bcache --cache /dev/{0} --block {1} --wipe-bcache'.format(dev, block_size)
# Actually bucket_size should always have a value, but for testing 0 is possible as well
if bucket_size:
cmd += ' --bucket {0}'.format(bucket_size)
if not _run_all(cmd, 'error', 'Error creating cache {0}: %s'.format(dev)):
return False
elif not _wait(lambda: uuid() is not False,
'error', 'Cache {0} seemingly created OK, but FS did not activate'.format(dev)):
return False
if attach:
return _alltrue(attach_())
else:
return True
def config_(dev=None, **kwargs):
'''
Show or update config of a bcache device.
If no device is given, operate on the cache set itself.
CLI example:
.. code-block:: bash
salt '*' bcache.config
salt '*' bcache.config bcache1
salt '*' bcache.config errors=panic journal_delay_ms=150
salt '*' bcache.config bcache1 cache_mode=writeback writeback_percent=15
:return: config or True/False
'''
if dev is None:
spath = _fspath()
else:
spath = _bcpath(dev)
# filter out 'hidden' kwargs added by our favourite orchestration system
updates = dict([(key, val) for key, val in kwargs.items() if not key.startswith('__')])
if updates:
endres = 0
for key, val in updates.items():
endres += _sysfs_attr([spath, key], val,
'warn', 'Failed to update {0} with {1}'.format(os.path.join(spath, key), val))
return endres > 0
else:
result = {}
data = _sysfs_parse(spath, config=True, internals=True, options=True)
for key in ('other_ro', 'inter_ro'):
if key in data:
del data[key]
for key in data:
result.update(data[key])
return result
def status(stats=False, config=False, internals=False, superblock=False, alldevs=False):
'''
Show the full status of the BCache system and optionally all it's involved devices
CLI example:
.. code-block:: bash
salt '*' bcache.status
salt '*' bcache.status stats=True
salt '*' bcache.status internals=True alldevs=True
:param stats: include statistics
:param config: include settings
:param internals: include internals
:param superblock: include superblock
'''
bdevs = []
for _, links, _ in salt.utils.path.os_walk('/sys/block/'):
for block in links:
if 'bcache' in block:
continue
for spath, sdirs, _ in salt.utils.path.os_walk('/sys/block/{0}'.format(block), followlinks=False):
if 'bcache' in sdirs:
bdevs.append(os.path.basename(spath))
statii = {}
for bcache in bdevs:
statii[bcache] = device(bcache, stats, config, internals, superblock)
cuuid = uuid()
cdev = _bdev()
if cdev:
count = 0
for dev in statii:
if dev != cdev:
# it's a backing dev
if statii[dev]['cache'] == cuuid:
count += 1
statii[cdev]['attached_backing_devices'] = count
if not alldevs:
statii = statii[cdev]
return statii
def device(dev, stats=False, config=False, internals=False, superblock=False):
'''
Check the state of a single bcache device
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc stats=True
:param stats: include statistics
:param settings: include all settings
:param internals: include all internals
:param superblock: include superblock info
'''
result = {}
if not _sysfs_attr(_bcpath(dev), None, 'error', '{0} is not a bcache fo any kind'.format(dev)):
return False
elif _bcsys(dev, 'set'):
# ---------------- It's the cache itself ----------------
result['uuid'] = uuid()
base_attr = ['block_size', 'bucket_size', 'cache_available_percent', 'cache_replacement_policy', 'congested']
# ---------------- Parse through both the blockdev & the FS ----------------
result.update(_sysfs_parse(_bcpath(dev), base_attr, stats, config, internals))
result.update(_sysfs_parse(_fspath(), base_attr, stats, config, internals))
result.update(result.pop('base'))
else:
# ---------------- It's a backing device ----------------
back_uuid = uuid(dev)
if back_uuid is not None:
result['cache'] = back_uuid
try:
result['dev'] = os.path.basename(_bcsys(dev, 'dev'))
except Exception:
pass
result['bdev'] = _bdev(dev)
base_attr = ['cache_mode', 'running', 'state', 'writeback_running']
base_path = _bcpath(dev)
result.update(_sysfs_parse(base_path, base_attr, stats, config, internals))
result.update(result.pop('base'))
# ---------------- Modifications ----------------
state = [result['state']]
if result.pop('running'):
state.append('running')
else:
state.append('stopped')
if 'writeback_running' in result:
if result.pop('writeback_running'):
state.append('writeback_running')
else:
state.append('writeback_stopped')
result['state'] = state
# ---------------- Statistics ----------------
if 'stats' in result:
replre = r'(stats|cache)_'
statres = result['stats']
for attr in result['stats']:
if '/' not in attr:
key = re.sub(replre, '', attr)
statres[key] = statres.pop(attr)
else:
stat, key = attr.split('/', 1)
stat = re.sub(replre, '', stat)
key = re.sub(replre, '', key)
if stat not in statres:
statres[stat] = {}
statres[stat][key] = statres.pop(attr)
result['stats'] = statres
# ---------------- Internals ----------------
if internals:
interres = result.pop('inter_ro', {})
interres.update(result.pop('inter_rw', {}))
if interres:
for key in interres:
if key.startswith('internal'):
nkey = re.sub(r'internal[s/]*', '', key)
interres[nkey] = interres.pop(key)
key = nkey
if key.startswith(('btree', 'writeback')):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in interres:
interres[mkey] = {}
interres[mkey][skey] = interres.pop(key)
result['internals'] = interres
# ---------------- Config ----------------
if config:
configres = result['config']
for key in configres:
if key.startswith('writeback'):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in configres:
configres[mkey] = {}
configres[mkey][skey] = configres.pop(key)
result['config'] = configres
# ---------------- Superblock ----------------
if superblock:
result['superblock'] = super_(dev)
return result
def super_(dev):
'''
Read out BCache SuperBlock
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc
'''
dev = _devpath(dev)
ret = {}
res = _run_all('bcache-super-show {0}'.format(dev), 'error', 'Error reading superblock on {0}: %s'.format(dev))
if not res:
return False
for line in res.splitlines(): # pylint: disable=no-member
line = line.strip()
if not line:
continue
key, val = [val.strip() for val in re.split(r'[\s]+', line, maxsplit=1)]
if not (key and val):
continue
mval = None
if ' ' in val:
rval, mval = [val.strip() for val in re.split(r'[\s]+', val, maxsplit=1)]
mval = mval[1:-1]
else:
rval = val
try:
rval = int(rval)
except Exception:
try:
rval = float(rval)
except Exception:
if rval == 'yes':
rval = True
elif rval == 'no':
rval = False
pkey, key = re.split(r'\.', key, maxsplit=1)
if pkey not in ret:
ret[pkey] = {}
if mval is not None:
ret[pkey][key] = (rval, mval)
else:
ret[pkey][key] = rval
return ret
# -------------------------------- HELPER FUNCTIONS --------------------------------
def _devbase(dev):
'''
Basename of just about any dev
'''
dev = os.path.realpath(os.path.expandvars(dev))
dev = os.path.basename(dev)
return dev
def _devpath(dev):
'''
Return /dev name of just about any dev
:return: /dev/devicename
'''
return os.path.join('/dev', _devbase(dev))
def _syspath(dev):
'''
Full SysFS path of a device
'''
dev = _devbase(dev)
dev = re.sub(r'^([vhs][a-z]+)([0-9]+)', r'\1/\1\2', dev)
# name = re.sub(r'^([a-z]+)(?<!(bcache|md|dm))([0-9]+)', r'\1/\1\2', name)
return os.path.join('/sys/block/', dev)
def _bdev(dev=None):
'''
Resolve a bcacheX or cache to a real dev
:return: basename of bcache dev
'''
if dev is None:
dev = _fssys('cache0')
else:
dev = _bcpath(dev)
if not dev:
return False
else:
return _devbase(os.path.dirname(dev))
def _bcpath(dev):
'''
Full SysFS path of a bcache device
'''
return os.path.join(_syspath(dev), 'bcache')
def _fspath():
'''
:return: path of active bcache
'''
cuuid = uuid()
if not cuuid:
return False
else:
return os.path.join('/sys/fs/bcache/', cuuid)
def _fssys(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with bcache SysFS
'''
fspath = _fspath()
if not fspath:
return False
else:
return _sysfs_attr([fspath, name], value, log_lvl, log_msg)
def _bcsys(dev, name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with backing devs SysFS
'''
return _sysfs_attr([_bcpath(dev), name], value, log_lvl, log_msg)
def _sysfs_attr(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper with logging around sysfs.attr
'''
if isinstance(name, six.string_types):
name = [name]
res = __salt__['sysfs.attr'](os.path.join(*name), value)
if not res and log_lvl is not None and log_msg is not None:
log.log(LOG[log_lvl], log_msg)
return res
def _sysfs_parse(path, base_attr=None, stats=False, config=False, internals=False, options=False):
'''
Helper function for parsing BCache's SysFS interface
'''
result = {}
# ---------------- Parse through the interfaces list ----------------
intfs = __salt__['sysfs.interfaces'](path)
# Actions, we ignore
del intfs['w']
# -------- Sorting hat --------
binkeys = []
if internals:
binkeys.extend(['inter_ro', 'inter_rw'])
if config:
binkeys.append('config')
if stats:
binkeys.append('stats')
bintf = {}
for key in binkeys:
bintf[key] = []
for intf in intfs['r']:
if intf.startswith('internal'):
key = 'inter_ro'
elif 'stats' in intf:
key = 'stats'
else:
# What to do with these???
# I'll utilize 'inter_ro' as 'misc' as well
key = 'inter_ro'
if key in bintf:
bintf[key].append(intf)
for intf in intfs['rw']:
if intf.startswith('internal'):
key = 'inter_rw'
else:
key = 'config'
if key in bintf:
bintf[key].append(intf)
if base_attr is not None:
for intf in bintf:
bintf[intf] = [sintf for sintf in bintf[intf] if sintf not in base_attr]
bintf['base'] = base_attr
mods = {
'stats': ['internal/bset_tree_stats', 'writeback_rate_debug', 'metadata_written', 'nbuckets', 'written',
'average_key_size', 'btree_cache_size'],
}
for modt, modlist in mods.items():
found = []
if modt not in bintf:
continue
for mod in modlist:
for intflist in bintf.values():
if mod in intflist:
found.append(mod)
intflist.remove(mod)
bintf[modt] += found
# -------- Fetch SysFS vals --------
bintflist = [intf for iflist in bintf.values() for intf in iflist]
result.update(__salt__['sysfs.read'](bintflist, path))
# -------- Parse through well known string lists --------
for strlist in ('writeback_rate_debug', 'internal/bset_tree_stats', 'priority_stats'):
if strlist in result:
listres = {}
for line in result[strlist].split('\n'):
key, val = line.split(':', 1)
val = val.strip()
try:
val = int(val)
except Exception:
try:
val = float(val)
except Exception:
pass
listres[key.strip()] = val
result[strlist] = listres
# -------- Parse through selection lists --------
if not options:
for sellist in ('cache_mode', 'cache_replacement_policy', 'errors'):
if sellist in result:
result[sellist] = re.search(r'\[(.+)\]', result[sellist]).groups()[0]
# -------- Parse through well known bools --------
for boolkey in ('running', 'writeback_running', 'congested'):
if boolkey in result:
result[boolkey] = bool(result[boolkey])
# -------- Recategorize results --------
bresult = {}
for iftype, intflist in bintf.items():
ifres = {}
for intf in intflist:
if intf in result:
ifres[intf] = result.pop(intf)
if ifres:
bresult[iftype] = ifres
return bresult
def _size_map(size):
'''
Map Bcache's size strings to real bytes
'''
try:
# I know, I know, EAFP.
# But everything else is reason for None
if not isinstance(size, int):
if re.search(r'[Kk]', size):
size = 1024 * float(re.sub(r'[Kk]', '', size))
elif re.search(r'[Mm]', size):
size = 1024**2 * float(re.sub(r'[Mm]', '', size))
size = int(size)
return size
except Exception:
return None
def _sizes(dev):
'''
Return neigh useless sizing info about a blockdev
:return: (total size in blocks, blocksize, maximum discard size in bytes)
'''
dev = _devbase(dev)
# standarization yay
block_sizes = ('hw_sector_size', 'minimum_io_size', 'physical_block_size', 'logical_block_size')
discard_sizes = ('discard_max_bytes', 'discard_max_hw_bytes', )
sysfs = __salt__['sysfs.read'](
('size',
'queue/hw_sector_size', '../queue/hw_sector_size',
'queue/discard_max_bytes', '../queue/discard_max_bytes'),
root=_syspath(dev))
# TODO: makes no sense
# First of all, it has to be a power of 2
# Secondly, this returns 4GiB - 512b on Intel 3500's for some weird reason
# discard_granularity seems in bytes, resolves to 512b ???
# max_hw_sectors_kb???
# There's also discard_max_hw_bytes more recently
# See: https://www.kernel.org/doc/Documentation/block/queue-sysfs.txt
# Also, I cant find any docs yet regarding bucket sizes;
# it's supposed to be discard_max_hw_bytes,
# but no way to figure that one reliably out apparently
discard = sysfs.get('queue/discard_max_bytes', sysfs.get('../queue/discard_max_bytes', None))
block = sysfs.get('queue/hw_sector_size', sysfs.get('../queue/hw_sector_size', None))
return 512*sysfs['size'], block, discard
def _wipe(dev):
'''
REALLY DESTRUCTIVE STUFF RIGHT AHEAD
'''
endres = 0
dev = _devbase(dev)
size, block, discard = _sizes(dev)
if discard is None:
log.error('Unable to read SysFS props for %s', dev)
return None
elif not discard:
log.warning('%s seems unable to discard', dev)
wiper = 'dd'
elif not HAS_BLKDISCARD:
log.warning('blkdiscard binary not available, properly wipe the dev manually for optimal results')
wiper = 'dd'
else:
wiper = 'blkdiscard'
wipe_failmsg = 'Error wiping {0}: %s'.format(dev)
if wiper == 'dd':
blocks = 4
cmd = 'dd if=/dev/zero of=/dev/{0} bs=1M count={1}'.format(dev, blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# Some stuff (<cough>GPT</cough>) writes stuff at the end of a dev as well
cmd += ' seek={0}'.format((size/1024**2) - blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
elif wiper == 'blkdiscard':
cmd = 'blkdiscard /dev/{0}'.format(dev)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# TODO: fix annoying bug failing blkdiscard by trying to discard 1 sector past blkdev
endres = 1
return endres > 0
def _wait(lfunc, log_lvl=None, log_msg=None, tries=10):
'''
Wait for lfunc to be True
:return: True if lfunc succeeded within tries, False if it didn't
'''
i = 0
while i < tries:
time.sleep(1)
if lfunc():
return True
else:
i += 1
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg)
return False
def _run_all(cmd, log_lvl=None, log_msg=None, exitcode=0):
'''
Simple wrapper around cmd.run_all
log_msg can contain {0} for stderr
:return: True or stdout, False if retcode wasn't exitcode
'''
res = __salt__['cmd.run_all'](cmd)
if res['retcode'] == exitcode:
if res['stdout']:
return res['stdout']
else:
return True
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg, res['stderr'])
return False
def _alltrue(resdict):
if resdict is None:
return True
return len([val for val in resdict.values() if val]) > 0
|
saltstack/salt
|
salt/modules/bcache.py
|
cache_make
|
python
|
def cache_make(dev, reserved=None, force=False, block_size=None, bucket_size=None, attach=True):
'''
Create BCache cache on a block device.
If blkdiscard is available the entire device will be properly cleared in advance.
CLI example:
.. code-block:: bash
salt '*' bcache.cache_make sdb reserved=10% block_size=4096
:param reserved: if dev is a full device, create a partition table with this size empty.
.. note::
this increases the amount of reserved space available to SSD garbage collectors,
potentially (vastly) increasing performance
:param block_size: Block size of the cache; defaults to devices' logical block size
:param force: Overwrite existing BCache sets
:param attach: Attach all existing backend devices immediately
'''
# TODO: multiple devs == md jbod
# pylint: disable=too-many-return-statements
# ---------------- Preflight checks ----------------
cache = uuid()
if cache:
if not force:
log.error('BCache cache %s is already on the system', cache)
return False
cache = _bdev()
dev = _devbase(dev)
udev = __salt__['udev.env'](dev)
if ('ID_FS_TYPE' in udev or (udev.get('DEVTYPE', None) != 'partition' and 'ID_PART_TABLE_TYPE' in udev)) \
and not force:
log.error('%s already contains data, wipe first or force', dev)
return False
elif reserved is not None and udev.get('DEVTYPE', None) != 'disk':
log.error('Need a partitionable blockdev for reserved to work')
return False
_, block, bucket = _sizes(dev)
if bucket_size is None:
bucket_size = bucket
# TODO: bucket from _sizes() makes no sense
bucket_size = False
if block_size is None:
block_size = block
# ---------------- Still here, start doing destructive stuff ----------------
if cache:
if not stop():
return False
# Wipe the current cache device as well,
# forever ruining any chance of it accidentally popping up again
elif not _wipe(cache):
return False
# Can't do enough wiping
if not _wipe(dev):
return False
if reserved:
cmd = 'parted -m -s -a optimal -- ' \
'/dev/{0} mklabel gpt mkpart bcache-reserved 1M {1} mkpart bcache {1} 100%'.format(dev, reserved)
# if wipe was incomplete & part layout remains the same,
# this is one condition set where udev would make it accidentally popup again
if not _run_all(cmd, 'error', 'Error creating bcache partitions on {0}: %s'.format(dev)):
return False
dev = '{0}2'.format(dev)
# ---------------- Finally, create a cache ----------------
cmd = 'make-bcache --cache /dev/{0} --block {1} --wipe-bcache'.format(dev, block_size)
# Actually bucket_size should always have a value, but for testing 0 is possible as well
if bucket_size:
cmd += ' --bucket {0}'.format(bucket_size)
if not _run_all(cmd, 'error', 'Error creating cache {0}: %s'.format(dev)):
return False
elif not _wait(lambda: uuid() is not False,
'error', 'Cache {0} seemingly created OK, but FS did not activate'.format(dev)):
return False
if attach:
return _alltrue(attach_())
else:
return True
|
Create BCache cache on a block device.
If blkdiscard is available the entire device will be properly cleared in advance.
CLI example:
.. code-block:: bash
salt '*' bcache.cache_make sdb reserved=10% block_size=4096
:param reserved: if dev is a full device, create a partition table with this size empty.
.. note::
this increases the amount of reserved space available to SSD garbage collectors,
potentially (vastly) increasing performance
:param block_size: Block size of the cache; defaults to devices' logical block size
:param force: Overwrite existing BCache sets
:param attach: Attach all existing backend devices immediately
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bcache.py#L267-L357
|
[
"def stop(dev=None):\n '''\n Stop a bcache device\n If no device is given, all backing devices will be detached from the cache, which will subsequently be stopped.\n\n .. warning::\n 'Stop' on an individual backing device means hard-stop;\n no attempt at flushing will be done and the bcache device will seemingly 'disappear' from the device lists\n\n CLI example:\n\n .. code-block:: bash\n\n salt '*' bcache.stop\n\n '''\n if dev is not None:\n log.warning('Stopping %s, device will only reappear after reregistering!', dev)\n if not _bcsys(dev, 'stop', 'goaway', 'error', 'Error stopping {0}'.format(dev)):\n return False\n return _wait(lambda: _sysfs_attr(_bcpath(dev)) is False, 'error', 'Device {0} did not stop'.format(dev), 300)\n else:\n cache = uuid()\n if not cache:\n log.warning('bcache already stopped?')\n return None\n\n if not _alltrue(detach()):\n return False\n elif not _fssys('stop', 'goaway', 'error', 'Error stopping cache'):\n return False\n\n return _wait(lambda: uuid() is False, 'error', 'Cache did not stop', 300)\n",
"def uuid(dev=None):\n '''\n Return the bcache UUID of a block device.\n If no device is given, the Cache UUID is returned.\n\n CLI example:\n\n .. code-block:: bash\n\n salt '*' bcache.uuid\n salt '*' bcache.uuid /dev/sda\n salt '*' bcache.uuid bcache0\n\n '''\n try:\n if dev is None:\n # take the only directory in /sys/fs/bcache and return it's basename\n return list(salt.utils.path.os_walk('/sys/fs/bcache/'))[0][1][0]\n else:\n # basename of the /sys/block/{dev}/bcache/cache symlink target\n return os.path.basename(_bcsys(dev, 'cache'))\n except Exception:\n return False\n",
"def _sizes(dev):\n '''\n Return neigh useless sizing info about a blockdev\n :return: (total size in blocks, blocksize, maximum discard size in bytes)\n '''\n dev = _devbase(dev)\n\n # standarization yay\n block_sizes = ('hw_sector_size', 'minimum_io_size', 'physical_block_size', 'logical_block_size')\n discard_sizes = ('discard_max_bytes', 'discard_max_hw_bytes', )\n\n sysfs = __salt__['sysfs.read'](\n ('size',\n 'queue/hw_sector_size', '../queue/hw_sector_size',\n 'queue/discard_max_bytes', '../queue/discard_max_bytes'),\n root=_syspath(dev))\n\n # TODO: makes no sense\n # First of all, it has to be a power of 2\n # Secondly, this returns 4GiB - 512b on Intel 3500's for some weird reason\n # discard_granularity seems in bytes, resolves to 512b ???\n # max_hw_sectors_kb???\n # There's also discard_max_hw_bytes more recently\n # See: https://www.kernel.org/doc/Documentation/block/queue-sysfs.txt\n # Also, I cant find any docs yet regarding bucket sizes;\n # it's supposed to be discard_max_hw_bytes,\n # but no way to figure that one reliably out apparently\n\n discard = sysfs.get('queue/discard_max_bytes', sysfs.get('../queue/discard_max_bytes', None))\n block = sysfs.get('queue/hw_sector_size', sysfs.get('../queue/hw_sector_size', None))\n\n return 512*sysfs['size'], block, discard\n",
"def _wait(lfunc, log_lvl=None, log_msg=None, tries=10):\n '''\n Wait for lfunc to be True\n :return: True if lfunc succeeded within tries, False if it didn't\n '''\n i = 0\n while i < tries:\n time.sleep(1)\n\n if lfunc():\n return True\n else:\n i += 1\n if log_lvl is not None:\n log.log(LOG[log_lvl], log_msg)\n return False\n",
"def attach_(dev=None):\n '''\n Attach a backing devices to a cache set\n If no dev is given, all backing devices will be attached.\n\n CLI example:\n\n .. code-block:: bash\n\n salt '*' bcache.attach sdc\n salt '*' bcache.attach /dev/bcache1\n\n\n :return: bool or None if nuttin' happened\n '''\n cache = uuid()\n if not cache:\n log.error('No cache to attach %s to', dev)\n return False\n\n if dev is None:\n res = {}\n for dev, data in status(alldevs=True).items():\n if 'cache' in data:\n res[dev] = attach_(dev)\n\n return res if res else None\n\n bcache = uuid(dev)\n if bcache:\n if bcache == cache:\n log.info('%s is already attached to bcache %s, doing nothing', dev, cache)\n return None\n elif not detach(dev):\n return False\n\n log.debug('Attaching %s to bcache %s', dev, cache)\n\n if not _bcsys(dev, 'attach', cache,\n 'error', 'Error attaching {0} to bcache {1}'.format(dev, cache)):\n return False\n\n return _wait(lambda: uuid(dev) == cache,\n 'error', '{0} received attach to bcache {1}, but did not comply'.format(dev, cache))\n",
"def _run_all(cmd, log_lvl=None, log_msg=None, exitcode=0):\n '''\n Simple wrapper around cmd.run_all\n log_msg can contain {0} for stderr\n :return: True or stdout, False if retcode wasn't exitcode\n '''\n res = __salt__['cmd.run_all'](cmd)\n if res['retcode'] == exitcode:\n if res['stdout']:\n return res['stdout']\n else:\n return True\n\n if log_lvl is not None:\n log.log(LOG[log_lvl], log_msg, res['stderr'])\n return False\n",
"def _alltrue(resdict):\n if resdict is None:\n return True\n return len([val for val in resdict.values() if val]) > 0\n",
"def _bdev(dev=None):\n '''\n Resolve a bcacheX or cache to a real dev\n :return: basename of bcache dev\n '''\n if dev is None:\n dev = _fssys('cache0')\n else:\n dev = _bcpath(dev)\n\n if not dev:\n return False\n else:\n return _devbase(os.path.dirname(dev))\n",
"def _devbase(dev):\n '''\n Basename of just about any dev\n '''\n dev = os.path.realpath(os.path.expandvars(dev))\n dev = os.path.basename(dev)\n return dev\n",
"def _wipe(dev):\n '''\n REALLY DESTRUCTIVE STUFF RIGHT AHEAD\n '''\n endres = 0\n dev = _devbase(dev)\n\n size, block, discard = _sizes(dev)\n\n if discard is None:\n log.error('Unable to read SysFS props for %s', dev)\n return None\n elif not discard:\n log.warning('%s seems unable to discard', dev)\n wiper = 'dd'\n elif not HAS_BLKDISCARD:\n log.warning('blkdiscard binary not available, properly wipe the dev manually for optimal results')\n wiper = 'dd'\n else:\n wiper = 'blkdiscard'\n\n wipe_failmsg = 'Error wiping {0}: %s'.format(dev)\n if wiper == 'dd':\n blocks = 4\n cmd = 'dd if=/dev/zero of=/dev/{0} bs=1M count={1}'.format(dev, blocks)\n endres += _run_all(cmd, 'warn', wipe_failmsg)\n\n # Some stuff (<cough>GPT</cough>) writes stuff at the end of a dev as well\n cmd += ' seek={0}'.format((size/1024**2) - blocks)\n endres += _run_all(cmd, 'warn', wipe_failmsg)\n\n elif wiper == 'blkdiscard':\n cmd = 'blkdiscard /dev/{0}'.format(dev)\n endres += _run_all(cmd, 'warn', wipe_failmsg)\n # TODO: fix annoying bug failing blkdiscard by trying to discard 1 sector past blkdev\n endres = 1\n\n return endres > 0\n"
] |
# -*- coding: utf-8 -*-
'''
Module for managing BCache sets
BCache is a block-level caching mechanism similar to ZFS L2ARC/ZIL, dm-cache and fscache.
It works by formatting one block device as a cache set, then adding backend devices
(which need to be formatted as such) to the set and activating them.
It's available in Linux mainline kernel since 3.10
https://www.kernel.org/doc/Documentation/bcache.txt
This module needs the bcache userspace tools to function.
.. versionadded: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import time
import re
from salt.ext import six
# Import salt libs
import salt.utils.path
log = logging.getLogger(__name__)
LOG = {
'trace': logging.TRACE,
'debug': logging.DEBUG,
'info': logging.INFO,
'warn': logging.WARNING,
'error': logging.ERROR,
'crit': logging.CRITICAL,
}
__func_alias__ = {
'attach_': 'attach',
'config_': 'config',
'super_': 'super',
}
HAS_BLKDISCARD = salt.utils.path.which('blkdiscard') is not None
def __virtual__():
'''
Only work when make-bcache is installed
'''
return salt.utils.path.which('make-bcache') is not None
def uuid(dev=None):
'''
Return the bcache UUID of a block device.
If no device is given, the Cache UUID is returned.
CLI example:
.. code-block:: bash
salt '*' bcache.uuid
salt '*' bcache.uuid /dev/sda
salt '*' bcache.uuid bcache0
'''
try:
if dev is None:
# take the only directory in /sys/fs/bcache and return it's basename
return list(salt.utils.path.os_walk('/sys/fs/bcache/'))[0][1][0]
else:
# basename of the /sys/block/{dev}/bcache/cache symlink target
return os.path.basename(_bcsys(dev, 'cache'))
except Exception:
return False
def attach_(dev=None):
'''
Attach a backing devices to a cache set
If no dev is given, all backing devices will be attached.
CLI example:
.. code-block:: bash
salt '*' bcache.attach sdc
salt '*' bcache.attach /dev/bcache1
:return: bool or None if nuttin' happened
'''
cache = uuid()
if not cache:
log.error('No cache to attach %s to', dev)
return False
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = attach_(dev)
return res if res else None
bcache = uuid(dev)
if bcache:
if bcache == cache:
log.info('%s is already attached to bcache %s, doing nothing', dev, cache)
return None
elif not detach(dev):
return False
log.debug('Attaching %s to bcache %s', dev, cache)
if not _bcsys(dev, 'attach', cache,
'error', 'Error attaching {0} to bcache {1}'.format(dev, cache)):
return False
return _wait(lambda: uuid(dev) == cache,
'error', '{0} received attach to bcache {1}, but did not comply'.format(dev, cache))
def detach(dev=None):
'''
Detach a backing device(s) from a cache set
If no dev is given, all backing devices will be attached.
Detaching a backing device will flush it's write cache.
This should leave the underlying device in a consistent state, but might take a while.
CLI example:
.. code-block:: bash
salt '*' bcache.detach sdc
salt '*' bcache.detach bcache1
'''
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = detach(dev)
return res if res else None
log.debug('Detaching %s', dev)
if not _bcsys(dev, 'detach', 'goaway', 'error', 'Error detaching {0}'.format(dev)):
return False
return _wait(lambda: uuid(dev) is False, 'error', '{0} received detach, but did not comply'.format(dev), 300)
def start():
'''
Trigger a start of the full bcache system through udev.
CLI example:
.. code-block:: bash
salt '*' bcache.start
'''
if not _run_all('udevadm trigger', 'error', 'Error starting bcache: %s'):
return False
elif not _wait(lambda: uuid() is not False, 'warn', 'Bcache system started, but no active cache set found.'):
return False
return True
def stop(dev=None):
'''
Stop a bcache device
If no device is given, all backing devices will be detached from the cache, which will subsequently be stopped.
.. warning::
'Stop' on an individual backing device means hard-stop;
no attempt at flushing will be done and the bcache device will seemingly 'disappear' from the device lists
CLI example:
.. code-block:: bash
salt '*' bcache.stop
'''
if dev is not None:
log.warning('Stopping %s, device will only reappear after reregistering!', dev)
if not _bcsys(dev, 'stop', 'goaway', 'error', 'Error stopping {0}'.format(dev)):
return False
return _wait(lambda: _sysfs_attr(_bcpath(dev)) is False, 'error', 'Device {0} did not stop'.format(dev), 300)
else:
cache = uuid()
if not cache:
log.warning('bcache already stopped?')
return None
if not _alltrue(detach()):
return False
elif not _fssys('stop', 'goaway', 'error', 'Error stopping cache'):
return False
return _wait(lambda: uuid() is False, 'error', 'Cache did not stop', 300)
def back_make(dev, cache_mode='writeback', force=False, attach=True, bucket_size=None):
'''
Create a backing device for attachment to a set.
Because the block size must be the same, a cache set already needs to exist.
CLI example:
.. code-block:: bash
salt '*' bcache.back_make sdc cache_mode=writeback attach=True
:param cache_mode: writethrough, writeback, writearound or none.
:param force: Overwrite existing bcaches
:param attach: Immediately attach the backing device to the set
:param bucket_size: Size of a bucket (see kernel doc)
'''
# pylint: disable=too-many-return-statements
cache = uuid()
if not cache:
log.error('No bcache set found')
return False
elif _sysfs_attr(_bcpath(dev)):
if not force:
log.error('%s already contains a bcache. Wipe it manually or use force', dev)
return False
elif uuid(dev) and not detach(dev):
return False
elif not stop(dev):
return False
dev = _devpath(dev)
block_size = _size_map(_fssys('block_size'))
# You might want to override, we pick the cache set's as sane default
if bucket_size is None:
bucket_size = _size_map(_fssys('bucket_size'))
cmd = 'make-bcache --block {0} --bucket {1} --{2} --bdev {3}'.format(block_size, bucket_size, cache_mode, dev)
if force:
cmd += ' --wipe-bcache'
if not _run_all(cmd, 'error', 'Error creating backing device {0}: %s'.format(dev)):
return False
elif not _sysfs_attr('fs/bcache/register', _devpath(dev),
'error', 'Error registering backing device {0}'.format(dev)):
return False
elif not _wait(lambda: _sysfs_attr(_bcpath(dev)) is not False,
'error', 'Backing device {0} did not register'.format(dev)):
return False
elif attach:
return attach_(dev)
return True
def config_(dev=None, **kwargs):
'''
Show or update config of a bcache device.
If no device is given, operate on the cache set itself.
CLI example:
.. code-block:: bash
salt '*' bcache.config
salt '*' bcache.config bcache1
salt '*' bcache.config errors=panic journal_delay_ms=150
salt '*' bcache.config bcache1 cache_mode=writeback writeback_percent=15
:return: config or True/False
'''
if dev is None:
spath = _fspath()
else:
spath = _bcpath(dev)
# filter out 'hidden' kwargs added by our favourite orchestration system
updates = dict([(key, val) for key, val in kwargs.items() if not key.startswith('__')])
if updates:
endres = 0
for key, val in updates.items():
endres += _sysfs_attr([spath, key], val,
'warn', 'Failed to update {0} with {1}'.format(os.path.join(spath, key), val))
return endres > 0
else:
result = {}
data = _sysfs_parse(spath, config=True, internals=True, options=True)
for key in ('other_ro', 'inter_ro'):
if key in data:
del data[key]
for key in data:
result.update(data[key])
return result
def status(stats=False, config=False, internals=False, superblock=False, alldevs=False):
'''
Show the full status of the BCache system and optionally all it's involved devices
CLI example:
.. code-block:: bash
salt '*' bcache.status
salt '*' bcache.status stats=True
salt '*' bcache.status internals=True alldevs=True
:param stats: include statistics
:param config: include settings
:param internals: include internals
:param superblock: include superblock
'''
bdevs = []
for _, links, _ in salt.utils.path.os_walk('/sys/block/'):
for block in links:
if 'bcache' in block:
continue
for spath, sdirs, _ in salt.utils.path.os_walk('/sys/block/{0}'.format(block), followlinks=False):
if 'bcache' in sdirs:
bdevs.append(os.path.basename(spath))
statii = {}
for bcache in bdevs:
statii[bcache] = device(bcache, stats, config, internals, superblock)
cuuid = uuid()
cdev = _bdev()
if cdev:
count = 0
for dev in statii:
if dev != cdev:
# it's a backing dev
if statii[dev]['cache'] == cuuid:
count += 1
statii[cdev]['attached_backing_devices'] = count
if not alldevs:
statii = statii[cdev]
return statii
def device(dev, stats=False, config=False, internals=False, superblock=False):
'''
Check the state of a single bcache device
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc stats=True
:param stats: include statistics
:param settings: include all settings
:param internals: include all internals
:param superblock: include superblock info
'''
result = {}
if not _sysfs_attr(_bcpath(dev), None, 'error', '{0} is not a bcache fo any kind'.format(dev)):
return False
elif _bcsys(dev, 'set'):
# ---------------- It's the cache itself ----------------
result['uuid'] = uuid()
base_attr = ['block_size', 'bucket_size', 'cache_available_percent', 'cache_replacement_policy', 'congested']
# ---------------- Parse through both the blockdev & the FS ----------------
result.update(_sysfs_parse(_bcpath(dev), base_attr, stats, config, internals))
result.update(_sysfs_parse(_fspath(), base_attr, stats, config, internals))
result.update(result.pop('base'))
else:
# ---------------- It's a backing device ----------------
back_uuid = uuid(dev)
if back_uuid is not None:
result['cache'] = back_uuid
try:
result['dev'] = os.path.basename(_bcsys(dev, 'dev'))
except Exception:
pass
result['bdev'] = _bdev(dev)
base_attr = ['cache_mode', 'running', 'state', 'writeback_running']
base_path = _bcpath(dev)
result.update(_sysfs_parse(base_path, base_attr, stats, config, internals))
result.update(result.pop('base'))
# ---------------- Modifications ----------------
state = [result['state']]
if result.pop('running'):
state.append('running')
else:
state.append('stopped')
if 'writeback_running' in result:
if result.pop('writeback_running'):
state.append('writeback_running')
else:
state.append('writeback_stopped')
result['state'] = state
# ---------------- Statistics ----------------
if 'stats' in result:
replre = r'(stats|cache)_'
statres = result['stats']
for attr in result['stats']:
if '/' not in attr:
key = re.sub(replre, '', attr)
statres[key] = statres.pop(attr)
else:
stat, key = attr.split('/', 1)
stat = re.sub(replre, '', stat)
key = re.sub(replre, '', key)
if stat not in statres:
statres[stat] = {}
statres[stat][key] = statres.pop(attr)
result['stats'] = statres
# ---------------- Internals ----------------
if internals:
interres = result.pop('inter_ro', {})
interres.update(result.pop('inter_rw', {}))
if interres:
for key in interres:
if key.startswith('internal'):
nkey = re.sub(r'internal[s/]*', '', key)
interres[nkey] = interres.pop(key)
key = nkey
if key.startswith(('btree', 'writeback')):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in interres:
interres[mkey] = {}
interres[mkey][skey] = interres.pop(key)
result['internals'] = interres
# ---------------- Config ----------------
if config:
configres = result['config']
for key in configres:
if key.startswith('writeback'):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in configres:
configres[mkey] = {}
configres[mkey][skey] = configres.pop(key)
result['config'] = configres
# ---------------- Superblock ----------------
if superblock:
result['superblock'] = super_(dev)
return result
def super_(dev):
'''
Read out BCache SuperBlock
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc
'''
dev = _devpath(dev)
ret = {}
res = _run_all('bcache-super-show {0}'.format(dev), 'error', 'Error reading superblock on {0}: %s'.format(dev))
if not res:
return False
for line in res.splitlines(): # pylint: disable=no-member
line = line.strip()
if not line:
continue
key, val = [val.strip() for val in re.split(r'[\s]+', line, maxsplit=1)]
if not (key and val):
continue
mval = None
if ' ' in val:
rval, mval = [val.strip() for val in re.split(r'[\s]+', val, maxsplit=1)]
mval = mval[1:-1]
else:
rval = val
try:
rval = int(rval)
except Exception:
try:
rval = float(rval)
except Exception:
if rval == 'yes':
rval = True
elif rval == 'no':
rval = False
pkey, key = re.split(r'\.', key, maxsplit=1)
if pkey not in ret:
ret[pkey] = {}
if mval is not None:
ret[pkey][key] = (rval, mval)
else:
ret[pkey][key] = rval
return ret
# -------------------------------- HELPER FUNCTIONS --------------------------------
def _devbase(dev):
'''
Basename of just about any dev
'''
dev = os.path.realpath(os.path.expandvars(dev))
dev = os.path.basename(dev)
return dev
def _devpath(dev):
'''
Return /dev name of just about any dev
:return: /dev/devicename
'''
return os.path.join('/dev', _devbase(dev))
def _syspath(dev):
'''
Full SysFS path of a device
'''
dev = _devbase(dev)
dev = re.sub(r'^([vhs][a-z]+)([0-9]+)', r'\1/\1\2', dev)
# name = re.sub(r'^([a-z]+)(?<!(bcache|md|dm))([0-9]+)', r'\1/\1\2', name)
return os.path.join('/sys/block/', dev)
def _bdev(dev=None):
'''
Resolve a bcacheX or cache to a real dev
:return: basename of bcache dev
'''
if dev is None:
dev = _fssys('cache0')
else:
dev = _bcpath(dev)
if not dev:
return False
else:
return _devbase(os.path.dirname(dev))
def _bcpath(dev):
'''
Full SysFS path of a bcache device
'''
return os.path.join(_syspath(dev), 'bcache')
def _fspath():
'''
:return: path of active bcache
'''
cuuid = uuid()
if not cuuid:
return False
else:
return os.path.join('/sys/fs/bcache/', cuuid)
def _fssys(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with bcache SysFS
'''
fspath = _fspath()
if not fspath:
return False
else:
return _sysfs_attr([fspath, name], value, log_lvl, log_msg)
def _bcsys(dev, name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with backing devs SysFS
'''
return _sysfs_attr([_bcpath(dev), name], value, log_lvl, log_msg)
def _sysfs_attr(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper with logging around sysfs.attr
'''
if isinstance(name, six.string_types):
name = [name]
res = __salt__['sysfs.attr'](os.path.join(*name), value)
if not res and log_lvl is not None and log_msg is not None:
log.log(LOG[log_lvl], log_msg)
return res
def _sysfs_parse(path, base_attr=None, stats=False, config=False, internals=False, options=False):
'''
Helper function for parsing BCache's SysFS interface
'''
result = {}
# ---------------- Parse through the interfaces list ----------------
intfs = __salt__['sysfs.interfaces'](path)
# Actions, we ignore
del intfs['w']
# -------- Sorting hat --------
binkeys = []
if internals:
binkeys.extend(['inter_ro', 'inter_rw'])
if config:
binkeys.append('config')
if stats:
binkeys.append('stats')
bintf = {}
for key in binkeys:
bintf[key] = []
for intf in intfs['r']:
if intf.startswith('internal'):
key = 'inter_ro'
elif 'stats' in intf:
key = 'stats'
else:
# What to do with these???
# I'll utilize 'inter_ro' as 'misc' as well
key = 'inter_ro'
if key in bintf:
bintf[key].append(intf)
for intf in intfs['rw']:
if intf.startswith('internal'):
key = 'inter_rw'
else:
key = 'config'
if key in bintf:
bintf[key].append(intf)
if base_attr is not None:
for intf in bintf:
bintf[intf] = [sintf for sintf in bintf[intf] if sintf not in base_attr]
bintf['base'] = base_attr
mods = {
'stats': ['internal/bset_tree_stats', 'writeback_rate_debug', 'metadata_written', 'nbuckets', 'written',
'average_key_size', 'btree_cache_size'],
}
for modt, modlist in mods.items():
found = []
if modt not in bintf:
continue
for mod in modlist:
for intflist in bintf.values():
if mod in intflist:
found.append(mod)
intflist.remove(mod)
bintf[modt] += found
# -------- Fetch SysFS vals --------
bintflist = [intf for iflist in bintf.values() for intf in iflist]
result.update(__salt__['sysfs.read'](bintflist, path))
# -------- Parse through well known string lists --------
for strlist in ('writeback_rate_debug', 'internal/bset_tree_stats', 'priority_stats'):
if strlist in result:
listres = {}
for line in result[strlist].split('\n'):
key, val = line.split(':', 1)
val = val.strip()
try:
val = int(val)
except Exception:
try:
val = float(val)
except Exception:
pass
listres[key.strip()] = val
result[strlist] = listres
# -------- Parse through selection lists --------
if not options:
for sellist in ('cache_mode', 'cache_replacement_policy', 'errors'):
if sellist in result:
result[sellist] = re.search(r'\[(.+)\]', result[sellist]).groups()[0]
# -------- Parse through well known bools --------
for boolkey in ('running', 'writeback_running', 'congested'):
if boolkey in result:
result[boolkey] = bool(result[boolkey])
# -------- Recategorize results --------
bresult = {}
for iftype, intflist in bintf.items():
ifres = {}
for intf in intflist:
if intf in result:
ifres[intf] = result.pop(intf)
if ifres:
bresult[iftype] = ifres
return bresult
def _size_map(size):
'''
Map Bcache's size strings to real bytes
'''
try:
# I know, I know, EAFP.
# But everything else is reason for None
if not isinstance(size, int):
if re.search(r'[Kk]', size):
size = 1024 * float(re.sub(r'[Kk]', '', size))
elif re.search(r'[Mm]', size):
size = 1024**2 * float(re.sub(r'[Mm]', '', size))
size = int(size)
return size
except Exception:
return None
def _sizes(dev):
'''
Return neigh useless sizing info about a blockdev
:return: (total size in blocks, blocksize, maximum discard size in bytes)
'''
dev = _devbase(dev)
# standarization yay
block_sizes = ('hw_sector_size', 'minimum_io_size', 'physical_block_size', 'logical_block_size')
discard_sizes = ('discard_max_bytes', 'discard_max_hw_bytes', )
sysfs = __salt__['sysfs.read'](
('size',
'queue/hw_sector_size', '../queue/hw_sector_size',
'queue/discard_max_bytes', '../queue/discard_max_bytes'),
root=_syspath(dev))
# TODO: makes no sense
# First of all, it has to be a power of 2
# Secondly, this returns 4GiB - 512b on Intel 3500's for some weird reason
# discard_granularity seems in bytes, resolves to 512b ???
# max_hw_sectors_kb???
# There's also discard_max_hw_bytes more recently
# See: https://www.kernel.org/doc/Documentation/block/queue-sysfs.txt
# Also, I cant find any docs yet regarding bucket sizes;
# it's supposed to be discard_max_hw_bytes,
# but no way to figure that one reliably out apparently
discard = sysfs.get('queue/discard_max_bytes', sysfs.get('../queue/discard_max_bytes', None))
block = sysfs.get('queue/hw_sector_size', sysfs.get('../queue/hw_sector_size', None))
return 512*sysfs['size'], block, discard
def _wipe(dev):
'''
REALLY DESTRUCTIVE STUFF RIGHT AHEAD
'''
endres = 0
dev = _devbase(dev)
size, block, discard = _sizes(dev)
if discard is None:
log.error('Unable to read SysFS props for %s', dev)
return None
elif not discard:
log.warning('%s seems unable to discard', dev)
wiper = 'dd'
elif not HAS_BLKDISCARD:
log.warning('blkdiscard binary not available, properly wipe the dev manually for optimal results')
wiper = 'dd'
else:
wiper = 'blkdiscard'
wipe_failmsg = 'Error wiping {0}: %s'.format(dev)
if wiper == 'dd':
blocks = 4
cmd = 'dd if=/dev/zero of=/dev/{0} bs=1M count={1}'.format(dev, blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# Some stuff (<cough>GPT</cough>) writes stuff at the end of a dev as well
cmd += ' seek={0}'.format((size/1024**2) - blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
elif wiper == 'blkdiscard':
cmd = 'blkdiscard /dev/{0}'.format(dev)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# TODO: fix annoying bug failing blkdiscard by trying to discard 1 sector past blkdev
endres = 1
return endres > 0
def _wait(lfunc, log_lvl=None, log_msg=None, tries=10):
'''
Wait for lfunc to be True
:return: True if lfunc succeeded within tries, False if it didn't
'''
i = 0
while i < tries:
time.sleep(1)
if lfunc():
return True
else:
i += 1
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg)
return False
def _run_all(cmd, log_lvl=None, log_msg=None, exitcode=0):
'''
Simple wrapper around cmd.run_all
log_msg can contain {0} for stderr
:return: True or stdout, False if retcode wasn't exitcode
'''
res = __salt__['cmd.run_all'](cmd)
if res['retcode'] == exitcode:
if res['stdout']:
return res['stdout']
else:
return True
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg, res['stderr'])
return False
def _alltrue(resdict):
if resdict is None:
return True
return len([val for val in resdict.values() if val]) > 0
|
saltstack/salt
|
salt/modules/bcache.py
|
config_
|
python
|
def config_(dev=None, **kwargs):
'''
Show or update config of a bcache device.
If no device is given, operate on the cache set itself.
CLI example:
.. code-block:: bash
salt '*' bcache.config
salt '*' bcache.config bcache1
salt '*' bcache.config errors=panic journal_delay_ms=150
salt '*' bcache.config bcache1 cache_mode=writeback writeback_percent=15
:return: config or True/False
'''
if dev is None:
spath = _fspath()
else:
spath = _bcpath(dev)
# filter out 'hidden' kwargs added by our favourite orchestration system
updates = dict([(key, val) for key, val in kwargs.items() if not key.startswith('__')])
if updates:
endres = 0
for key, val in updates.items():
endres += _sysfs_attr([spath, key], val,
'warn', 'Failed to update {0} with {1}'.format(os.path.join(spath, key), val))
return endres > 0
else:
result = {}
data = _sysfs_parse(spath, config=True, internals=True, options=True)
for key in ('other_ro', 'inter_ro'):
if key in data:
del data[key]
for key in data:
result.update(data[key])
return result
|
Show or update config of a bcache device.
If no device is given, operate on the cache set itself.
CLI example:
.. code-block:: bash
salt '*' bcache.config
salt '*' bcache.config bcache1
salt '*' bcache.config errors=panic journal_delay_ms=150
salt '*' bcache.config bcache1 cache_mode=writeback writeback_percent=15
:return: config or True/False
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bcache.py#L360-L401
|
[
"def _sysfs_attr(name, value=None, log_lvl=None, log_msg=None):\n '''\n Simple wrapper with logging around sysfs.attr\n '''\n if isinstance(name, six.string_types):\n name = [name]\n res = __salt__['sysfs.attr'](os.path.join(*name), value)\n if not res and log_lvl is not None and log_msg is not None:\n log.log(LOG[log_lvl], log_msg)\n return res\n",
"def _bcpath(dev):\n '''\n Full SysFS path of a bcache device\n '''\n return os.path.join(_syspath(dev), 'bcache')\n",
"def _fspath():\n '''\n :return: path of active bcache\n '''\n cuuid = uuid()\n if not cuuid:\n return False\n else:\n return os.path.join('/sys/fs/bcache/', cuuid)\n",
"def _sysfs_parse(path, base_attr=None, stats=False, config=False, internals=False, options=False):\n '''\n Helper function for parsing BCache's SysFS interface\n '''\n result = {}\n\n # ---------------- Parse through the interfaces list ----------------\n intfs = __salt__['sysfs.interfaces'](path)\n\n # Actions, we ignore\n del intfs['w']\n\n # -------- Sorting hat --------\n binkeys = []\n if internals:\n binkeys.extend(['inter_ro', 'inter_rw'])\n if config:\n binkeys.append('config')\n if stats:\n binkeys.append('stats')\n\n bintf = {}\n for key in binkeys:\n bintf[key] = []\n\n for intf in intfs['r']:\n if intf.startswith('internal'):\n key = 'inter_ro'\n elif 'stats' in intf:\n key = 'stats'\n else:\n # What to do with these???\n # I'll utilize 'inter_ro' as 'misc' as well\n key = 'inter_ro'\n\n if key in bintf:\n bintf[key].append(intf)\n\n for intf in intfs['rw']:\n if intf.startswith('internal'):\n key = 'inter_rw'\n else:\n key = 'config'\n\n if key in bintf:\n bintf[key].append(intf)\n\n if base_attr is not None:\n for intf in bintf:\n bintf[intf] = [sintf for sintf in bintf[intf] if sintf not in base_attr]\n bintf['base'] = base_attr\n\n mods = {\n 'stats': ['internal/bset_tree_stats', 'writeback_rate_debug', 'metadata_written', 'nbuckets', 'written',\n 'average_key_size', 'btree_cache_size'],\n }\n\n for modt, modlist in mods.items():\n found = []\n if modt not in bintf:\n continue\n for mod in modlist:\n for intflist in bintf.values():\n if mod in intflist:\n found.append(mod)\n intflist.remove(mod)\n bintf[modt] += found\n\n # -------- Fetch SysFS vals --------\n bintflist = [intf for iflist in bintf.values() for intf in iflist]\n result.update(__salt__['sysfs.read'](bintflist, path))\n\n # -------- Parse through well known string lists --------\n for strlist in ('writeback_rate_debug', 'internal/bset_tree_stats', 'priority_stats'):\n if strlist in result:\n listres = {}\n for line in result[strlist].split('\\n'):\n key, val = line.split(':', 1)\n val = val.strip()\n try:\n val = int(val)\n except Exception:\n try:\n val = float(val)\n except Exception:\n pass\n listres[key.strip()] = val\n result[strlist] = listres\n\n # -------- Parse through selection lists --------\n if not options:\n for sellist in ('cache_mode', 'cache_replacement_policy', 'errors'):\n if sellist in result:\n result[sellist] = re.search(r'\\[(.+)\\]', result[sellist]).groups()[0]\n\n # -------- Parse through well known bools --------\n for boolkey in ('running', 'writeback_running', 'congested'):\n if boolkey in result:\n result[boolkey] = bool(result[boolkey])\n\n # -------- Recategorize results --------\n bresult = {}\n for iftype, intflist in bintf.items():\n ifres = {}\n for intf in intflist:\n if intf in result:\n ifres[intf] = result.pop(intf)\n if ifres:\n bresult[iftype] = ifres\n\n return bresult\n"
] |
# -*- coding: utf-8 -*-
'''
Module for managing BCache sets
BCache is a block-level caching mechanism similar to ZFS L2ARC/ZIL, dm-cache and fscache.
It works by formatting one block device as a cache set, then adding backend devices
(which need to be formatted as such) to the set and activating them.
It's available in Linux mainline kernel since 3.10
https://www.kernel.org/doc/Documentation/bcache.txt
This module needs the bcache userspace tools to function.
.. versionadded: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import time
import re
from salt.ext import six
# Import salt libs
import salt.utils.path
log = logging.getLogger(__name__)
LOG = {
'trace': logging.TRACE,
'debug': logging.DEBUG,
'info': logging.INFO,
'warn': logging.WARNING,
'error': logging.ERROR,
'crit': logging.CRITICAL,
}
__func_alias__ = {
'attach_': 'attach',
'config_': 'config',
'super_': 'super',
}
HAS_BLKDISCARD = salt.utils.path.which('blkdiscard') is not None
def __virtual__():
'''
Only work when make-bcache is installed
'''
return salt.utils.path.which('make-bcache') is not None
def uuid(dev=None):
'''
Return the bcache UUID of a block device.
If no device is given, the Cache UUID is returned.
CLI example:
.. code-block:: bash
salt '*' bcache.uuid
salt '*' bcache.uuid /dev/sda
salt '*' bcache.uuid bcache0
'''
try:
if dev is None:
# take the only directory in /sys/fs/bcache and return it's basename
return list(salt.utils.path.os_walk('/sys/fs/bcache/'))[0][1][0]
else:
# basename of the /sys/block/{dev}/bcache/cache symlink target
return os.path.basename(_bcsys(dev, 'cache'))
except Exception:
return False
def attach_(dev=None):
'''
Attach a backing devices to a cache set
If no dev is given, all backing devices will be attached.
CLI example:
.. code-block:: bash
salt '*' bcache.attach sdc
salt '*' bcache.attach /dev/bcache1
:return: bool or None if nuttin' happened
'''
cache = uuid()
if not cache:
log.error('No cache to attach %s to', dev)
return False
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = attach_(dev)
return res if res else None
bcache = uuid(dev)
if bcache:
if bcache == cache:
log.info('%s is already attached to bcache %s, doing nothing', dev, cache)
return None
elif not detach(dev):
return False
log.debug('Attaching %s to bcache %s', dev, cache)
if not _bcsys(dev, 'attach', cache,
'error', 'Error attaching {0} to bcache {1}'.format(dev, cache)):
return False
return _wait(lambda: uuid(dev) == cache,
'error', '{0} received attach to bcache {1}, but did not comply'.format(dev, cache))
def detach(dev=None):
'''
Detach a backing device(s) from a cache set
If no dev is given, all backing devices will be attached.
Detaching a backing device will flush it's write cache.
This should leave the underlying device in a consistent state, but might take a while.
CLI example:
.. code-block:: bash
salt '*' bcache.detach sdc
salt '*' bcache.detach bcache1
'''
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = detach(dev)
return res if res else None
log.debug('Detaching %s', dev)
if not _bcsys(dev, 'detach', 'goaway', 'error', 'Error detaching {0}'.format(dev)):
return False
return _wait(lambda: uuid(dev) is False, 'error', '{0} received detach, but did not comply'.format(dev), 300)
def start():
'''
Trigger a start of the full bcache system through udev.
CLI example:
.. code-block:: bash
salt '*' bcache.start
'''
if not _run_all('udevadm trigger', 'error', 'Error starting bcache: %s'):
return False
elif not _wait(lambda: uuid() is not False, 'warn', 'Bcache system started, but no active cache set found.'):
return False
return True
def stop(dev=None):
'''
Stop a bcache device
If no device is given, all backing devices will be detached from the cache, which will subsequently be stopped.
.. warning::
'Stop' on an individual backing device means hard-stop;
no attempt at flushing will be done and the bcache device will seemingly 'disappear' from the device lists
CLI example:
.. code-block:: bash
salt '*' bcache.stop
'''
if dev is not None:
log.warning('Stopping %s, device will only reappear after reregistering!', dev)
if not _bcsys(dev, 'stop', 'goaway', 'error', 'Error stopping {0}'.format(dev)):
return False
return _wait(lambda: _sysfs_attr(_bcpath(dev)) is False, 'error', 'Device {0} did not stop'.format(dev), 300)
else:
cache = uuid()
if not cache:
log.warning('bcache already stopped?')
return None
if not _alltrue(detach()):
return False
elif not _fssys('stop', 'goaway', 'error', 'Error stopping cache'):
return False
return _wait(lambda: uuid() is False, 'error', 'Cache did not stop', 300)
def back_make(dev, cache_mode='writeback', force=False, attach=True, bucket_size=None):
'''
Create a backing device for attachment to a set.
Because the block size must be the same, a cache set already needs to exist.
CLI example:
.. code-block:: bash
salt '*' bcache.back_make sdc cache_mode=writeback attach=True
:param cache_mode: writethrough, writeback, writearound or none.
:param force: Overwrite existing bcaches
:param attach: Immediately attach the backing device to the set
:param bucket_size: Size of a bucket (see kernel doc)
'''
# pylint: disable=too-many-return-statements
cache = uuid()
if not cache:
log.error('No bcache set found')
return False
elif _sysfs_attr(_bcpath(dev)):
if not force:
log.error('%s already contains a bcache. Wipe it manually or use force', dev)
return False
elif uuid(dev) and not detach(dev):
return False
elif not stop(dev):
return False
dev = _devpath(dev)
block_size = _size_map(_fssys('block_size'))
# You might want to override, we pick the cache set's as sane default
if bucket_size is None:
bucket_size = _size_map(_fssys('bucket_size'))
cmd = 'make-bcache --block {0} --bucket {1} --{2} --bdev {3}'.format(block_size, bucket_size, cache_mode, dev)
if force:
cmd += ' --wipe-bcache'
if not _run_all(cmd, 'error', 'Error creating backing device {0}: %s'.format(dev)):
return False
elif not _sysfs_attr('fs/bcache/register', _devpath(dev),
'error', 'Error registering backing device {0}'.format(dev)):
return False
elif not _wait(lambda: _sysfs_attr(_bcpath(dev)) is not False,
'error', 'Backing device {0} did not register'.format(dev)):
return False
elif attach:
return attach_(dev)
return True
def cache_make(dev, reserved=None, force=False, block_size=None, bucket_size=None, attach=True):
'''
Create BCache cache on a block device.
If blkdiscard is available the entire device will be properly cleared in advance.
CLI example:
.. code-block:: bash
salt '*' bcache.cache_make sdb reserved=10% block_size=4096
:param reserved: if dev is a full device, create a partition table with this size empty.
.. note::
this increases the amount of reserved space available to SSD garbage collectors,
potentially (vastly) increasing performance
:param block_size: Block size of the cache; defaults to devices' logical block size
:param force: Overwrite existing BCache sets
:param attach: Attach all existing backend devices immediately
'''
# TODO: multiple devs == md jbod
# pylint: disable=too-many-return-statements
# ---------------- Preflight checks ----------------
cache = uuid()
if cache:
if not force:
log.error('BCache cache %s is already on the system', cache)
return False
cache = _bdev()
dev = _devbase(dev)
udev = __salt__['udev.env'](dev)
if ('ID_FS_TYPE' in udev or (udev.get('DEVTYPE', None) != 'partition' and 'ID_PART_TABLE_TYPE' in udev)) \
and not force:
log.error('%s already contains data, wipe first or force', dev)
return False
elif reserved is not None and udev.get('DEVTYPE', None) != 'disk':
log.error('Need a partitionable blockdev for reserved to work')
return False
_, block, bucket = _sizes(dev)
if bucket_size is None:
bucket_size = bucket
# TODO: bucket from _sizes() makes no sense
bucket_size = False
if block_size is None:
block_size = block
# ---------------- Still here, start doing destructive stuff ----------------
if cache:
if not stop():
return False
# Wipe the current cache device as well,
# forever ruining any chance of it accidentally popping up again
elif not _wipe(cache):
return False
# Can't do enough wiping
if not _wipe(dev):
return False
if reserved:
cmd = 'parted -m -s -a optimal -- ' \
'/dev/{0} mklabel gpt mkpart bcache-reserved 1M {1} mkpart bcache {1} 100%'.format(dev, reserved)
# if wipe was incomplete & part layout remains the same,
# this is one condition set where udev would make it accidentally popup again
if not _run_all(cmd, 'error', 'Error creating bcache partitions on {0}: %s'.format(dev)):
return False
dev = '{0}2'.format(dev)
# ---------------- Finally, create a cache ----------------
cmd = 'make-bcache --cache /dev/{0} --block {1} --wipe-bcache'.format(dev, block_size)
# Actually bucket_size should always have a value, but for testing 0 is possible as well
if bucket_size:
cmd += ' --bucket {0}'.format(bucket_size)
if not _run_all(cmd, 'error', 'Error creating cache {0}: %s'.format(dev)):
return False
elif not _wait(lambda: uuid() is not False,
'error', 'Cache {0} seemingly created OK, but FS did not activate'.format(dev)):
return False
if attach:
return _alltrue(attach_())
else:
return True
def status(stats=False, config=False, internals=False, superblock=False, alldevs=False):
'''
Show the full status of the BCache system and optionally all it's involved devices
CLI example:
.. code-block:: bash
salt '*' bcache.status
salt '*' bcache.status stats=True
salt '*' bcache.status internals=True alldevs=True
:param stats: include statistics
:param config: include settings
:param internals: include internals
:param superblock: include superblock
'''
bdevs = []
for _, links, _ in salt.utils.path.os_walk('/sys/block/'):
for block in links:
if 'bcache' in block:
continue
for spath, sdirs, _ in salt.utils.path.os_walk('/sys/block/{0}'.format(block), followlinks=False):
if 'bcache' in sdirs:
bdevs.append(os.path.basename(spath))
statii = {}
for bcache in bdevs:
statii[bcache] = device(bcache, stats, config, internals, superblock)
cuuid = uuid()
cdev = _bdev()
if cdev:
count = 0
for dev in statii:
if dev != cdev:
# it's a backing dev
if statii[dev]['cache'] == cuuid:
count += 1
statii[cdev]['attached_backing_devices'] = count
if not alldevs:
statii = statii[cdev]
return statii
def device(dev, stats=False, config=False, internals=False, superblock=False):
'''
Check the state of a single bcache device
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc stats=True
:param stats: include statistics
:param settings: include all settings
:param internals: include all internals
:param superblock: include superblock info
'''
result = {}
if not _sysfs_attr(_bcpath(dev), None, 'error', '{0} is not a bcache fo any kind'.format(dev)):
return False
elif _bcsys(dev, 'set'):
# ---------------- It's the cache itself ----------------
result['uuid'] = uuid()
base_attr = ['block_size', 'bucket_size', 'cache_available_percent', 'cache_replacement_policy', 'congested']
# ---------------- Parse through both the blockdev & the FS ----------------
result.update(_sysfs_parse(_bcpath(dev), base_attr, stats, config, internals))
result.update(_sysfs_parse(_fspath(), base_attr, stats, config, internals))
result.update(result.pop('base'))
else:
# ---------------- It's a backing device ----------------
back_uuid = uuid(dev)
if back_uuid is not None:
result['cache'] = back_uuid
try:
result['dev'] = os.path.basename(_bcsys(dev, 'dev'))
except Exception:
pass
result['bdev'] = _bdev(dev)
base_attr = ['cache_mode', 'running', 'state', 'writeback_running']
base_path = _bcpath(dev)
result.update(_sysfs_parse(base_path, base_attr, stats, config, internals))
result.update(result.pop('base'))
# ---------------- Modifications ----------------
state = [result['state']]
if result.pop('running'):
state.append('running')
else:
state.append('stopped')
if 'writeback_running' in result:
if result.pop('writeback_running'):
state.append('writeback_running')
else:
state.append('writeback_stopped')
result['state'] = state
# ---------------- Statistics ----------------
if 'stats' in result:
replre = r'(stats|cache)_'
statres = result['stats']
for attr in result['stats']:
if '/' not in attr:
key = re.sub(replre, '', attr)
statres[key] = statres.pop(attr)
else:
stat, key = attr.split('/', 1)
stat = re.sub(replre, '', stat)
key = re.sub(replre, '', key)
if stat not in statres:
statres[stat] = {}
statres[stat][key] = statres.pop(attr)
result['stats'] = statres
# ---------------- Internals ----------------
if internals:
interres = result.pop('inter_ro', {})
interres.update(result.pop('inter_rw', {}))
if interres:
for key in interres:
if key.startswith('internal'):
nkey = re.sub(r'internal[s/]*', '', key)
interres[nkey] = interres.pop(key)
key = nkey
if key.startswith(('btree', 'writeback')):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in interres:
interres[mkey] = {}
interres[mkey][skey] = interres.pop(key)
result['internals'] = interres
# ---------------- Config ----------------
if config:
configres = result['config']
for key in configres:
if key.startswith('writeback'):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in configres:
configres[mkey] = {}
configres[mkey][skey] = configres.pop(key)
result['config'] = configres
# ---------------- Superblock ----------------
if superblock:
result['superblock'] = super_(dev)
return result
def super_(dev):
'''
Read out BCache SuperBlock
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc
'''
dev = _devpath(dev)
ret = {}
res = _run_all('bcache-super-show {0}'.format(dev), 'error', 'Error reading superblock on {0}: %s'.format(dev))
if not res:
return False
for line in res.splitlines(): # pylint: disable=no-member
line = line.strip()
if not line:
continue
key, val = [val.strip() for val in re.split(r'[\s]+', line, maxsplit=1)]
if not (key and val):
continue
mval = None
if ' ' in val:
rval, mval = [val.strip() for val in re.split(r'[\s]+', val, maxsplit=1)]
mval = mval[1:-1]
else:
rval = val
try:
rval = int(rval)
except Exception:
try:
rval = float(rval)
except Exception:
if rval == 'yes':
rval = True
elif rval == 'no':
rval = False
pkey, key = re.split(r'\.', key, maxsplit=1)
if pkey not in ret:
ret[pkey] = {}
if mval is not None:
ret[pkey][key] = (rval, mval)
else:
ret[pkey][key] = rval
return ret
# -------------------------------- HELPER FUNCTIONS --------------------------------
def _devbase(dev):
'''
Basename of just about any dev
'''
dev = os.path.realpath(os.path.expandvars(dev))
dev = os.path.basename(dev)
return dev
def _devpath(dev):
'''
Return /dev name of just about any dev
:return: /dev/devicename
'''
return os.path.join('/dev', _devbase(dev))
def _syspath(dev):
'''
Full SysFS path of a device
'''
dev = _devbase(dev)
dev = re.sub(r'^([vhs][a-z]+)([0-9]+)', r'\1/\1\2', dev)
# name = re.sub(r'^([a-z]+)(?<!(bcache|md|dm))([0-9]+)', r'\1/\1\2', name)
return os.path.join('/sys/block/', dev)
def _bdev(dev=None):
'''
Resolve a bcacheX or cache to a real dev
:return: basename of bcache dev
'''
if dev is None:
dev = _fssys('cache0')
else:
dev = _bcpath(dev)
if not dev:
return False
else:
return _devbase(os.path.dirname(dev))
def _bcpath(dev):
'''
Full SysFS path of a bcache device
'''
return os.path.join(_syspath(dev), 'bcache')
def _fspath():
'''
:return: path of active bcache
'''
cuuid = uuid()
if not cuuid:
return False
else:
return os.path.join('/sys/fs/bcache/', cuuid)
def _fssys(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with bcache SysFS
'''
fspath = _fspath()
if not fspath:
return False
else:
return _sysfs_attr([fspath, name], value, log_lvl, log_msg)
def _bcsys(dev, name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with backing devs SysFS
'''
return _sysfs_attr([_bcpath(dev), name], value, log_lvl, log_msg)
def _sysfs_attr(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper with logging around sysfs.attr
'''
if isinstance(name, six.string_types):
name = [name]
res = __salt__['sysfs.attr'](os.path.join(*name), value)
if not res and log_lvl is not None and log_msg is not None:
log.log(LOG[log_lvl], log_msg)
return res
def _sysfs_parse(path, base_attr=None, stats=False, config=False, internals=False, options=False):
'''
Helper function for parsing BCache's SysFS interface
'''
result = {}
# ---------------- Parse through the interfaces list ----------------
intfs = __salt__['sysfs.interfaces'](path)
# Actions, we ignore
del intfs['w']
# -------- Sorting hat --------
binkeys = []
if internals:
binkeys.extend(['inter_ro', 'inter_rw'])
if config:
binkeys.append('config')
if stats:
binkeys.append('stats')
bintf = {}
for key in binkeys:
bintf[key] = []
for intf in intfs['r']:
if intf.startswith('internal'):
key = 'inter_ro'
elif 'stats' in intf:
key = 'stats'
else:
# What to do with these???
# I'll utilize 'inter_ro' as 'misc' as well
key = 'inter_ro'
if key in bintf:
bintf[key].append(intf)
for intf in intfs['rw']:
if intf.startswith('internal'):
key = 'inter_rw'
else:
key = 'config'
if key in bintf:
bintf[key].append(intf)
if base_attr is not None:
for intf in bintf:
bintf[intf] = [sintf for sintf in bintf[intf] if sintf not in base_attr]
bintf['base'] = base_attr
mods = {
'stats': ['internal/bset_tree_stats', 'writeback_rate_debug', 'metadata_written', 'nbuckets', 'written',
'average_key_size', 'btree_cache_size'],
}
for modt, modlist in mods.items():
found = []
if modt not in bintf:
continue
for mod in modlist:
for intflist in bintf.values():
if mod in intflist:
found.append(mod)
intflist.remove(mod)
bintf[modt] += found
# -------- Fetch SysFS vals --------
bintflist = [intf for iflist in bintf.values() for intf in iflist]
result.update(__salt__['sysfs.read'](bintflist, path))
# -------- Parse through well known string lists --------
for strlist in ('writeback_rate_debug', 'internal/bset_tree_stats', 'priority_stats'):
if strlist in result:
listres = {}
for line in result[strlist].split('\n'):
key, val = line.split(':', 1)
val = val.strip()
try:
val = int(val)
except Exception:
try:
val = float(val)
except Exception:
pass
listres[key.strip()] = val
result[strlist] = listres
# -------- Parse through selection lists --------
if not options:
for sellist in ('cache_mode', 'cache_replacement_policy', 'errors'):
if sellist in result:
result[sellist] = re.search(r'\[(.+)\]', result[sellist]).groups()[0]
# -------- Parse through well known bools --------
for boolkey in ('running', 'writeback_running', 'congested'):
if boolkey in result:
result[boolkey] = bool(result[boolkey])
# -------- Recategorize results --------
bresult = {}
for iftype, intflist in bintf.items():
ifres = {}
for intf in intflist:
if intf in result:
ifres[intf] = result.pop(intf)
if ifres:
bresult[iftype] = ifres
return bresult
def _size_map(size):
'''
Map Bcache's size strings to real bytes
'''
try:
# I know, I know, EAFP.
# But everything else is reason for None
if not isinstance(size, int):
if re.search(r'[Kk]', size):
size = 1024 * float(re.sub(r'[Kk]', '', size))
elif re.search(r'[Mm]', size):
size = 1024**2 * float(re.sub(r'[Mm]', '', size))
size = int(size)
return size
except Exception:
return None
def _sizes(dev):
'''
Return neigh useless sizing info about a blockdev
:return: (total size in blocks, blocksize, maximum discard size in bytes)
'''
dev = _devbase(dev)
# standarization yay
block_sizes = ('hw_sector_size', 'minimum_io_size', 'physical_block_size', 'logical_block_size')
discard_sizes = ('discard_max_bytes', 'discard_max_hw_bytes', )
sysfs = __salt__['sysfs.read'](
('size',
'queue/hw_sector_size', '../queue/hw_sector_size',
'queue/discard_max_bytes', '../queue/discard_max_bytes'),
root=_syspath(dev))
# TODO: makes no sense
# First of all, it has to be a power of 2
# Secondly, this returns 4GiB - 512b on Intel 3500's for some weird reason
# discard_granularity seems in bytes, resolves to 512b ???
# max_hw_sectors_kb???
# There's also discard_max_hw_bytes more recently
# See: https://www.kernel.org/doc/Documentation/block/queue-sysfs.txt
# Also, I cant find any docs yet regarding bucket sizes;
# it's supposed to be discard_max_hw_bytes,
# but no way to figure that one reliably out apparently
discard = sysfs.get('queue/discard_max_bytes', sysfs.get('../queue/discard_max_bytes', None))
block = sysfs.get('queue/hw_sector_size', sysfs.get('../queue/hw_sector_size', None))
return 512*sysfs['size'], block, discard
def _wipe(dev):
'''
REALLY DESTRUCTIVE STUFF RIGHT AHEAD
'''
endres = 0
dev = _devbase(dev)
size, block, discard = _sizes(dev)
if discard is None:
log.error('Unable to read SysFS props for %s', dev)
return None
elif not discard:
log.warning('%s seems unable to discard', dev)
wiper = 'dd'
elif not HAS_BLKDISCARD:
log.warning('blkdiscard binary not available, properly wipe the dev manually for optimal results')
wiper = 'dd'
else:
wiper = 'blkdiscard'
wipe_failmsg = 'Error wiping {0}: %s'.format(dev)
if wiper == 'dd':
blocks = 4
cmd = 'dd if=/dev/zero of=/dev/{0} bs=1M count={1}'.format(dev, blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# Some stuff (<cough>GPT</cough>) writes stuff at the end of a dev as well
cmd += ' seek={0}'.format((size/1024**2) - blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
elif wiper == 'blkdiscard':
cmd = 'blkdiscard /dev/{0}'.format(dev)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# TODO: fix annoying bug failing blkdiscard by trying to discard 1 sector past blkdev
endres = 1
return endres > 0
def _wait(lfunc, log_lvl=None, log_msg=None, tries=10):
'''
Wait for lfunc to be True
:return: True if lfunc succeeded within tries, False if it didn't
'''
i = 0
while i < tries:
time.sleep(1)
if lfunc():
return True
else:
i += 1
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg)
return False
def _run_all(cmd, log_lvl=None, log_msg=None, exitcode=0):
'''
Simple wrapper around cmd.run_all
log_msg can contain {0} for stderr
:return: True or stdout, False if retcode wasn't exitcode
'''
res = __salt__['cmd.run_all'](cmd)
if res['retcode'] == exitcode:
if res['stdout']:
return res['stdout']
else:
return True
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg, res['stderr'])
return False
def _alltrue(resdict):
if resdict is None:
return True
return len([val for val in resdict.values() if val]) > 0
|
saltstack/salt
|
salt/modules/bcache.py
|
status
|
python
|
def status(stats=False, config=False, internals=False, superblock=False, alldevs=False):
'''
Show the full status of the BCache system and optionally all it's involved devices
CLI example:
.. code-block:: bash
salt '*' bcache.status
salt '*' bcache.status stats=True
salt '*' bcache.status internals=True alldevs=True
:param stats: include statistics
:param config: include settings
:param internals: include internals
:param superblock: include superblock
'''
bdevs = []
for _, links, _ in salt.utils.path.os_walk('/sys/block/'):
for block in links:
if 'bcache' in block:
continue
for spath, sdirs, _ in salt.utils.path.os_walk('/sys/block/{0}'.format(block), followlinks=False):
if 'bcache' in sdirs:
bdevs.append(os.path.basename(spath))
statii = {}
for bcache in bdevs:
statii[bcache] = device(bcache, stats, config, internals, superblock)
cuuid = uuid()
cdev = _bdev()
if cdev:
count = 0
for dev in statii:
if dev != cdev:
# it's a backing dev
if statii[dev]['cache'] == cuuid:
count += 1
statii[cdev]['attached_backing_devices'] = count
if not alldevs:
statii = statii[cdev]
return statii
|
Show the full status of the BCache system and optionally all it's involved devices
CLI example:
.. code-block:: bash
salt '*' bcache.status
salt '*' bcache.status stats=True
salt '*' bcache.status internals=True alldevs=True
:param stats: include statistics
:param config: include settings
:param internals: include internals
:param superblock: include superblock
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bcache.py#L404-L448
|
[
"def os_walk(top, *args, **kwargs):\n '''\n This is a helper than ensures that all paths returned from os.walk are\n unicode.\n '''\n if six.PY2 and salt.utils.platform.is_windows():\n top_query = top\n else:\n top_query = salt.utils.stringutils.to_str(top)\n for item in os.walk(top_query, *args, **kwargs):\n yield salt.utils.data.decode(item, preserve_tuples=True)\n",
"def uuid(dev=None):\n '''\n Return the bcache UUID of a block device.\n If no device is given, the Cache UUID is returned.\n\n CLI example:\n\n .. code-block:: bash\n\n salt '*' bcache.uuid\n salt '*' bcache.uuid /dev/sda\n salt '*' bcache.uuid bcache0\n\n '''\n try:\n if dev is None:\n # take the only directory in /sys/fs/bcache and return it's basename\n return list(salt.utils.path.os_walk('/sys/fs/bcache/'))[0][1][0]\n else:\n # basename of the /sys/block/{dev}/bcache/cache symlink target\n return os.path.basename(_bcsys(dev, 'cache'))\n except Exception:\n return False\n",
"def device(dev, stats=False, config=False, internals=False, superblock=False):\n '''\n Check the state of a single bcache device\n\n CLI example:\n\n .. code-block:: bash\n\n salt '*' bcache.device bcache0\n salt '*' bcache.device /dev/sdc stats=True\n\n :param stats: include statistics\n :param settings: include all settings\n :param internals: include all internals\n :param superblock: include superblock info\n '''\n result = {}\n\n if not _sysfs_attr(_bcpath(dev), None, 'error', '{0} is not a bcache fo any kind'.format(dev)):\n return False\n elif _bcsys(dev, 'set'):\n # ---------------- It's the cache itself ----------------\n result['uuid'] = uuid()\n base_attr = ['block_size', 'bucket_size', 'cache_available_percent', 'cache_replacement_policy', 'congested']\n\n # ---------------- Parse through both the blockdev & the FS ----------------\n result.update(_sysfs_parse(_bcpath(dev), base_attr, stats, config, internals))\n result.update(_sysfs_parse(_fspath(), base_attr, stats, config, internals))\n\n result.update(result.pop('base'))\n else:\n # ---------------- It's a backing device ----------------\n back_uuid = uuid(dev)\n if back_uuid is not None:\n result['cache'] = back_uuid\n\n try:\n result['dev'] = os.path.basename(_bcsys(dev, 'dev'))\n except Exception:\n pass\n result['bdev'] = _bdev(dev)\n\n base_attr = ['cache_mode', 'running', 'state', 'writeback_running']\n base_path = _bcpath(dev)\n\n result.update(_sysfs_parse(base_path, base_attr, stats, config, internals))\n result.update(result.pop('base'))\n\n # ---------------- Modifications ----------------\n state = [result['state']]\n if result.pop('running'):\n state.append('running')\n else:\n state.append('stopped')\n if 'writeback_running' in result:\n if result.pop('writeback_running'):\n state.append('writeback_running')\n else:\n state.append('writeback_stopped')\n result['state'] = state\n\n # ---------------- Statistics ----------------\n if 'stats' in result:\n replre = r'(stats|cache)_'\n statres = result['stats']\n for attr in result['stats']:\n if '/' not in attr:\n key = re.sub(replre, '', attr)\n statres[key] = statres.pop(attr)\n else:\n stat, key = attr.split('/', 1)\n stat = re.sub(replre, '', stat)\n key = re.sub(replre, '', key)\n if stat not in statres:\n statres[stat] = {}\n statres[stat][key] = statres.pop(attr)\n result['stats'] = statres\n\n # ---------------- Internals ----------------\n if internals:\n interres = result.pop('inter_ro', {})\n interres.update(result.pop('inter_rw', {}))\n if interres:\n for key in interres:\n if key.startswith('internal'):\n nkey = re.sub(r'internal[s/]*', '', key)\n interres[nkey] = interres.pop(key)\n key = nkey\n if key.startswith(('btree', 'writeback')):\n mkey, skey = re.split(r'_', key, maxsplit=1)\n if mkey not in interres:\n interres[mkey] = {}\n interres[mkey][skey] = interres.pop(key)\n result['internals'] = interres\n\n # ---------------- Config ----------------\n if config:\n configres = result['config']\n for key in configres:\n if key.startswith('writeback'):\n mkey, skey = re.split(r'_', key, maxsplit=1)\n if mkey not in configres:\n configres[mkey] = {}\n configres[mkey][skey] = configres.pop(key)\n result['config'] = configres\n\n # ---------------- Superblock ----------------\n if superblock:\n result['superblock'] = super_(dev)\n\n return result\n",
"def _bdev(dev=None):\n '''\n Resolve a bcacheX or cache to a real dev\n :return: basename of bcache dev\n '''\n if dev is None:\n dev = _fssys('cache0')\n else:\n dev = _bcpath(dev)\n\n if not dev:\n return False\n else:\n return _devbase(os.path.dirname(dev))\n"
] |
# -*- coding: utf-8 -*-
'''
Module for managing BCache sets
BCache is a block-level caching mechanism similar to ZFS L2ARC/ZIL, dm-cache and fscache.
It works by formatting one block device as a cache set, then adding backend devices
(which need to be formatted as such) to the set and activating them.
It's available in Linux mainline kernel since 3.10
https://www.kernel.org/doc/Documentation/bcache.txt
This module needs the bcache userspace tools to function.
.. versionadded: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import time
import re
from salt.ext import six
# Import salt libs
import salt.utils.path
log = logging.getLogger(__name__)
LOG = {
'trace': logging.TRACE,
'debug': logging.DEBUG,
'info': logging.INFO,
'warn': logging.WARNING,
'error': logging.ERROR,
'crit': logging.CRITICAL,
}
__func_alias__ = {
'attach_': 'attach',
'config_': 'config',
'super_': 'super',
}
HAS_BLKDISCARD = salt.utils.path.which('blkdiscard') is not None
def __virtual__():
'''
Only work when make-bcache is installed
'''
return salt.utils.path.which('make-bcache') is not None
def uuid(dev=None):
'''
Return the bcache UUID of a block device.
If no device is given, the Cache UUID is returned.
CLI example:
.. code-block:: bash
salt '*' bcache.uuid
salt '*' bcache.uuid /dev/sda
salt '*' bcache.uuid bcache0
'''
try:
if dev is None:
# take the only directory in /sys/fs/bcache and return it's basename
return list(salt.utils.path.os_walk('/sys/fs/bcache/'))[0][1][0]
else:
# basename of the /sys/block/{dev}/bcache/cache symlink target
return os.path.basename(_bcsys(dev, 'cache'))
except Exception:
return False
def attach_(dev=None):
'''
Attach a backing devices to a cache set
If no dev is given, all backing devices will be attached.
CLI example:
.. code-block:: bash
salt '*' bcache.attach sdc
salt '*' bcache.attach /dev/bcache1
:return: bool or None if nuttin' happened
'''
cache = uuid()
if not cache:
log.error('No cache to attach %s to', dev)
return False
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = attach_(dev)
return res if res else None
bcache = uuid(dev)
if bcache:
if bcache == cache:
log.info('%s is already attached to bcache %s, doing nothing', dev, cache)
return None
elif not detach(dev):
return False
log.debug('Attaching %s to bcache %s', dev, cache)
if not _bcsys(dev, 'attach', cache,
'error', 'Error attaching {0} to bcache {1}'.format(dev, cache)):
return False
return _wait(lambda: uuid(dev) == cache,
'error', '{0} received attach to bcache {1}, but did not comply'.format(dev, cache))
def detach(dev=None):
'''
Detach a backing device(s) from a cache set
If no dev is given, all backing devices will be attached.
Detaching a backing device will flush it's write cache.
This should leave the underlying device in a consistent state, but might take a while.
CLI example:
.. code-block:: bash
salt '*' bcache.detach sdc
salt '*' bcache.detach bcache1
'''
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = detach(dev)
return res if res else None
log.debug('Detaching %s', dev)
if not _bcsys(dev, 'detach', 'goaway', 'error', 'Error detaching {0}'.format(dev)):
return False
return _wait(lambda: uuid(dev) is False, 'error', '{0} received detach, but did not comply'.format(dev), 300)
def start():
'''
Trigger a start of the full bcache system through udev.
CLI example:
.. code-block:: bash
salt '*' bcache.start
'''
if not _run_all('udevadm trigger', 'error', 'Error starting bcache: %s'):
return False
elif not _wait(lambda: uuid() is not False, 'warn', 'Bcache system started, but no active cache set found.'):
return False
return True
def stop(dev=None):
'''
Stop a bcache device
If no device is given, all backing devices will be detached from the cache, which will subsequently be stopped.
.. warning::
'Stop' on an individual backing device means hard-stop;
no attempt at flushing will be done and the bcache device will seemingly 'disappear' from the device lists
CLI example:
.. code-block:: bash
salt '*' bcache.stop
'''
if dev is not None:
log.warning('Stopping %s, device will only reappear after reregistering!', dev)
if not _bcsys(dev, 'stop', 'goaway', 'error', 'Error stopping {0}'.format(dev)):
return False
return _wait(lambda: _sysfs_attr(_bcpath(dev)) is False, 'error', 'Device {0} did not stop'.format(dev), 300)
else:
cache = uuid()
if not cache:
log.warning('bcache already stopped?')
return None
if not _alltrue(detach()):
return False
elif not _fssys('stop', 'goaway', 'error', 'Error stopping cache'):
return False
return _wait(lambda: uuid() is False, 'error', 'Cache did not stop', 300)
def back_make(dev, cache_mode='writeback', force=False, attach=True, bucket_size=None):
'''
Create a backing device for attachment to a set.
Because the block size must be the same, a cache set already needs to exist.
CLI example:
.. code-block:: bash
salt '*' bcache.back_make sdc cache_mode=writeback attach=True
:param cache_mode: writethrough, writeback, writearound or none.
:param force: Overwrite existing bcaches
:param attach: Immediately attach the backing device to the set
:param bucket_size: Size of a bucket (see kernel doc)
'''
# pylint: disable=too-many-return-statements
cache = uuid()
if not cache:
log.error('No bcache set found')
return False
elif _sysfs_attr(_bcpath(dev)):
if not force:
log.error('%s already contains a bcache. Wipe it manually or use force', dev)
return False
elif uuid(dev) and not detach(dev):
return False
elif not stop(dev):
return False
dev = _devpath(dev)
block_size = _size_map(_fssys('block_size'))
# You might want to override, we pick the cache set's as sane default
if bucket_size is None:
bucket_size = _size_map(_fssys('bucket_size'))
cmd = 'make-bcache --block {0} --bucket {1} --{2} --bdev {3}'.format(block_size, bucket_size, cache_mode, dev)
if force:
cmd += ' --wipe-bcache'
if not _run_all(cmd, 'error', 'Error creating backing device {0}: %s'.format(dev)):
return False
elif not _sysfs_attr('fs/bcache/register', _devpath(dev),
'error', 'Error registering backing device {0}'.format(dev)):
return False
elif not _wait(lambda: _sysfs_attr(_bcpath(dev)) is not False,
'error', 'Backing device {0} did not register'.format(dev)):
return False
elif attach:
return attach_(dev)
return True
def cache_make(dev, reserved=None, force=False, block_size=None, bucket_size=None, attach=True):
'''
Create BCache cache on a block device.
If blkdiscard is available the entire device will be properly cleared in advance.
CLI example:
.. code-block:: bash
salt '*' bcache.cache_make sdb reserved=10% block_size=4096
:param reserved: if dev is a full device, create a partition table with this size empty.
.. note::
this increases the amount of reserved space available to SSD garbage collectors,
potentially (vastly) increasing performance
:param block_size: Block size of the cache; defaults to devices' logical block size
:param force: Overwrite existing BCache sets
:param attach: Attach all existing backend devices immediately
'''
# TODO: multiple devs == md jbod
# pylint: disable=too-many-return-statements
# ---------------- Preflight checks ----------------
cache = uuid()
if cache:
if not force:
log.error('BCache cache %s is already on the system', cache)
return False
cache = _bdev()
dev = _devbase(dev)
udev = __salt__['udev.env'](dev)
if ('ID_FS_TYPE' in udev or (udev.get('DEVTYPE', None) != 'partition' and 'ID_PART_TABLE_TYPE' in udev)) \
and not force:
log.error('%s already contains data, wipe first or force', dev)
return False
elif reserved is not None and udev.get('DEVTYPE', None) != 'disk':
log.error('Need a partitionable blockdev for reserved to work')
return False
_, block, bucket = _sizes(dev)
if bucket_size is None:
bucket_size = bucket
# TODO: bucket from _sizes() makes no sense
bucket_size = False
if block_size is None:
block_size = block
# ---------------- Still here, start doing destructive stuff ----------------
if cache:
if not stop():
return False
# Wipe the current cache device as well,
# forever ruining any chance of it accidentally popping up again
elif not _wipe(cache):
return False
# Can't do enough wiping
if not _wipe(dev):
return False
if reserved:
cmd = 'parted -m -s -a optimal -- ' \
'/dev/{0} mklabel gpt mkpart bcache-reserved 1M {1} mkpart bcache {1} 100%'.format(dev, reserved)
# if wipe was incomplete & part layout remains the same,
# this is one condition set where udev would make it accidentally popup again
if not _run_all(cmd, 'error', 'Error creating bcache partitions on {0}: %s'.format(dev)):
return False
dev = '{0}2'.format(dev)
# ---------------- Finally, create a cache ----------------
cmd = 'make-bcache --cache /dev/{0} --block {1} --wipe-bcache'.format(dev, block_size)
# Actually bucket_size should always have a value, but for testing 0 is possible as well
if bucket_size:
cmd += ' --bucket {0}'.format(bucket_size)
if not _run_all(cmd, 'error', 'Error creating cache {0}: %s'.format(dev)):
return False
elif not _wait(lambda: uuid() is not False,
'error', 'Cache {0} seemingly created OK, but FS did not activate'.format(dev)):
return False
if attach:
return _alltrue(attach_())
else:
return True
def config_(dev=None, **kwargs):
'''
Show or update config of a bcache device.
If no device is given, operate on the cache set itself.
CLI example:
.. code-block:: bash
salt '*' bcache.config
salt '*' bcache.config bcache1
salt '*' bcache.config errors=panic journal_delay_ms=150
salt '*' bcache.config bcache1 cache_mode=writeback writeback_percent=15
:return: config or True/False
'''
if dev is None:
spath = _fspath()
else:
spath = _bcpath(dev)
# filter out 'hidden' kwargs added by our favourite orchestration system
updates = dict([(key, val) for key, val in kwargs.items() if not key.startswith('__')])
if updates:
endres = 0
for key, val in updates.items():
endres += _sysfs_attr([spath, key], val,
'warn', 'Failed to update {0} with {1}'.format(os.path.join(spath, key), val))
return endres > 0
else:
result = {}
data = _sysfs_parse(spath, config=True, internals=True, options=True)
for key in ('other_ro', 'inter_ro'):
if key in data:
del data[key]
for key in data:
result.update(data[key])
return result
def device(dev, stats=False, config=False, internals=False, superblock=False):
'''
Check the state of a single bcache device
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc stats=True
:param stats: include statistics
:param settings: include all settings
:param internals: include all internals
:param superblock: include superblock info
'''
result = {}
if not _sysfs_attr(_bcpath(dev), None, 'error', '{0} is not a bcache fo any kind'.format(dev)):
return False
elif _bcsys(dev, 'set'):
# ---------------- It's the cache itself ----------------
result['uuid'] = uuid()
base_attr = ['block_size', 'bucket_size', 'cache_available_percent', 'cache_replacement_policy', 'congested']
# ---------------- Parse through both the blockdev & the FS ----------------
result.update(_sysfs_parse(_bcpath(dev), base_attr, stats, config, internals))
result.update(_sysfs_parse(_fspath(), base_attr, stats, config, internals))
result.update(result.pop('base'))
else:
# ---------------- It's a backing device ----------------
back_uuid = uuid(dev)
if back_uuid is not None:
result['cache'] = back_uuid
try:
result['dev'] = os.path.basename(_bcsys(dev, 'dev'))
except Exception:
pass
result['bdev'] = _bdev(dev)
base_attr = ['cache_mode', 'running', 'state', 'writeback_running']
base_path = _bcpath(dev)
result.update(_sysfs_parse(base_path, base_attr, stats, config, internals))
result.update(result.pop('base'))
# ---------------- Modifications ----------------
state = [result['state']]
if result.pop('running'):
state.append('running')
else:
state.append('stopped')
if 'writeback_running' in result:
if result.pop('writeback_running'):
state.append('writeback_running')
else:
state.append('writeback_stopped')
result['state'] = state
# ---------------- Statistics ----------------
if 'stats' in result:
replre = r'(stats|cache)_'
statres = result['stats']
for attr in result['stats']:
if '/' not in attr:
key = re.sub(replre, '', attr)
statres[key] = statres.pop(attr)
else:
stat, key = attr.split('/', 1)
stat = re.sub(replre, '', stat)
key = re.sub(replre, '', key)
if stat not in statres:
statres[stat] = {}
statres[stat][key] = statres.pop(attr)
result['stats'] = statres
# ---------------- Internals ----------------
if internals:
interres = result.pop('inter_ro', {})
interres.update(result.pop('inter_rw', {}))
if interres:
for key in interres:
if key.startswith('internal'):
nkey = re.sub(r'internal[s/]*', '', key)
interres[nkey] = interres.pop(key)
key = nkey
if key.startswith(('btree', 'writeback')):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in interres:
interres[mkey] = {}
interres[mkey][skey] = interres.pop(key)
result['internals'] = interres
# ---------------- Config ----------------
if config:
configres = result['config']
for key in configres:
if key.startswith('writeback'):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in configres:
configres[mkey] = {}
configres[mkey][skey] = configres.pop(key)
result['config'] = configres
# ---------------- Superblock ----------------
if superblock:
result['superblock'] = super_(dev)
return result
def super_(dev):
'''
Read out BCache SuperBlock
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc
'''
dev = _devpath(dev)
ret = {}
res = _run_all('bcache-super-show {0}'.format(dev), 'error', 'Error reading superblock on {0}: %s'.format(dev))
if not res:
return False
for line in res.splitlines(): # pylint: disable=no-member
line = line.strip()
if not line:
continue
key, val = [val.strip() for val in re.split(r'[\s]+', line, maxsplit=1)]
if not (key and val):
continue
mval = None
if ' ' in val:
rval, mval = [val.strip() for val in re.split(r'[\s]+', val, maxsplit=1)]
mval = mval[1:-1]
else:
rval = val
try:
rval = int(rval)
except Exception:
try:
rval = float(rval)
except Exception:
if rval == 'yes':
rval = True
elif rval == 'no':
rval = False
pkey, key = re.split(r'\.', key, maxsplit=1)
if pkey not in ret:
ret[pkey] = {}
if mval is not None:
ret[pkey][key] = (rval, mval)
else:
ret[pkey][key] = rval
return ret
# -------------------------------- HELPER FUNCTIONS --------------------------------
def _devbase(dev):
'''
Basename of just about any dev
'''
dev = os.path.realpath(os.path.expandvars(dev))
dev = os.path.basename(dev)
return dev
def _devpath(dev):
'''
Return /dev name of just about any dev
:return: /dev/devicename
'''
return os.path.join('/dev', _devbase(dev))
def _syspath(dev):
'''
Full SysFS path of a device
'''
dev = _devbase(dev)
dev = re.sub(r'^([vhs][a-z]+)([0-9]+)', r'\1/\1\2', dev)
# name = re.sub(r'^([a-z]+)(?<!(bcache|md|dm))([0-9]+)', r'\1/\1\2', name)
return os.path.join('/sys/block/', dev)
def _bdev(dev=None):
'''
Resolve a bcacheX or cache to a real dev
:return: basename of bcache dev
'''
if dev is None:
dev = _fssys('cache0')
else:
dev = _bcpath(dev)
if not dev:
return False
else:
return _devbase(os.path.dirname(dev))
def _bcpath(dev):
'''
Full SysFS path of a bcache device
'''
return os.path.join(_syspath(dev), 'bcache')
def _fspath():
'''
:return: path of active bcache
'''
cuuid = uuid()
if not cuuid:
return False
else:
return os.path.join('/sys/fs/bcache/', cuuid)
def _fssys(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with bcache SysFS
'''
fspath = _fspath()
if not fspath:
return False
else:
return _sysfs_attr([fspath, name], value, log_lvl, log_msg)
def _bcsys(dev, name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with backing devs SysFS
'''
return _sysfs_attr([_bcpath(dev), name], value, log_lvl, log_msg)
def _sysfs_attr(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper with logging around sysfs.attr
'''
if isinstance(name, six.string_types):
name = [name]
res = __salt__['sysfs.attr'](os.path.join(*name), value)
if not res and log_lvl is not None and log_msg is not None:
log.log(LOG[log_lvl], log_msg)
return res
def _sysfs_parse(path, base_attr=None, stats=False, config=False, internals=False, options=False):
'''
Helper function for parsing BCache's SysFS interface
'''
result = {}
# ---------------- Parse through the interfaces list ----------------
intfs = __salt__['sysfs.interfaces'](path)
# Actions, we ignore
del intfs['w']
# -------- Sorting hat --------
binkeys = []
if internals:
binkeys.extend(['inter_ro', 'inter_rw'])
if config:
binkeys.append('config')
if stats:
binkeys.append('stats')
bintf = {}
for key in binkeys:
bintf[key] = []
for intf in intfs['r']:
if intf.startswith('internal'):
key = 'inter_ro'
elif 'stats' in intf:
key = 'stats'
else:
# What to do with these???
# I'll utilize 'inter_ro' as 'misc' as well
key = 'inter_ro'
if key in bintf:
bintf[key].append(intf)
for intf in intfs['rw']:
if intf.startswith('internal'):
key = 'inter_rw'
else:
key = 'config'
if key in bintf:
bintf[key].append(intf)
if base_attr is not None:
for intf in bintf:
bintf[intf] = [sintf for sintf in bintf[intf] if sintf not in base_attr]
bintf['base'] = base_attr
mods = {
'stats': ['internal/bset_tree_stats', 'writeback_rate_debug', 'metadata_written', 'nbuckets', 'written',
'average_key_size', 'btree_cache_size'],
}
for modt, modlist in mods.items():
found = []
if modt not in bintf:
continue
for mod in modlist:
for intflist in bintf.values():
if mod in intflist:
found.append(mod)
intflist.remove(mod)
bintf[modt] += found
# -------- Fetch SysFS vals --------
bintflist = [intf for iflist in bintf.values() for intf in iflist]
result.update(__salt__['sysfs.read'](bintflist, path))
# -------- Parse through well known string lists --------
for strlist in ('writeback_rate_debug', 'internal/bset_tree_stats', 'priority_stats'):
if strlist in result:
listres = {}
for line in result[strlist].split('\n'):
key, val = line.split(':', 1)
val = val.strip()
try:
val = int(val)
except Exception:
try:
val = float(val)
except Exception:
pass
listres[key.strip()] = val
result[strlist] = listres
# -------- Parse through selection lists --------
if not options:
for sellist in ('cache_mode', 'cache_replacement_policy', 'errors'):
if sellist in result:
result[sellist] = re.search(r'\[(.+)\]', result[sellist]).groups()[0]
# -------- Parse through well known bools --------
for boolkey in ('running', 'writeback_running', 'congested'):
if boolkey in result:
result[boolkey] = bool(result[boolkey])
# -------- Recategorize results --------
bresult = {}
for iftype, intflist in bintf.items():
ifres = {}
for intf in intflist:
if intf in result:
ifres[intf] = result.pop(intf)
if ifres:
bresult[iftype] = ifres
return bresult
def _size_map(size):
'''
Map Bcache's size strings to real bytes
'''
try:
# I know, I know, EAFP.
# But everything else is reason for None
if not isinstance(size, int):
if re.search(r'[Kk]', size):
size = 1024 * float(re.sub(r'[Kk]', '', size))
elif re.search(r'[Mm]', size):
size = 1024**2 * float(re.sub(r'[Mm]', '', size))
size = int(size)
return size
except Exception:
return None
def _sizes(dev):
'''
Return neigh useless sizing info about a blockdev
:return: (total size in blocks, blocksize, maximum discard size in bytes)
'''
dev = _devbase(dev)
# standarization yay
block_sizes = ('hw_sector_size', 'minimum_io_size', 'physical_block_size', 'logical_block_size')
discard_sizes = ('discard_max_bytes', 'discard_max_hw_bytes', )
sysfs = __salt__['sysfs.read'](
('size',
'queue/hw_sector_size', '../queue/hw_sector_size',
'queue/discard_max_bytes', '../queue/discard_max_bytes'),
root=_syspath(dev))
# TODO: makes no sense
# First of all, it has to be a power of 2
# Secondly, this returns 4GiB - 512b on Intel 3500's for some weird reason
# discard_granularity seems in bytes, resolves to 512b ???
# max_hw_sectors_kb???
# There's also discard_max_hw_bytes more recently
# See: https://www.kernel.org/doc/Documentation/block/queue-sysfs.txt
# Also, I cant find any docs yet regarding bucket sizes;
# it's supposed to be discard_max_hw_bytes,
# but no way to figure that one reliably out apparently
discard = sysfs.get('queue/discard_max_bytes', sysfs.get('../queue/discard_max_bytes', None))
block = sysfs.get('queue/hw_sector_size', sysfs.get('../queue/hw_sector_size', None))
return 512*sysfs['size'], block, discard
def _wipe(dev):
'''
REALLY DESTRUCTIVE STUFF RIGHT AHEAD
'''
endres = 0
dev = _devbase(dev)
size, block, discard = _sizes(dev)
if discard is None:
log.error('Unable to read SysFS props for %s', dev)
return None
elif not discard:
log.warning('%s seems unable to discard', dev)
wiper = 'dd'
elif not HAS_BLKDISCARD:
log.warning('blkdiscard binary not available, properly wipe the dev manually for optimal results')
wiper = 'dd'
else:
wiper = 'blkdiscard'
wipe_failmsg = 'Error wiping {0}: %s'.format(dev)
if wiper == 'dd':
blocks = 4
cmd = 'dd if=/dev/zero of=/dev/{0} bs=1M count={1}'.format(dev, blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# Some stuff (<cough>GPT</cough>) writes stuff at the end of a dev as well
cmd += ' seek={0}'.format((size/1024**2) - blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
elif wiper == 'blkdiscard':
cmd = 'blkdiscard /dev/{0}'.format(dev)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# TODO: fix annoying bug failing blkdiscard by trying to discard 1 sector past blkdev
endres = 1
return endres > 0
def _wait(lfunc, log_lvl=None, log_msg=None, tries=10):
'''
Wait for lfunc to be True
:return: True if lfunc succeeded within tries, False if it didn't
'''
i = 0
while i < tries:
time.sleep(1)
if lfunc():
return True
else:
i += 1
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg)
return False
def _run_all(cmd, log_lvl=None, log_msg=None, exitcode=0):
'''
Simple wrapper around cmd.run_all
log_msg can contain {0} for stderr
:return: True or stdout, False if retcode wasn't exitcode
'''
res = __salt__['cmd.run_all'](cmd)
if res['retcode'] == exitcode:
if res['stdout']:
return res['stdout']
else:
return True
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg, res['stderr'])
return False
def _alltrue(resdict):
if resdict is None:
return True
return len([val for val in resdict.values() if val]) > 0
|
saltstack/salt
|
salt/modules/bcache.py
|
device
|
python
|
def device(dev, stats=False, config=False, internals=False, superblock=False):
'''
Check the state of a single bcache device
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc stats=True
:param stats: include statistics
:param settings: include all settings
:param internals: include all internals
:param superblock: include superblock info
'''
result = {}
if not _sysfs_attr(_bcpath(dev), None, 'error', '{0} is not a bcache fo any kind'.format(dev)):
return False
elif _bcsys(dev, 'set'):
# ---------------- It's the cache itself ----------------
result['uuid'] = uuid()
base_attr = ['block_size', 'bucket_size', 'cache_available_percent', 'cache_replacement_policy', 'congested']
# ---------------- Parse through both the blockdev & the FS ----------------
result.update(_sysfs_parse(_bcpath(dev), base_attr, stats, config, internals))
result.update(_sysfs_parse(_fspath(), base_attr, stats, config, internals))
result.update(result.pop('base'))
else:
# ---------------- It's a backing device ----------------
back_uuid = uuid(dev)
if back_uuid is not None:
result['cache'] = back_uuid
try:
result['dev'] = os.path.basename(_bcsys(dev, 'dev'))
except Exception:
pass
result['bdev'] = _bdev(dev)
base_attr = ['cache_mode', 'running', 'state', 'writeback_running']
base_path = _bcpath(dev)
result.update(_sysfs_parse(base_path, base_attr, stats, config, internals))
result.update(result.pop('base'))
# ---------------- Modifications ----------------
state = [result['state']]
if result.pop('running'):
state.append('running')
else:
state.append('stopped')
if 'writeback_running' in result:
if result.pop('writeback_running'):
state.append('writeback_running')
else:
state.append('writeback_stopped')
result['state'] = state
# ---------------- Statistics ----------------
if 'stats' in result:
replre = r'(stats|cache)_'
statres = result['stats']
for attr in result['stats']:
if '/' not in attr:
key = re.sub(replre, '', attr)
statres[key] = statres.pop(attr)
else:
stat, key = attr.split('/', 1)
stat = re.sub(replre, '', stat)
key = re.sub(replre, '', key)
if stat not in statres:
statres[stat] = {}
statres[stat][key] = statres.pop(attr)
result['stats'] = statres
# ---------------- Internals ----------------
if internals:
interres = result.pop('inter_ro', {})
interres.update(result.pop('inter_rw', {}))
if interres:
for key in interres:
if key.startswith('internal'):
nkey = re.sub(r'internal[s/]*', '', key)
interres[nkey] = interres.pop(key)
key = nkey
if key.startswith(('btree', 'writeback')):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in interres:
interres[mkey] = {}
interres[mkey][skey] = interres.pop(key)
result['internals'] = interres
# ---------------- Config ----------------
if config:
configres = result['config']
for key in configres:
if key.startswith('writeback'):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in configres:
configres[mkey] = {}
configres[mkey][skey] = configres.pop(key)
result['config'] = configres
# ---------------- Superblock ----------------
if superblock:
result['superblock'] = super_(dev)
return result
|
Check the state of a single bcache device
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc stats=True
:param stats: include statistics
:param settings: include all settings
:param internals: include all internals
:param superblock: include superblock info
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bcache.py#L451-L561
|
[
"def uuid(dev=None):\n '''\n Return the bcache UUID of a block device.\n If no device is given, the Cache UUID is returned.\n\n CLI example:\n\n .. code-block:: bash\n\n salt '*' bcache.uuid\n salt '*' bcache.uuid /dev/sda\n salt '*' bcache.uuid bcache0\n\n '''\n try:\n if dev is None:\n # take the only directory in /sys/fs/bcache and return it's basename\n return list(salt.utils.path.os_walk('/sys/fs/bcache/'))[0][1][0]\n else:\n # basename of the /sys/block/{dev}/bcache/cache symlink target\n return os.path.basename(_bcsys(dev, 'cache'))\n except Exception:\n return False\n",
"def super_(dev):\n '''\n Read out BCache SuperBlock\n\n CLI example:\n\n .. code-block:: bash\n\n salt '*' bcache.device bcache0\n salt '*' bcache.device /dev/sdc\n\n '''\n dev = _devpath(dev)\n ret = {}\n\n res = _run_all('bcache-super-show {0}'.format(dev), 'error', 'Error reading superblock on {0}: %s'.format(dev))\n if not res:\n return False\n\n for line in res.splitlines(): # pylint: disable=no-member\n line = line.strip()\n if not line:\n continue\n\n key, val = [val.strip() for val in re.split(r'[\\s]+', line, maxsplit=1)]\n if not (key and val):\n continue\n\n mval = None\n if ' ' in val:\n rval, mval = [val.strip() for val in re.split(r'[\\s]+', val, maxsplit=1)]\n mval = mval[1:-1]\n else:\n rval = val\n\n try:\n rval = int(rval)\n except Exception:\n try:\n rval = float(rval)\n except Exception:\n if rval == 'yes':\n rval = True\n elif rval == 'no':\n rval = False\n\n pkey, key = re.split(r'\\.', key, maxsplit=1)\n if pkey not in ret:\n ret[pkey] = {}\n\n if mval is not None:\n ret[pkey][key] = (rval, mval)\n else:\n ret[pkey][key] = rval\n\n return ret\n",
"def _bcsys(dev, name, value=None, log_lvl=None, log_msg=None):\n '''\n Simple wrapper to interface with backing devs SysFS\n '''\n return _sysfs_attr([_bcpath(dev), name], value, log_lvl, log_msg)\n",
"def _sysfs_attr(name, value=None, log_lvl=None, log_msg=None):\n '''\n Simple wrapper with logging around sysfs.attr\n '''\n if isinstance(name, six.string_types):\n name = [name]\n res = __salt__['sysfs.attr'](os.path.join(*name), value)\n if not res and log_lvl is not None and log_msg is not None:\n log.log(LOG[log_lvl], log_msg)\n return res\n",
"def _bcpath(dev):\n '''\n Full SysFS path of a bcache device\n '''\n return os.path.join(_syspath(dev), 'bcache')\n",
"def _bdev(dev=None):\n '''\n Resolve a bcacheX or cache to a real dev\n :return: basename of bcache dev\n '''\n if dev is None:\n dev = _fssys('cache0')\n else:\n dev = _bcpath(dev)\n\n if not dev:\n return False\n else:\n return _devbase(os.path.dirname(dev))\n",
"def _fspath():\n '''\n :return: path of active bcache\n '''\n cuuid = uuid()\n if not cuuid:\n return False\n else:\n return os.path.join('/sys/fs/bcache/', cuuid)\n",
"def _sysfs_parse(path, base_attr=None, stats=False, config=False, internals=False, options=False):\n '''\n Helper function for parsing BCache's SysFS interface\n '''\n result = {}\n\n # ---------------- Parse through the interfaces list ----------------\n intfs = __salt__['sysfs.interfaces'](path)\n\n # Actions, we ignore\n del intfs['w']\n\n # -------- Sorting hat --------\n binkeys = []\n if internals:\n binkeys.extend(['inter_ro', 'inter_rw'])\n if config:\n binkeys.append('config')\n if stats:\n binkeys.append('stats')\n\n bintf = {}\n for key in binkeys:\n bintf[key] = []\n\n for intf in intfs['r']:\n if intf.startswith('internal'):\n key = 'inter_ro'\n elif 'stats' in intf:\n key = 'stats'\n else:\n # What to do with these???\n # I'll utilize 'inter_ro' as 'misc' as well\n key = 'inter_ro'\n\n if key in bintf:\n bintf[key].append(intf)\n\n for intf in intfs['rw']:\n if intf.startswith('internal'):\n key = 'inter_rw'\n else:\n key = 'config'\n\n if key in bintf:\n bintf[key].append(intf)\n\n if base_attr is not None:\n for intf in bintf:\n bintf[intf] = [sintf for sintf in bintf[intf] if sintf not in base_attr]\n bintf['base'] = base_attr\n\n mods = {\n 'stats': ['internal/bset_tree_stats', 'writeback_rate_debug', 'metadata_written', 'nbuckets', 'written',\n 'average_key_size', 'btree_cache_size'],\n }\n\n for modt, modlist in mods.items():\n found = []\n if modt not in bintf:\n continue\n for mod in modlist:\n for intflist in bintf.values():\n if mod in intflist:\n found.append(mod)\n intflist.remove(mod)\n bintf[modt] += found\n\n # -------- Fetch SysFS vals --------\n bintflist = [intf for iflist in bintf.values() for intf in iflist]\n result.update(__salt__['sysfs.read'](bintflist, path))\n\n # -------- Parse through well known string lists --------\n for strlist in ('writeback_rate_debug', 'internal/bset_tree_stats', 'priority_stats'):\n if strlist in result:\n listres = {}\n for line in result[strlist].split('\\n'):\n key, val = line.split(':', 1)\n val = val.strip()\n try:\n val = int(val)\n except Exception:\n try:\n val = float(val)\n except Exception:\n pass\n listres[key.strip()] = val\n result[strlist] = listres\n\n # -------- Parse through selection lists --------\n if not options:\n for sellist in ('cache_mode', 'cache_replacement_policy', 'errors'):\n if sellist in result:\n result[sellist] = re.search(r'\\[(.+)\\]', result[sellist]).groups()[0]\n\n # -------- Parse through well known bools --------\n for boolkey in ('running', 'writeback_running', 'congested'):\n if boolkey in result:\n result[boolkey] = bool(result[boolkey])\n\n # -------- Recategorize results --------\n bresult = {}\n for iftype, intflist in bintf.items():\n ifres = {}\n for intf in intflist:\n if intf in result:\n ifres[intf] = result.pop(intf)\n if ifres:\n bresult[iftype] = ifres\n\n return bresult\n"
] |
# -*- coding: utf-8 -*-
'''
Module for managing BCache sets
BCache is a block-level caching mechanism similar to ZFS L2ARC/ZIL, dm-cache and fscache.
It works by formatting one block device as a cache set, then adding backend devices
(which need to be formatted as such) to the set and activating them.
It's available in Linux mainline kernel since 3.10
https://www.kernel.org/doc/Documentation/bcache.txt
This module needs the bcache userspace tools to function.
.. versionadded: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import time
import re
from salt.ext import six
# Import salt libs
import salt.utils.path
log = logging.getLogger(__name__)
LOG = {
'trace': logging.TRACE,
'debug': logging.DEBUG,
'info': logging.INFO,
'warn': logging.WARNING,
'error': logging.ERROR,
'crit': logging.CRITICAL,
}
__func_alias__ = {
'attach_': 'attach',
'config_': 'config',
'super_': 'super',
}
HAS_BLKDISCARD = salt.utils.path.which('blkdiscard') is not None
def __virtual__():
'''
Only work when make-bcache is installed
'''
return salt.utils.path.which('make-bcache') is not None
def uuid(dev=None):
'''
Return the bcache UUID of a block device.
If no device is given, the Cache UUID is returned.
CLI example:
.. code-block:: bash
salt '*' bcache.uuid
salt '*' bcache.uuid /dev/sda
salt '*' bcache.uuid bcache0
'''
try:
if dev is None:
# take the only directory in /sys/fs/bcache and return it's basename
return list(salt.utils.path.os_walk('/sys/fs/bcache/'))[0][1][0]
else:
# basename of the /sys/block/{dev}/bcache/cache symlink target
return os.path.basename(_bcsys(dev, 'cache'))
except Exception:
return False
def attach_(dev=None):
'''
Attach a backing devices to a cache set
If no dev is given, all backing devices will be attached.
CLI example:
.. code-block:: bash
salt '*' bcache.attach sdc
salt '*' bcache.attach /dev/bcache1
:return: bool or None if nuttin' happened
'''
cache = uuid()
if not cache:
log.error('No cache to attach %s to', dev)
return False
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = attach_(dev)
return res if res else None
bcache = uuid(dev)
if bcache:
if bcache == cache:
log.info('%s is already attached to bcache %s, doing nothing', dev, cache)
return None
elif not detach(dev):
return False
log.debug('Attaching %s to bcache %s', dev, cache)
if not _bcsys(dev, 'attach', cache,
'error', 'Error attaching {0} to bcache {1}'.format(dev, cache)):
return False
return _wait(lambda: uuid(dev) == cache,
'error', '{0} received attach to bcache {1}, but did not comply'.format(dev, cache))
def detach(dev=None):
'''
Detach a backing device(s) from a cache set
If no dev is given, all backing devices will be attached.
Detaching a backing device will flush it's write cache.
This should leave the underlying device in a consistent state, but might take a while.
CLI example:
.. code-block:: bash
salt '*' bcache.detach sdc
salt '*' bcache.detach bcache1
'''
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = detach(dev)
return res if res else None
log.debug('Detaching %s', dev)
if not _bcsys(dev, 'detach', 'goaway', 'error', 'Error detaching {0}'.format(dev)):
return False
return _wait(lambda: uuid(dev) is False, 'error', '{0} received detach, but did not comply'.format(dev), 300)
def start():
'''
Trigger a start of the full bcache system through udev.
CLI example:
.. code-block:: bash
salt '*' bcache.start
'''
if not _run_all('udevadm trigger', 'error', 'Error starting bcache: %s'):
return False
elif not _wait(lambda: uuid() is not False, 'warn', 'Bcache system started, but no active cache set found.'):
return False
return True
def stop(dev=None):
'''
Stop a bcache device
If no device is given, all backing devices will be detached from the cache, which will subsequently be stopped.
.. warning::
'Stop' on an individual backing device means hard-stop;
no attempt at flushing will be done and the bcache device will seemingly 'disappear' from the device lists
CLI example:
.. code-block:: bash
salt '*' bcache.stop
'''
if dev is not None:
log.warning('Stopping %s, device will only reappear after reregistering!', dev)
if not _bcsys(dev, 'stop', 'goaway', 'error', 'Error stopping {0}'.format(dev)):
return False
return _wait(lambda: _sysfs_attr(_bcpath(dev)) is False, 'error', 'Device {0} did not stop'.format(dev), 300)
else:
cache = uuid()
if not cache:
log.warning('bcache already stopped?')
return None
if not _alltrue(detach()):
return False
elif not _fssys('stop', 'goaway', 'error', 'Error stopping cache'):
return False
return _wait(lambda: uuid() is False, 'error', 'Cache did not stop', 300)
def back_make(dev, cache_mode='writeback', force=False, attach=True, bucket_size=None):
'''
Create a backing device for attachment to a set.
Because the block size must be the same, a cache set already needs to exist.
CLI example:
.. code-block:: bash
salt '*' bcache.back_make sdc cache_mode=writeback attach=True
:param cache_mode: writethrough, writeback, writearound or none.
:param force: Overwrite existing bcaches
:param attach: Immediately attach the backing device to the set
:param bucket_size: Size of a bucket (see kernel doc)
'''
# pylint: disable=too-many-return-statements
cache = uuid()
if not cache:
log.error('No bcache set found')
return False
elif _sysfs_attr(_bcpath(dev)):
if not force:
log.error('%s already contains a bcache. Wipe it manually or use force', dev)
return False
elif uuid(dev) and not detach(dev):
return False
elif not stop(dev):
return False
dev = _devpath(dev)
block_size = _size_map(_fssys('block_size'))
# You might want to override, we pick the cache set's as sane default
if bucket_size is None:
bucket_size = _size_map(_fssys('bucket_size'))
cmd = 'make-bcache --block {0} --bucket {1} --{2} --bdev {3}'.format(block_size, bucket_size, cache_mode, dev)
if force:
cmd += ' --wipe-bcache'
if not _run_all(cmd, 'error', 'Error creating backing device {0}: %s'.format(dev)):
return False
elif not _sysfs_attr('fs/bcache/register', _devpath(dev),
'error', 'Error registering backing device {0}'.format(dev)):
return False
elif not _wait(lambda: _sysfs_attr(_bcpath(dev)) is not False,
'error', 'Backing device {0} did not register'.format(dev)):
return False
elif attach:
return attach_(dev)
return True
def cache_make(dev, reserved=None, force=False, block_size=None, bucket_size=None, attach=True):
'''
Create BCache cache on a block device.
If blkdiscard is available the entire device will be properly cleared in advance.
CLI example:
.. code-block:: bash
salt '*' bcache.cache_make sdb reserved=10% block_size=4096
:param reserved: if dev is a full device, create a partition table with this size empty.
.. note::
this increases the amount of reserved space available to SSD garbage collectors,
potentially (vastly) increasing performance
:param block_size: Block size of the cache; defaults to devices' logical block size
:param force: Overwrite existing BCache sets
:param attach: Attach all existing backend devices immediately
'''
# TODO: multiple devs == md jbod
# pylint: disable=too-many-return-statements
# ---------------- Preflight checks ----------------
cache = uuid()
if cache:
if not force:
log.error('BCache cache %s is already on the system', cache)
return False
cache = _bdev()
dev = _devbase(dev)
udev = __salt__['udev.env'](dev)
if ('ID_FS_TYPE' in udev or (udev.get('DEVTYPE', None) != 'partition' and 'ID_PART_TABLE_TYPE' in udev)) \
and not force:
log.error('%s already contains data, wipe first or force', dev)
return False
elif reserved is not None and udev.get('DEVTYPE', None) != 'disk':
log.error('Need a partitionable blockdev for reserved to work')
return False
_, block, bucket = _sizes(dev)
if bucket_size is None:
bucket_size = bucket
# TODO: bucket from _sizes() makes no sense
bucket_size = False
if block_size is None:
block_size = block
# ---------------- Still here, start doing destructive stuff ----------------
if cache:
if not stop():
return False
# Wipe the current cache device as well,
# forever ruining any chance of it accidentally popping up again
elif not _wipe(cache):
return False
# Can't do enough wiping
if not _wipe(dev):
return False
if reserved:
cmd = 'parted -m -s -a optimal -- ' \
'/dev/{0} mklabel gpt mkpart bcache-reserved 1M {1} mkpart bcache {1} 100%'.format(dev, reserved)
# if wipe was incomplete & part layout remains the same,
# this is one condition set where udev would make it accidentally popup again
if not _run_all(cmd, 'error', 'Error creating bcache partitions on {0}: %s'.format(dev)):
return False
dev = '{0}2'.format(dev)
# ---------------- Finally, create a cache ----------------
cmd = 'make-bcache --cache /dev/{0} --block {1} --wipe-bcache'.format(dev, block_size)
# Actually bucket_size should always have a value, but for testing 0 is possible as well
if bucket_size:
cmd += ' --bucket {0}'.format(bucket_size)
if not _run_all(cmd, 'error', 'Error creating cache {0}: %s'.format(dev)):
return False
elif not _wait(lambda: uuid() is not False,
'error', 'Cache {0} seemingly created OK, but FS did not activate'.format(dev)):
return False
if attach:
return _alltrue(attach_())
else:
return True
def config_(dev=None, **kwargs):
'''
Show or update config of a bcache device.
If no device is given, operate on the cache set itself.
CLI example:
.. code-block:: bash
salt '*' bcache.config
salt '*' bcache.config bcache1
salt '*' bcache.config errors=panic journal_delay_ms=150
salt '*' bcache.config bcache1 cache_mode=writeback writeback_percent=15
:return: config or True/False
'''
if dev is None:
spath = _fspath()
else:
spath = _bcpath(dev)
# filter out 'hidden' kwargs added by our favourite orchestration system
updates = dict([(key, val) for key, val in kwargs.items() if not key.startswith('__')])
if updates:
endres = 0
for key, val in updates.items():
endres += _sysfs_attr([spath, key], val,
'warn', 'Failed to update {0} with {1}'.format(os.path.join(spath, key), val))
return endres > 0
else:
result = {}
data = _sysfs_parse(spath, config=True, internals=True, options=True)
for key in ('other_ro', 'inter_ro'):
if key in data:
del data[key]
for key in data:
result.update(data[key])
return result
def status(stats=False, config=False, internals=False, superblock=False, alldevs=False):
'''
Show the full status of the BCache system and optionally all it's involved devices
CLI example:
.. code-block:: bash
salt '*' bcache.status
salt '*' bcache.status stats=True
salt '*' bcache.status internals=True alldevs=True
:param stats: include statistics
:param config: include settings
:param internals: include internals
:param superblock: include superblock
'''
bdevs = []
for _, links, _ in salt.utils.path.os_walk('/sys/block/'):
for block in links:
if 'bcache' in block:
continue
for spath, sdirs, _ in salt.utils.path.os_walk('/sys/block/{0}'.format(block), followlinks=False):
if 'bcache' in sdirs:
bdevs.append(os.path.basename(spath))
statii = {}
for bcache in bdevs:
statii[bcache] = device(bcache, stats, config, internals, superblock)
cuuid = uuid()
cdev = _bdev()
if cdev:
count = 0
for dev in statii:
if dev != cdev:
# it's a backing dev
if statii[dev]['cache'] == cuuid:
count += 1
statii[cdev]['attached_backing_devices'] = count
if not alldevs:
statii = statii[cdev]
return statii
def super_(dev):
'''
Read out BCache SuperBlock
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc
'''
dev = _devpath(dev)
ret = {}
res = _run_all('bcache-super-show {0}'.format(dev), 'error', 'Error reading superblock on {0}: %s'.format(dev))
if not res:
return False
for line in res.splitlines(): # pylint: disable=no-member
line = line.strip()
if not line:
continue
key, val = [val.strip() for val in re.split(r'[\s]+', line, maxsplit=1)]
if not (key and val):
continue
mval = None
if ' ' in val:
rval, mval = [val.strip() for val in re.split(r'[\s]+', val, maxsplit=1)]
mval = mval[1:-1]
else:
rval = val
try:
rval = int(rval)
except Exception:
try:
rval = float(rval)
except Exception:
if rval == 'yes':
rval = True
elif rval == 'no':
rval = False
pkey, key = re.split(r'\.', key, maxsplit=1)
if pkey not in ret:
ret[pkey] = {}
if mval is not None:
ret[pkey][key] = (rval, mval)
else:
ret[pkey][key] = rval
return ret
# -------------------------------- HELPER FUNCTIONS --------------------------------
def _devbase(dev):
'''
Basename of just about any dev
'''
dev = os.path.realpath(os.path.expandvars(dev))
dev = os.path.basename(dev)
return dev
def _devpath(dev):
'''
Return /dev name of just about any dev
:return: /dev/devicename
'''
return os.path.join('/dev', _devbase(dev))
def _syspath(dev):
'''
Full SysFS path of a device
'''
dev = _devbase(dev)
dev = re.sub(r'^([vhs][a-z]+)([0-9]+)', r'\1/\1\2', dev)
# name = re.sub(r'^([a-z]+)(?<!(bcache|md|dm))([0-9]+)', r'\1/\1\2', name)
return os.path.join('/sys/block/', dev)
def _bdev(dev=None):
'''
Resolve a bcacheX or cache to a real dev
:return: basename of bcache dev
'''
if dev is None:
dev = _fssys('cache0')
else:
dev = _bcpath(dev)
if not dev:
return False
else:
return _devbase(os.path.dirname(dev))
def _bcpath(dev):
'''
Full SysFS path of a bcache device
'''
return os.path.join(_syspath(dev), 'bcache')
def _fspath():
'''
:return: path of active bcache
'''
cuuid = uuid()
if not cuuid:
return False
else:
return os.path.join('/sys/fs/bcache/', cuuid)
def _fssys(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with bcache SysFS
'''
fspath = _fspath()
if not fspath:
return False
else:
return _sysfs_attr([fspath, name], value, log_lvl, log_msg)
def _bcsys(dev, name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with backing devs SysFS
'''
return _sysfs_attr([_bcpath(dev), name], value, log_lvl, log_msg)
def _sysfs_attr(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper with logging around sysfs.attr
'''
if isinstance(name, six.string_types):
name = [name]
res = __salt__['sysfs.attr'](os.path.join(*name), value)
if not res and log_lvl is not None and log_msg is not None:
log.log(LOG[log_lvl], log_msg)
return res
def _sysfs_parse(path, base_attr=None, stats=False, config=False, internals=False, options=False):
'''
Helper function for parsing BCache's SysFS interface
'''
result = {}
# ---------------- Parse through the interfaces list ----------------
intfs = __salt__['sysfs.interfaces'](path)
# Actions, we ignore
del intfs['w']
# -------- Sorting hat --------
binkeys = []
if internals:
binkeys.extend(['inter_ro', 'inter_rw'])
if config:
binkeys.append('config')
if stats:
binkeys.append('stats')
bintf = {}
for key in binkeys:
bintf[key] = []
for intf in intfs['r']:
if intf.startswith('internal'):
key = 'inter_ro'
elif 'stats' in intf:
key = 'stats'
else:
# What to do with these???
# I'll utilize 'inter_ro' as 'misc' as well
key = 'inter_ro'
if key in bintf:
bintf[key].append(intf)
for intf in intfs['rw']:
if intf.startswith('internal'):
key = 'inter_rw'
else:
key = 'config'
if key in bintf:
bintf[key].append(intf)
if base_attr is not None:
for intf in bintf:
bintf[intf] = [sintf for sintf in bintf[intf] if sintf not in base_attr]
bintf['base'] = base_attr
mods = {
'stats': ['internal/bset_tree_stats', 'writeback_rate_debug', 'metadata_written', 'nbuckets', 'written',
'average_key_size', 'btree_cache_size'],
}
for modt, modlist in mods.items():
found = []
if modt not in bintf:
continue
for mod in modlist:
for intflist in bintf.values():
if mod in intflist:
found.append(mod)
intflist.remove(mod)
bintf[modt] += found
# -------- Fetch SysFS vals --------
bintflist = [intf for iflist in bintf.values() for intf in iflist]
result.update(__salt__['sysfs.read'](bintflist, path))
# -------- Parse through well known string lists --------
for strlist in ('writeback_rate_debug', 'internal/bset_tree_stats', 'priority_stats'):
if strlist in result:
listres = {}
for line in result[strlist].split('\n'):
key, val = line.split(':', 1)
val = val.strip()
try:
val = int(val)
except Exception:
try:
val = float(val)
except Exception:
pass
listres[key.strip()] = val
result[strlist] = listres
# -------- Parse through selection lists --------
if not options:
for sellist in ('cache_mode', 'cache_replacement_policy', 'errors'):
if sellist in result:
result[sellist] = re.search(r'\[(.+)\]', result[sellist]).groups()[0]
# -------- Parse through well known bools --------
for boolkey in ('running', 'writeback_running', 'congested'):
if boolkey in result:
result[boolkey] = bool(result[boolkey])
# -------- Recategorize results --------
bresult = {}
for iftype, intflist in bintf.items():
ifres = {}
for intf in intflist:
if intf in result:
ifres[intf] = result.pop(intf)
if ifres:
bresult[iftype] = ifres
return bresult
def _size_map(size):
'''
Map Bcache's size strings to real bytes
'''
try:
# I know, I know, EAFP.
# But everything else is reason for None
if not isinstance(size, int):
if re.search(r'[Kk]', size):
size = 1024 * float(re.sub(r'[Kk]', '', size))
elif re.search(r'[Mm]', size):
size = 1024**2 * float(re.sub(r'[Mm]', '', size))
size = int(size)
return size
except Exception:
return None
def _sizes(dev):
'''
Return neigh useless sizing info about a blockdev
:return: (total size in blocks, blocksize, maximum discard size in bytes)
'''
dev = _devbase(dev)
# standarization yay
block_sizes = ('hw_sector_size', 'minimum_io_size', 'physical_block_size', 'logical_block_size')
discard_sizes = ('discard_max_bytes', 'discard_max_hw_bytes', )
sysfs = __salt__['sysfs.read'](
('size',
'queue/hw_sector_size', '../queue/hw_sector_size',
'queue/discard_max_bytes', '../queue/discard_max_bytes'),
root=_syspath(dev))
# TODO: makes no sense
# First of all, it has to be a power of 2
# Secondly, this returns 4GiB - 512b on Intel 3500's for some weird reason
# discard_granularity seems in bytes, resolves to 512b ???
# max_hw_sectors_kb???
# There's also discard_max_hw_bytes more recently
# See: https://www.kernel.org/doc/Documentation/block/queue-sysfs.txt
# Also, I cant find any docs yet regarding bucket sizes;
# it's supposed to be discard_max_hw_bytes,
# but no way to figure that one reliably out apparently
discard = sysfs.get('queue/discard_max_bytes', sysfs.get('../queue/discard_max_bytes', None))
block = sysfs.get('queue/hw_sector_size', sysfs.get('../queue/hw_sector_size', None))
return 512*sysfs['size'], block, discard
def _wipe(dev):
'''
REALLY DESTRUCTIVE STUFF RIGHT AHEAD
'''
endres = 0
dev = _devbase(dev)
size, block, discard = _sizes(dev)
if discard is None:
log.error('Unable to read SysFS props for %s', dev)
return None
elif not discard:
log.warning('%s seems unable to discard', dev)
wiper = 'dd'
elif not HAS_BLKDISCARD:
log.warning('blkdiscard binary not available, properly wipe the dev manually for optimal results')
wiper = 'dd'
else:
wiper = 'blkdiscard'
wipe_failmsg = 'Error wiping {0}: %s'.format(dev)
if wiper == 'dd':
blocks = 4
cmd = 'dd if=/dev/zero of=/dev/{0} bs=1M count={1}'.format(dev, blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# Some stuff (<cough>GPT</cough>) writes stuff at the end of a dev as well
cmd += ' seek={0}'.format((size/1024**2) - blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
elif wiper == 'blkdiscard':
cmd = 'blkdiscard /dev/{0}'.format(dev)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# TODO: fix annoying bug failing blkdiscard by trying to discard 1 sector past blkdev
endres = 1
return endres > 0
def _wait(lfunc, log_lvl=None, log_msg=None, tries=10):
'''
Wait for lfunc to be True
:return: True if lfunc succeeded within tries, False if it didn't
'''
i = 0
while i < tries:
time.sleep(1)
if lfunc():
return True
else:
i += 1
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg)
return False
def _run_all(cmd, log_lvl=None, log_msg=None, exitcode=0):
'''
Simple wrapper around cmd.run_all
log_msg can contain {0} for stderr
:return: True or stdout, False if retcode wasn't exitcode
'''
res = __salt__['cmd.run_all'](cmd)
if res['retcode'] == exitcode:
if res['stdout']:
return res['stdout']
else:
return True
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg, res['stderr'])
return False
def _alltrue(resdict):
if resdict is None:
return True
return len([val for val in resdict.values() if val]) > 0
|
saltstack/salt
|
salt/modules/bcache.py
|
super_
|
python
|
def super_(dev):
'''
Read out BCache SuperBlock
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc
'''
dev = _devpath(dev)
ret = {}
res = _run_all('bcache-super-show {0}'.format(dev), 'error', 'Error reading superblock on {0}: %s'.format(dev))
if not res:
return False
for line in res.splitlines(): # pylint: disable=no-member
line = line.strip()
if not line:
continue
key, val = [val.strip() for val in re.split(r'[\s]+', line, maxsplit=1)]
if not (key and val):
continue
mval = None
if ' ' in val:
rval, mval = [val.strip() for val in re.split(r'[\s]+', val, maxsplit=1)]
mval = mval[1:-1]
else:
rval = val
try:
rval = int(rval)
except Exception:
try:
rval = float(rval)
except Exception:
if rval == 'yes':
rval = True
elif rval == 'no':
rval = False
pkey, key = re.split(r'\.', key, maxsplit=1)
if pkey not in ret:
ret[pkey] = {}
if mval is not None:
ret[pkey][key] = (rval, mval)
else:
ret[pkey][key] = rval
return ret
|
Read out BCache SuperBlock
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bcache.py#L564-L619
|
[
"def _run_all(cmd, log_lvl=None, log_msg=None, exitcode=0):\n '''\n Simple wrapper around cmd.run_all\n log_msg can contain {0} for stderr\n :return: True or stdout, False if retcode wasn't exitcode\n '''\n res = __salt__['cmd.run_all'](cmd)\n if res['retcode'] == exitcode:\n if res['stdout']:\n return res['stdout']\n else:\n return True\n\n if log_lvl is not None:\n log.log(LOG[log_lvl], log_msg, res['stderr'])\n return False\n",
"def _devpath(dev):\n '''\n Return /dev name of just about any dev\n :return: /dev/devicename\n '''\n return os.path.join('/dev', _devbase(dev))\n"
] |
# -*- coding: utf-8 -*-
'''
Module for managing BCache sets
BCache is a block-level caching mechanism similar to ZFS L2ARC/ZIL, dm-cache and fscache.
It works by formatting one block device as a cache set, then adding backend devices
(which need to be formatted as such) to the set and activating them.
It's available in Linux mainline kernel since 3.10
https://www.kernel.org/doc/Documentation/bcache.txt
This module needs the bcache userspace tools to function.
.. versionadded: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import time
import re
from salt.ext import six
# Import salt libs
import salt.utils.path
log = logging.getLogger(__name__)
LOG = {
'trace': logging.TRACE,
'debug': logging.DEBUG,
'info': logging.INFO,
'warn': logging.WARNING,
'error': logging.ERROR,
'crit': logging.CRITICAL,
}
__func_alias__ = {
'attach_': 'attach',
'config_': 'config',
'super_': 'super',
}
HAS_BLKDISCARD = salt.utils.path.which('blkdiscard') is not None
def __virtual__():
'''
Only work when make-bcache is installed
'''
return salt.utils.path.which('make-bcache') is not None
def uuid(dev=None):
'''
Return the bcache UUID of a block device.
If no device is given, the Cache UUID is returned.
CLI example:
.. code-block:: bash
salt '*' bcache.uuid
salt '*' bcache.uuid /dev/sda
salt '*' bcache.uuid bcache0
'''
try:
if dev is None:
# take the only directory in /sys/fs/bcache and return it's basename
return list(salt.utils.path.os_walk('/sys/fs/bcache/'))[0][1][0]
else:
# basename of the /sys/block/{dev}/bcache/cache symlink target
return os.path.basename(_bcsys(dev, 'cache'))
except Exception:
return False
def attach_(dev=None):
'''
Attach a backing devices to a cache set
If no dev is given, all backing devices will be attached.
CLI example:
.. code-block:: bash
salt '*' bcache.attach sdc
salt '*' bcache.attach /dev/bcache1
:return: bool or None if nuttin' happened
'''
cache = uuid()
if not cache:
log.error('No cache to attach %s to', dev)
return False
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = attach_(dev)
return res if res else None
bcache = uuid(dev)
if bcache:
if bcache == cache:
log.info('%s is already attached to bcache %s, doing nothing', dev, cache)
return None
elif not detach(dev):
return False
log.debug('Attaching %s to bcache %s', dev, cache)
if not _bcsys(dev, 'attach', cache,
'error', 'Error attaching {0} to bcache {1}'.format(dev, cache)):
return False
return _wait(lambda: uuid(dev) == cache,
'error', '{0} received attach to bcache {1}, but did not comply'.format(dev, cache))
def detach(dev=None):
'''
Detach a backing device(s) from a cache set
If no dev is given, all backing devices will be attached.
Detaching a backing device will flush it's write cache.
This should leave the underlying device in a consistent state, but might take a while.
CLI example:
.. code-block:: bash
salt '*' bcache.detach sdc
salt '*' bcache.detach bcache1
'''
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = detach(dev)
return res if res else None
log.debug('Detaching %s', dev)
if not _bcsys(dev, 'detach', 'goaway', 'error', 'Error detaching {0}'.format(dev)):
return False
return _wait(lambda: uuid(dev) is False, 'error', '{0} received detach, but did not comply'.format(dev), 300)
def start():
'''
Trigger a start of the full bcache system through udev.
CLI example:
.. code-block:: bash
salt '*' bcache.start
'''
if not _run_all('udevadm trigger', 'error', 'Error starting bcache: %s'):
return False
elif not _wait(lambda: uuid() is not False, 'warn', 'Bcache system started, but no active cache set found.'):
return False
return True
def stop(dev=None):
'''
Stop a bcache device
If no device is given, all backing devices will be detached from the cache, which will subsequently be stopped.
.. warning::
'Stop' on an individual backing device means hard-stop;
no attempt at flushing will be done and the bcache device will seemingly 'disappear' from the device lists
CLI example:
.. code-block:: bash
salt '*' bcache.stop
'''
if dev is not None:
log.warning('Stopping %s, device will only reappear after reregistering!', dev)
if not _bcsys(dev, 'stop', 'goaway', 'error', 'Error stopping {0}'.format(dev)):
return False
return _wait(lambda: _sysfs_attr(_bcpath(dev)) is False, 'error', 'Device {0} did not stop'.format(dev), 300)
else:
cache = uuid()
if not cache:
log.warning('bcache already stopped?')
return None
if not _alltrue(detach()):
return False
elif not _fssys('stop', 'goaway', 'error', 'Error stopping cache'):
return False
return _wait(lambda: uuid() is False, 'error', 'Cache did not stop', 300)
def back_make(dev, cache_mode='writeback', force=False, attach=True, bucket_size=None):
'''
Create a backing device for attachment to a set.
Because the block size must be the same, a cache set already needs to exist.
CLI example:
.. code-block:: bash
salt '*' bcache.back_make sdc cache_mode=writeback attach=True
:param cache_mode: writethrough, writeback, writearound or none.
:param force: Overwrite existing bcaches
:param attach: Immediately attach the backing device to the set
:param bucket_size: Size of a bucket (see kernel doc)
'''
# pylint: disable=too-many-return-statements
cache = uuid()
if not cache:
log.error('No bcache set found')
return False
elif _sysfs_attr(_bcpath(dev)):
if not force:
log.error('%s already contains a bcache. Wipe it manually or use force', dev)
return False
elif uuid(dev) and not detach(dev):
return False
elif not stop(dev):
return False
dev = _devpath(dev)
block_size = _size_map(_fssys('block_size'))
# You might want to override, we pick the cache set's as sane default
if bucket_size is None:
bucket_size = _size_map(_fssys('bucket_size'))
cmd = 'make-bcache --block {0} --bucket {1} --{2} --bdev {3}'.format(block_size, bucket_size, cache_mode, dev)
if force:
cmd += ' --wipe-bcache'
if not _run_all(cmd, 'error', 'Error creating backing device {0}: %s'.format(dev)):
return False
elif not _sysfs_attr('fs/bcache/register', _devpath(dev),
'error', 'Error registering backing device {0}'.format(dev)):
return False
elif not _wait(lambda: _sysfs_attr(_bcpath(dev)) is not False,
'error', 'Backing device {0} did not register'.format(dev)):
return False
elif attach:
return attach_(dev)
return True
def cache_make(dev, reserved=None, force=False, block_size=None, bucket_size=None, attach=True):
'''
Create BCache cache on a block device.
If blkdiscard is available the entire device will be properly cleared in advance.
CLI example:
.. code-block:: bash
salt '*' bcache.cache_make sdb reserved=10% block_size=4096
:param reserved: if dev is a full device, create a partition table with this size empty.
.. note::
this increases the amount of reserved space available to SSD garbage collectors,
potentially (vastly) increasing performance
:param block_size: Block size of the cache; defaults to devices' logical block size
:param force: Overwrite existing BCache sets
:param attach: Attach all existing backend devices immediately
'''
# TODO: multiple devs == md jbod
# pylint: disable=too-many-return-statements
# ---------------- Preflight checks ----------------
cache = uuid()
if cache:
if not force:
log.error('BCache cache %s is already on the system', cache)
return False
cache = _bdev()
dev = _devbase(dev)
udev = __salt__['udev.env'](dev)
if ('ID_FS_TYPE' in udev or (udev.get('DEVTYPE', None) != 'partition' and 'ID_PART_TABLE_TYPE' in udev)) \
and not force:
log.error('%s already contains data, wipe first or force', dev)
return False
elif reserved is not None and udev.get('DEVTYPE', None) != 'disk':
log.error('Need a partitionable blockdev for reserved to work')
return False
_, block, bucket = _sizes(dev)
if bucket_size is None:
bucket_size = bucket
# TODO: bucket from _sizes() makes no sense
bucket_size = False
if block_size is None:
block_size = block
# ---------------- Still here, start doing destructive stuff ----------------
if cache:
if not stop():
return False
# Wipe the current cache device as well,
# forever ruining any chance of it accidentally popping up again
elif not _wipe(cache):
return False
# Can't do enough wiping
if not _wipe(dev):
return False
if reserved:
cmd = 'parted -m -s -a optimal -- ' \
'/dev/{0} mklabel gpt mkpart bcache-reserved 1M {1} mkpart bcache {1} 100%'.format(dev, reserved)
# if wipe was incomplete & part layout remains the same,
# this is one condition set where udev would make it accidentally popup again
if not _run_all(cmd, 'error', 'Error creating bcache partitions on {0}: %s'.format(dev)):
return False
dev = '{0}2'.format(dev)
# ---------------- Finally, create a cache ----------------
cmd = 'make-bcache --cache /dev/{0} --block {1} --wipe-bcache'.format(dev, block_size)
# Actually bucket_size should always have a value, but for testing 0 is possible as well
if bucket_size:
cmd += ' --bucket {0}'.format(bucket_size)
if not _run_all(cmd, 'error', 'Error creating cache {0}: %s'.format(dev)):
return False
elif not _wait(lambda: uuid() is not False,
'error', 'Cache {0} seemingly created OK, but FS did not activate'.format(dev)):
return False
if attach:
return _alltrue(attach_())
else:
return True
def config_(dev=None, **kwargs):
'''
Show or update config of a bcache device.
If no device is given, operate on the cache set itself.
CLI example:
.. code-block:: bash
salt '*' bcache.config
salt '*' bcache.config bcache1
salt '*' bcache.config errors=panic journal_delay_ms=150
salt '*' bcache.config bcache1 cache_mode=writeback writeback_percent=15
:return: config or True/False
'''
if dev is None:
spath = _fspath()
else:
spath = _bcpath(dev)
# filter out 'hidden' kwargs added by our favourite orchestration system
updates = dict([(key, val) for key, val in kwargs.items() if not key.startswith('__')])
if updates:
endres = 0
for key, val in updates.items():
endres += _sysfs_attr([spath, key], val,
'warn', 'Failed to update {0} with {1}'.format(os.path.join(spath, key), val))
return endres > 0
else:
result = {}
data = _sysfs_parse(spath, config=True, internals=True, options=True)
for key in ('other_ro', 'inter_ro'):
if key in data:
del data[key]
for key in data:
result.update(data[key])
return result
def status(stats=False, config=False, internals=False, superblock=False, alldevs=False):
'''
Show the full status of the BCache system and optionally all it's involved devices
CLI example:
.. code-block:: bash
salt '*' bcache.status
salt '*' bcache.status stats=True
salt '*' bcache.status internals=True alldevs=True
:param stats: include statistics
:param config: include settings
:param internals: include internals
:param superblock: include superblock
'''
bdevs = []
for _, links, _ in salt.utils.path.os_walk('/sys/block/'):
for block in links:
if 'bcache' in block:
continue
for spath, sdirs, _ in salt.utils.path.os_walk('/sys/block/{0}'.format(block), followlinks=False):
if 'bcache' in sdirs:
bdevs.append(os.path.basename(spath))
statii = {}
for bcache in bdevs:
statii[bcache] = device(bcache, stats, config, internals, superblock)
cuuid = uuid()
cdev = _bdev()
if cdev:
count = 0
for dev in statii:
if dev != cdev:
# it's a backing dev
if statii[dev]['cache'] == cuuid:
count += 1
statii[cdev]['attached_backing_devices'] = count
if not alldevs:
statii = statii[cdev]
return statii
def device(dev, stats=False, config=False, internals=False, superblock=False):
'''
Check the state of a single bcache device
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc stats=True
:param stats: include statistics
:param settings: include all settings
:param internals: include all internals
:param superblock: include superblock info
'''
result = {}
if not _sysfs_attr(_bcpath(dev), None, 'error', '{0} is not a bcache fo any kind'.format(dev)):
return False
elif _bcsys(dev, 'set'):
# ---------------- It's the cache itself ----------------
result['uuid'] = uuid()
base_attr = ['block_size', 'bucket_size', 'cache_available_percent', 'cache_replacement_policy', 'congested']
# ---------------- Parse through both the blockdev & the FS ----------------
result.update(_sysfs_parse(_bcpath(dev), base_attr, stats, config, internals))
result.update(_sysfs_parse(_fspath(), base_attr, stats, config, internals))
result.update(result.pop('base'))
else:
# ---------------- It's a backing device ----------------
back_uuid = uuid(dev)
if back_uuid is not None:
result['cache'] = back_uuid
try:
result['dev'] = os.path.basename(_bcsys(dev, 'dev'))
except Exception:
pass
result['bdev'] = _bdev(dev)
base_attr = ['cache_mode', 'running', 'state', 'writeback_running']
base_path = _bcpath(dev)
result.update(_sysfs_parse(base_path, base_attr, stats, config, internals))
result.update(result.pop('base'))
# ---------------- Modifications ----------------
state = [result['state']]
if result.pop('running'):
state.append('running')
else:
state.append('stopped')
if 'writeback_running' in result:
if result.pop('writeback_running'):
state.append('writeback_running')
else:
state.append('writeback_stopped')
result['state'] = state
# ---------------- Statistics ----------------
if 'stats' in result:
replre = r'(stats|cache)_'
statres = result['stats']
for attr in result['stats']:
if '/' not in attr:
key = re.sub(replre, '', attr)
statres[key] = statres.pop(attr)
else:
stat, key = attr.split('/', 1)
stat = re.sub(replre, '', stat)
key = re.sub(replre, '', key)
if stat not in statres:
statres[stat] = {}
statres[stat][key] = statres.pop(attr)
result['stats'] = statres
# ---------------- Internals ----------------
if internals:
interres = result.pop('inter_ro', {})
interres.update(result.pop('inter_rw', {}))
if interres:
for key in interres:
if key.startswith('internal'):
nkey = re.sub(r'internal[s/]*', '', key)
interres[nkey] = interres.pop(key)
key = nkey
if key.startswith(('btree', 'writeback')):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in interres:
interres[mkey] = {}
interres[mkey][skey] = interres.pop(key)
result['internals'] = interres
# ---------------- Config ----------------
if config:
configres = result['config']
for key in configres:
if key.startswith('writeback'):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in configres:
configres[mkey] = {}
configres[mkey][skey] = configres.pop(key)
result['config'] = configres
# ---------------- Superblock ----------------
if superblock:
result['superblock'] = super_(dev)
return result
# -------------------------------- HELPER FUNCTIONS --------------------------------
def _devbase(dev):
'''
Basename of just about any dev
'''
dev = os.path.realpath(os.path.expandvars(dev))
dev = os.path.basename(dev)
return dev
def _devpath(dev):
'''
Return /dev name of just about any dev
:return: /dev/devicename
'''
return os.path.join('/dev', _devbase(dev))
def _syspath(dev):
'''
Full SysFS path of a device
'''
dev = _devbase(dev)
dev = re.sub(r'^([vhs][a-z]+)([0-9]+)', r'\1/\1\2', dev)
# name = re.sub(r'^([a-z]+)(?<!(bcache|md|dm))([0-9]+)', r'\1/\1\2', name)
return os.path.join('/sys/block/', dev)
def _bdev(dev=None):
'''
Resolve a bcacheX or cache to a real dev
:return: basename of bcache dev
'''
if dev is None:
dev = _fssys('cache0')
else:
dev = _bcpath(dev)
if not dev:
return False
else:
return _devbase(os.path.dirname(dev))
def _bcpath(dev):
'''
Full SysFS path of a bcache device
'''
return os.path.join(_syspath(dev), 'bcache')
def _fspath():
'''
:return: path of active bcache
'''
cuuid = uuid()
if not cuuid:
return False
else:
return os.path.join('/sys/fs/bcache/', cuuid)
def _fssys(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with bcache SysFS
'''
fspath = _fspath()
if not fspath:
return False
else:
return _sysfs_attr([fspath, name], value, log_lvl, log_msg)
def _bcsys(dev, name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with backing devs SysFS
'''
return _sysfs_attr([_bcpath(dev), name], value, log_lvl, log_msg)
def _sysfs_attr(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper with logging around sysfs.attr
'''
if isinstance(name, six.string_types):
name = [name]
res = __salt__['sysfs.attr'](os.path.join(*name), value)
if not res and log_lvl is not None and log_msg is not None:
log.log(LOG[log_lvl], log_msg)
return res
def _sysfs_parse(path, base_attr=None, stats=False, config=False, internals=False, options=False):
'''
Helper function for parsing BCache's SysFS interface
'''
result = {}
# ---------------- Parse through the interfaces list ----------------
intfs = __salt__['sysfs.interfaces'](path)
# Actions, we ignore
del intfs['w']
# -------- Sorting hat --------
binkeys = []
if internals:
binkeys.extend(['inter_ro', 'inter_rw'])
if config:
binkeys.append('config')
if stats:
binkeys.append('stats')
bintf = {}
for key in binkeys:
bintf[key] = []
for intf in intfs['r']:
if intf.startswith('internal'):
key = 'inter_ro'
elif 'stats' in intf:
key = 'stats'
else:
# What to do with these???
# I'll utilize 'inter_ro' as 'misc' as well
key = 'inter_ro'
if key in bintf:
bintf[key].append(intf)
for intf in intfs['rw']:
if intf.startswith('internal'):
key = 'inter_rw'
else:
key = 'config'
if key in bintf:
bintf[key].append(intf)
if base_attr is not None:
for intf in bintf:
bintf[intf] = [sintf for sintf in bintf[intf] if sintf not in base_attr]
bintf['base'] = base_attr
mods = {
'stats': ['internal/bset_tree_stats', 'writeback_rate_debug', 'metadata_written', 'nbuckets', 'written',
'average_key_size', 'btree_cache_size'],
}
for modt, modlist in mods.items():
found = []
if modt not in bintf:
continue
for mod in modlist:
for intflist in bintf.values():
if mod in intflist:
found.append(mod)
intflist.remove(mod)
bintf[modt] += found
# -------- Fetch SysFS vals --------
bintflist = [intf for iflist in bintf.values() for intf in iflist]
result.update(__salt__['sysfs.read'](bintflist, path))
# -------- Parse through well known string lists --------
for strlist in ('writeback_rate_debug', 'internal/bset_tree_stats', 'priority_stats'):
if strlist in result:
listres = {}
for line in result[strlist].split('\n'):
key, val = line.split(':', 1)
val = val.strip()
try:
val = int(val)
except Exception:
try:
val = float(val)
except Exception:
pass
listres[key.strip()] = val
result[strlist] = listres
# -------- Parse through selection lists --------
if not options:
for sellist in ('cache_mode', 'cache_replacement_policy', 'errors'):
if sellist in result:
result[sellist] = re.search(r'\[(.+)\]', result[sellist]).groups()[0]
# -------- Parse through well known bools --------
for boolkey in ('running', 'writeback_running', 'congested'):
if boolkey in result:
result[boolkey] = bool(result[boolkey])
# -------- Recategorize results --------
bresult = {}
for iftype, intflist in bintf.items():
ifres = {}
for intf in intflist:
if intf in result:
ifres[intf] = result.pop(intf)
if ifres:
bresult[iftype] = ifres
return bresult
def _size_map(size):
'''
Map Bcache's size strings to real bytes
'''
try:
# I know, I know, EAFP.
# But everything else is reason for None
if not isinstance(size, int):
if re.search(r'[Kk]', size):
size = 1024 * float(re.sub(r'[Kk]', '', size))
elif re.search(r'[Mm]', size):
size = 1024**2 * float(re.sub(r'[Mm]', '', size))
size = int(size)
return size
except Exception:
return None
def _sizes(dev):
'''
Return neigh useless sizing info about a blockdev
:return: (total size in blocks, blocksize, maximum discard size in bytes)
'''
dev = _devbase(dev)
# standarization yay
block_sizes = ('hw_sector_size', 'minimum_io_size', 'physical_block_size', 'logical_block_size')
discard_sizes = ('discard_max_bytes', 'discard_max_hw_bytes', )
sysfs = __salt__['sysfs.read'](
('size',
'queue/hw_sector_size', '../queue/hw_sector_size',
'queue/discard_max_bytes', '../queue/discard_max_bytes'),
root=_syspath(dev))
# TODO: makes no sense
# First of all, it has to be a power of 2
# Secondly, this returns 4GiB - 512b on Intel 3500's for some weird reason
# discard_granularity seems in bytes, resolves to 512b ???
# max_hw_sectors_kb???
# There's also discard_max_hw_bytes more recently
# See: https://www.kernel.org/doc/Documentation/block/queue-sysfs.txt
# Also, I cant find any docs yet regarding bucket sizes;
# it's supposed to be discard_max_hw_bytes,
# but no way to figure that one reliably out apparently
discard = sysfs.get('queue/discard_max_bytes', sysfs.get('../queue/discard_max_bytes', None))
block = sysfs.get('queue/hw_sector_size', sysfs.get('../queue/hw_sector_size', None))
return 512*sysfs['size'], block, discard
def _wipe(dev):
'''
REALLY DESTRUCTIVE STUFF RIGHT AHEAD
'''
endres = 0
dev = _devbase(dev)
size, block, discard = _sizes(dev)
if discard is None:
log.error('Unable to read SysFS props for %s', dev)
return None
elif not discard:
log.warning('%s seems unable to discard', dev)
wiper = 'dd'
elif not HAS_BLKDISCARD:
log.warning('blkdiscard binary not available, properly wipe the dev manually for optimal results')
wiper = 'dd'
else:
wiper = 'blkdiscard'
wipe_failmsg = 'Error wiping {0}: %s'.format(dev)
if wiper == 'dd':
blocks = 4
cmd = 'dd if=/dev/zero of=/dev/{0} bs=1M count={1}'.format(dev, blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# Some stuff (<cough>GPT</cough>) writes stuff at the end of a dev as well
cmd += ' seek={0}'.format((size/1024**2) - blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
elif wiper == 'blkdiscard':
cmd = 'blkdiscard /dev/{0}'.format(dev)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# TODO: fix annoying bug failing blkdiscard by trying to discard 1 sector past blkdev
endres = 1
return endres > 0
def _wait(lfunc, log_lvl=None, log_msg=None, tries=10):
'''
Wait for lfunc to be True
:return: True if lfunc succeeded within tries, False if it didn't
'''
i = 0
while i < tries:
time.sleep(1)
if lfunc():
return True
else:
i += 1
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg)
return False
def _run_all(cmd, log_lvl=None, log_msg=None, exitcode=0):
'''
Simple wrapper around cmd.run_all
log_msg can contain {0} for stderr
:return: True or stdout, False if retcode wasn't exitcode
'''
res = __salt__['cmd.run_all'](cmd)
if res['retcode'] == exitcode:
if res['stdout']:
return res['stdout']
else:
return True
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg, res['stderr'])
return False
def _alltrue(resdict):
if resdict is None:
return True
return len([val for val in resdict.values() if val]) > 0
|
saltstack/salt
|
salt/modules/bcache.py
|
_devbase
|
python
|
def _devbase(dev):
'''
Basename of just about any dev
'''
dev = os.path.realpath(os.path.expandvars(dev))
dev = os.path.basename(dev)
return dev
|
Basename of just about any dev
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bcache.py#L624-L630
| null |
# -*- coding: utf-8 -*-
'''
Module for managing BCache sets
BCache is a block-level caching mechanism similar to ZFS L2ARC/ZIL, dm-cache and fscache.
It works by formatting one block device as a cache set, then adding backend devices
(which need to be formatted as such) to the set and activating them.
It's available in Linux mainline kernel since 3.10
https://www.kernel.org/doc/Documentation/bcache.txt
This module needs the bcache userspace tools to function.
.. versionadded: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import time
import re
from salt.ext import six
# Import salt libs
import salt.utils.path
log = logging.getLogger(__name__)
LOG = {
'trace': logging.TRACE,
'debug': logging.DEBUG,
'info': logging.INFO,
'warn': logging.WARNING,
'error': logging.ERROR,
'crit': logging.CRITICAL,
}
__func_alias__ = {
'attach_': 'attach',
'config_': 'config',
'super_': 'super',
}
HAS_BLKDISCARD = salt.utils.path.which('blkdiscard') is not None
def __virtual__():
'''
Only work when make-bcache is installed
'''
return salt.utils.path.which('make-bcache') is not None
def uuid(dev=None):
'''
Return the bcache UUID of a block device.
If no device is given, the Cache UUID is returned.
CLI example:
.. code-block:: bash
salt '*' bcache.uuid
salt '*' bcache.uuid /dev/sda
salt '*' bcache.uuid bcache0
'''
try:
if dev is None:
# take the only directory in /sys/fs/bcache and return it's basename
return list(salt.utils.path.os_walk('/sys/fs/bcache/'))[0][1][0]
else:
# basename of the /sys/block/{dev}/bcache/cache symlink target
return os.path.basename(_bcsys(dev, 'cache'))
except Exception:
return False
def attach_(dev=None):
'''
Attach a backing devices to a cache set
If no dev is given, all backing devices will be attached.
CLI example:
.. code-block:: bash
salt '*' bcache.attach sdc
salt '*' bcache.attach /dev/bcache1
:return: bool or None if nuttin' happened
'''
cache = uuid()
if not cache:
log.error('No cache to attach %s to', dev)
return False
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = attach_(dev)
return res if res else None
bcache = uuid(dev)
if bcache:
if bcache == cache:
log.info('%s is already attached to bcache %s, doing nothing', dev, cache)
return None
elif not detach(dev):
return False
log.debug('Attaching %s to bcache %s', dev, cache)
if not _bcsys(dev, 'attach', cache,
'error', 'Error attaching {0} to bcache {1}'.format(dev, cache)):
return False
return _wait(lambda: uuid(dev) == cache,
'error', '{0} received attach to bcache {1}, but did not comply'.format(dev, cache))
def detach(dev=None):
'''
Detach a backing device(s) from a cache set
If no dev is given, all backing devices will be attached.
Detaching a backing device will flush it's write cache.
This should leave the underlying device in a consistent state, but might take a while.
CLI example:
.. code-block:: bash
salt '*' bcache.detach sdc
salt '*' bcache.detach bcache1
'''
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = detach(dev)
return res if res else None
log.debug('Detaching %s', dev)
if not _bcsys(dev, 'detach', 'goaway', 'error', 'Error detaching {0}'.format(dev)):
return False
return _wait(lambda: uuid(dev) is False, 'error', '{0} received detach, but did not comply'.format(dev), 300)
def start():
'''
Trigger a start of the full bcache system through udev.
CLI example:
.. code-block:: bash
salt '*' bcache.start
'''
if not _run_all('udevadm trigger', 'error', 'Error starting bcache: %s'):
return False
elif not _wait(lambda: uuid() is not False, 'warn', 'Bcache system started, but no active cache set found.'):
return False
return True
def stop(dev=None):
'''
Stop a bcache device
If no device is given, all backing devices will be detached from the cache, which will subsequently be stopped.
.. warning::
'Stop' on an individual backing device means hard-stop;
no attempt at flushing will be done and the bcache device will seemingly 'disappear' from the device lists
CLI example:
.. code-block:: bash
salt '*' bcache.stop
'''
if dev is not None:
log.warning('Stopping %s, device will only reappear after reregistering!', dev)
if not _bcsys(dev, 'stop', 'goaway', 'error', 'Error stopping {0}'.format(dev)):
return False
return _wait(lambda: _sysfs_attr(_bcpath(dev)) is False, 'error', 'Device {0} did not stop'.format(dev), 300)
else:
cache = uuid()
if not cache:
log.warning('bcache already stopped?')
return None
if not _alltrue(detach()):
return False
elif not _fssys('stop', 'goaway', 'error', 'Error stopping cache'):
return False
return _wait(lambda: uuid() is False, 'error', 'Cache did not stop', 300)
def back_make(dev, cache_mode='writeback', force=False, attach=True, bucket_size=None):
'''
Create a backing device for attachment to a set.
Because the block size must be the same, a cache set already needs to exist.
CLI example:
.. code-block:: bash
salt '*' bcache.back_make sdc cache_mode=writeback attach=True
:param cache_mode: writethrough, writeback, writearound or none.
:param force: Overwrite existing bcaches
:param attach: Immediately attach the backing device to the set
:param bucket_size: Size of a bucket (see kernel doc)
'''
# pylint: disable=too-many-return-statements
cache = uuid()
if not cache:
log.error('No bcache set found')
return False
elif _sysfs_attr(_bcpath(dev)):
if not force:
log.error('%s already contains a bcache. Wipe it manually or use force', dev)
return False
elif uuid(dev) and not detach(dev):
return False
elif not stop(dev):
return False
dev = _devpath(dev)
block_size = _size_map(_fssys('block_size'))
# You might want to override, we pick the cache set's as sane default
if bucket_size is None:
bucket_size = _size_map(_fssys('bucket_size'))
cmd = 'make-bcache --block {0} --bucket {1} --{2} --bdev {3}'.format(block_size, bucket_size, cache_mode, dev)
if force:
cmd += ' --wipe-bcache'
if not _run_all(cmd, 'error', 'Error creating backing device {0}: %s'.format(dev)):
return False
elif not _sysfs_attr('fs/bcache/register', _devpath(dev),
'error', 'Error registering backing device {0}'.format(dev)):
return False
elif not _wait(lambda: _sysfs_attr(_bcpath(dev)) is not False,
'error', 'Backing device {0} did not register'.format(dev)):
return False
elif attach:
return attach_(dev)
return True
def cache_make(dev, reserved=None, force=False, block_size=None, bucket_size=None, attach=True):
'''
Create BCache cache on a block device.
If blkdiscard is available the entire device will be properly cleared in advance.
CLI example:
.. code-block:: bash
salt '*' bcache.cache_make sdb reserved=10% block_size=4096
:param reserved: if dev is a full device, create a partition table with this size empty.
.. note::
this increases the amount of reserved space available to SSD garbage collectors,
potentially (vastly) increasing performance
:param block_size: Block size of the cache; defaults to devices' logical block size
:param force: Overwrite existing BCache sets
:param attach: Attach all existing backend devices immediately
'''
# TODO: multiple devs == md jbod
# pylint: disable=too-many-return-statements
# ---------------- Preflight checks ----------------
cache = uuid()
if cache:
if not force:
log.error('BCache cache %s is already on the system', cache)
return False
cache = _bdev()
dev = _devbase(dev)
udev = __salt__['udev.env'](dev)
if ('ID_FS_TYPE' in udev or (udev.get('DEVTYPE', None) != 'partition' and 'ID_PART_TABLE_TYPE' in udev)) \
and not force:
log.error('%s already contains data, wipe first or force', dev)
return False
elif reserved is not None and udev.get('DEVTYPE', None) != 'disk':
log.error('Need a partitionable blockdev for reserved to work')
return False
_, block, bucket = _sizes(dev)
if bucket_size is None:
bucket_size = bucket
# TODO: bucket from _sizes() makes no sense
bucket_size = False
if block_size is None:
block_size = block
# ---------------- Still here, start doing destructive stuff ----------------
if cache:
if not stop():
return False
# Wipe the current cache device as well,
# forever ruining any chance of it accidentally popping up again
elif not _wipe(cache):
return False
# Can't do enough wiping
if not _wipe(dev):
return False
if reserved:
cmd = 'parted -m -s -a optimal -- ' \
'/dev/{0} mklabel gpt mkpart bcache-reserved 1M {1} mkpart bcache {1} 100%'.format(dev, reserved)
# if wipe was incomplete & part layout remains the same,
# this is one condition set where udev would make it accidentally popup again
if not _run_all(cmd, 'error', 'Error creating bcache partitions on {0}: %s'.format(dev)):
return False
dev = '{0}2'.format(dev)
# ---------------- Finally, create a cache ----------------
cmd = 'make-bcache --cache /dev/{0} --block {1} --wipe-bcache'.format(dev, block_size)
# Actually bucket_size should always have a value, but for testing 0 is possible as well
if bucket_size:
cmd += ' --bucket {0}'.format(bucket_size)
if not _run_all(cmd, 'error', 'Error creating cache {0}: %s'.format(dev)):
return False
elif not _wait(lambda: uuid() is not False,
'error', 'Cache {0} seemingly created OK, but FS did not activate'.format(dev)):
return False
if attach:
return _alltrue(attach_())
else:
return True
def config_(dev=None, **kwargs):
'''
Show or update config of a bcache device.
If no device is given, operate on the cache set itself.
CLI example:
.. code-block:: bash
salt '*' bcache.config
salt '*' bcache.config bcache1
salt '*' bcache.config errors=panic journal_delay_ms=150
salt '*' bcache.config bcache1 cache_mode=writeback writeback_percent=15
:return: config or True/False
'''
if dev is None:
spath = _fspath()
else:
spath = _bcpath(dev)
# filter out 'hidden' kwargs added by our favourite orchestration system
updates = dict([(key, val) for key, val in kwargs.items() if not key.startswith('__')])
if updates:
endres = 0
for key, val in updates.items():
endres += _sysfs_attr([spath, key], val,
'warn', 'Failed to update {0} with {1}'.format(os.path.join(spath, key), val))
return endres > 0
else:
result = {}
data = _sysfs_parse(spath, config=True, internals=True, options=True)
for key in ('other_ro', 'inter_ro'):
if key in data:
del data[key]
for key in data:
result.update(data[key])
return result
def status(stats=False, config=False, internals=False, superblock=False, alldevs=False):
'''
Show the full status of the BCache system and optionally all it's involved devices
CLI example:
.. code-block:: bash
salt '*' bcache.status
salt '*' bcache.status stats=True
salt '*' bcache.status internals=True alldevs=True
:param stats: include statistics
:param config: include settings
:param internals: include internals
:param superblock: include superblock
'''
bdevs = []
for _, links, _ in salt.utils.path.os_walk('/sys/block/'):
for block in links:
if 'bcache' in block:
continue
for spath, sdirs, _ in salt.utils.path.os_walk('/sys/block/{0}'.format(block), followlinks=False):
if 'bcache' in sdirs:
bdevs.append(os.path.basename(spath))
statii = {}
for bcache in bdevs:
statii[bcache] = device(bcache, stats, config, internals, superblock)
cuuid = uuid()
cdev = _bdev()
if cdev:
count = 0
for dev in statii:
if dev != cdev:
# it's a backing dev
if statii[dev]['cache'] == cuuid:
count += 1
statii[cdev]['attached_backing_devices'] = count
if not alldevs:
statii = statii[cdev]
return statii
def device(dev, stats=False, config=False, internals=False, superblock=False):
'''
Check the state of a single bcache device
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc stats=True
:param stats: include statistics
:param settings: include all settings
:param internals: include all internals
:param superblock: include superblock info
'''
result = {}
if not _sysfs_attr(_bcpath(dev), None, 'error', '{0} is not a bcache fo any kind'.format(dev)):
return False
elif _bcsys(dev, 'set'):
# ---------------- It's the cache itself ----------------
result['uuid'] = uuid()
base_attr = ['block_size', 'bucket_size', 'cache_available_percent', 'cache_replacement_policy', 'congested']
# ---------------- Parse through both the blockdev & the FS ----------------
result.update(_sysfs_parse(_bcpath(dev), base_attr, stats, config, internals))
result.update(_sysfs_parse(_fspath(), base_attr, stats, config, internals))
result.update(result.pop('base'))
else:
# ---------------- It's a backing device ----------------
back_uuid = uuid(dev)
if back_uuid is not None:
result['cache'] = back_uuid
try:
result['dev'] = os.path.basename(_bcsys(dev, 'dev'))
except Exception:
pass
result['bdev'] = _bdev(dev)
base_attr = ['cache_mode', 'running', 'state', 'writeback_running']
base_path = _bcpath(dev)
result.update(_sysfs_parse(base_path, base_attr, stats, config, internals))
result.update(result.pop('base'))
# ---------------- Modifications ----------------
state = [result['state']]
if result.pop('running'):
state.append('running')
else:
state.append('stopped')
if 'writeback_running' in result:
if result.pop('writeback_running'):
state.append('writeback_running')
else:
state.append('writeback_stopped')
result['state'] = state
# ---------------- Statistics ----------------
if 'stats' in result:
replre = r'(stats|cache)_'
statres = result['stats']
for attr in result['stats']:
if '/' not in attr:
key = re.sub(replre, '', attr)
statres[key] = statres.pop(attr)
else:
stat, key = attr.split('/', 1)
stat = re.sub(replre, '', stat)
key = re.sub(replre, '', key)
if stat not in statres:
statres[stat] = {}
statres[stat][key] = statres.pop(attr)
result['stats'] = statres
# ---------------- Internals ----------------
if internals:
interres = result.pop('inter_ro', {})
interres.update(result.pop('inter_rw', {}))
if interres:
for key in interres:
if key.startswith('internal'):
nkey = re.sub(r'internal[s/]*', '', key)
interres[nkey] = interres.pop(key)
key = nkey
if key.startswith(('btree', 'writeback')):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in interres:
interres[mkey] = {}
interres[mkey][skey] = interres.pop(key)
result['internals'] = interres
# ---------------- Config ----------------
if config:
configres = result['config']
for key in configres:
if key.startswith('writeback'):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in configres:
configres[mkey] = {}
configres[mkey][skey] = configres.pop(key)
result['config'] = configres
# ---------------- Superblock ----------------
if superblock:
result['superblock'] = super_(dev)
return result
def super_(dev):
'''
Read out BCache SuperBlock
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc
'''
dev = _devpath(dev)
ret = {}
res = _run_all('bcache-super-show {0}'.format(dev), 'error', 'Error reading superblock on {0}: %s'.format(dev))
if not res:
return False
for line in res.splitlines(): # pylint: disable=no-member
line = line.strip()
if not line:
continue
key, val = [val.strip() for val in re.split(r'[\s]+', line, maxsplit=1)]
if not (key and val):
continue
mval = None
if ' ' in val:
rval, mval = [val.strip() for val in re.split(r'[\s]+', val, maxsplit=1)]
mval = mval[1:-1]
else:
rval = val
try:
rval = int(rval)
except Exception:
try:
rval = float(rval)
except Exception:
if rval == 'yes':
rval = True
elif rval == 'no':
rval = False
pkey, key = re.split(r'\.', key, maxsplit=1)
if pkey not in ret:
ret[pkey] = {}
if mval is not None:
ret[pkey][key] = (rval, mval)
else:
ret[pkey][key] = rval
return ret
# -------------------------------- HELPER FUNCTIONS --------------------------------
def _devpath(dev):
'''
Return /dev name of just about any dev
:return: /dev/devicename
'''
return os.path.join('/dev', _devbase(dev))
def _syspath(dev):
'''
Full SysFS path of a device
'''
dev = _devbase(dev)
dev = re.sub(r'^([vhs][a-z]+)([0-9]+)', r'\1/\1\2', dev)
# name = re.sub(r'^([a-z]+)(?<!(bcache|md|dm))([0-9]+)', r'\1/\1\2', name)
return os.path.join('/sys/block/', dev)
def _bdev(dev=None):
'''
Resolve a bcacheX or cache to a real dev
:return: basename of bcache dev
'''
if dev is None:
dev = _fssys('cache0')
else:
dev = _bcpath(dev)
if not dev:
return False
else:
return _devbase(os.path.dirname(dev))
def _bcpath(dev):
'''
Full SysFS path of a bcache device
'''
return os.path.join(_syspath(dev), 'bcache')
def _fspath():
'''
:return: path of active bcache
'''
cuuid = uuid()
if not cuuid:
return False
else:
return os.path.join('/sys/fs/bcache/', cuuid)
def _fssys(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with bcache SysFS
'''
fspath = _fspath()
if not fspath:
return False
else:
return _sysfs_attr([fspath, name], value, log_lvl, log_msg)
def _bcsys(dev, name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with backing devs SysFS
'''
return _sysfs_attr([_bcpath(dev), name], value, log_lvl, log_msg)
def _sysfs_attr(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper with logging around sysfs.attr
'''
if isinstance(name, six.string_types):
name = [name]
res = __salt__['sysfs.attr'](os.path.join(*name), value)
if not res and log_lvl is not None and log_msg is not None:
log.log(LOG[log_lvl], log_msg)
return res
def _sysfs_parse(path, base_attr=None, stats=False, config=False, internals=False, options=False):
'''
Helper function for parsing BCache's SysFS interface
'''
result = {}
# ---------------- Parse through the interfaces list ----------------
intfs = __salt__['sysfs.interfaces'](path)
# Actions, we ignore
del intfs['w']
# -------- Sorting hat --------
binkeys = []
if internals:
binkeys.extend(['inter_ro', 'inter_rw'])
if config:
binkeys.append('config')
if stats:
binkeys.append('stats')
bintf = {}
for key in binkeys:
bintf[key] = []
for intf in intfs['r']:
if intf.startswith('internal'):
key = 'inter_ro'
elif 'stats' in intf:
key = 'stats'
else:
# What to do with these???
# I'll utilize 'inter_ro' as 'misc' as well
key = 'inter_ro'
if key in bintf:
bintf[key].append(intf)
for intf in intfs['rw']:
if intf.startswith('internal'):
key = 'inter_rw'
else:
key = 'config'
if key in bintf:
bintf[key].append(intf)
if base_attr is not None:
for intf in bintf:
bintf[intf] = [sintf for sintf in bintf[intf] if sintf not in base_attr]
bintf['base'] = base_attr
mods = {
'stats': ['internal/bset_tree_stats', 'writeback_rate_debug', 'metadata_written', 'nbuckets', 'written',
'average_key_size', 'btree_cache_size'],
}
for modt, modlist in mods.items():
found = []
if modt not in bintf:
continue
for mod in modlist:
for intflist in bintf.values():
if mod in intflist:
found.append(mod)
intflist.remove(mod)
bintf[modt] += found
# -------- Fetch SysFS vals --------
bintflist = [intf for iflist in bintf.values() for intf in iflist]
result.update(__salt__['sysfs.read'](bintflist, path))
# -------- Parse through well known string lists --------
for strlist in ('writeback_rate_debug', 'internal/bset_tree_stats', 'priority_stats'):
if strlist in result:
listres = {}
for line in result[strlist].split('\n'):
key, val = line.split(':', 1)
val = val.strip()
try:
val = int(val)
except Exception:
try:
val = float(val)
except Exception:
pass
listres[key.strip()] = val
result[strlist] = listres
# -------- Parse through selection lists --------
if not options:
for sellist in ('cache_mode', 'cache_replacement_policy', 'errors'):
if sellist in result:
result[sellist] = re.search(r'\[(.+)\]', result[sellist]).groups()[0]
# -------- Parse through well known bools --------
for boolkey in ('running', 'writeback_running', 'congested'):
if boolkey in result:
result[boolkey] = bool(result[boolkey])
# -------- Recategorize results --------
bresult = {}
for iftype, intflist in bintf.items():
ifres = {}
for intf in intflist:
if intf in result:
ifres[intf] = result.pop(intf)
if ifres:
bresult[iftype] = ifres
return bresult
def _size_map(size):
'''
Map Bcache's size strings to real bytes
'''
try:
# I know, I know, EAFP.
# But everything else is reason for None
if not isinstance(size, int):
if re.search(r'[Kk]', size):
size = 1024 * float(re.sub(r'[Kk]', '', size))
elif re.search(r'[Mm]', size):
size = 1024**2 * float(re.sub(r'[Mm]', '', size))
size = int(size)
return size
except Exception:
return None
def _sizes(dev):
'''
Return neigh useless sizing info about a blockdev
:return: (total size in blocks, blocksize, maximum discard size in bytes)
'''
dev = _devbase(dev)
# standarization yay
block_sizes = ('hw_sector_size', 'minimum_io_size', 'physical_block_size', 'logical_block_size')
discard_sizes = ('discard_max_bytes', 'discard_max_hw_bytes', )
sysfs = __salt__['sysfs.read'](
('size',
'queue/hw_sector_size', '../queue/hw_sector_size',
'queue/discard_max_bytes', '../queue/discard_max_bytes'),
root=_syspath(dev))
# TODO: makes no sense
# First of all, it has to be a power of 2
# Secondly, this returns 4GiB - 512b on Intel 3500's for some weird reason
# discard_granularity seems in bytes, resolves to 512b ???
# max_hw_sectors_kb???
# There's also discard_max_hw_bytes more recently
# See: https://www.kernel.org/doc/Documentation/block/queue-sysfs.txt
# Also, I cant find any docs yet regarding bucket sizes;
# it's supposed to be discard_max_hw_bytes,
# but no way to figure that one reliably out apparently
discard = sysfs.get('queue/discard_max_bytes', sysfs.get('../queue/discard_max_bytes', None))
block = sysfs.get('queue/hw_sector_size', sysfs.get('../queue/hw_sector_size', None))
return 512*sysfs['size'], block, discard
def _wipe(dev):
'''
REALLY DESTRUCTIVE STUFF RIGHT AHEAD
'''
endres = 0
dev = _devbase(dev)
size, block, discard = _sizes(dev)
if discard is None:
log.error('Unable to read SysFS props for %s', dev)
return None
elif not discard:
log.warning('%s seems unable to discard', dev)
wiper = 'dd'
elif not HAS_BLKDISCARD:
log.warning('blkdiscard binary not available, properly wipe the dev manually for optimal results')
wiper = 'dd'
else:
wiper = 'blkdiscard'
wipe_failmsg = 'Error wiping {0}: %s'.format(dev)
if wiper == 'dd':
blocks = 4
cmd = 'dd if=/dev/zero of=/dev/{0} bs=1M count={1}'.format(dev, blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# Some stuff (<cough>GPT</cough>) writes stuff at the end of a dev as well
cmd += ' seek={0}'.format((size/1024**2) - blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
elif wiper == 'blkdiscard':
cmd = 'blkdiscard /dev/{0}'.format(dev)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# TODO: fix annoying bug failing blkdiscard by trying to discard 1 sector past blkdev
endres = 1
return endres > 0
def _wait(lfunc, log_lvl=None, log_msg=None, tries=10):
'''
Wait for lfunc to be True
:return: True if lfunc succeeded within tries, False if it didn't
'''
i = 0
while i < tries:
time.sleep(1)
if lfunc():
return True
else:
i += 1
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg)
return False
def _run_all(cmd, log_lvl=None, log_msg=None, exitcode=0):
'''
Simple wrapper around cmd.run_all
log_msg can contain {0} for stderr
:return: True or stdout, False if retcode wasn't exitcode
'''
res = __salt__['cmd.run_all'](cmd)
if res['retcode'] == exitcode:
if res['stdout']:
return res['stdout']
else:
return True
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg, res['stderr'])
return False
def _alltrue(resdict):
if resdict is None:
return True
return len([val for val in resdict.values() if val]) > 0
|
saltstack/salt
|
salt/modules/bcache.py
|
_syspath
|
python
|
def _syspath(dev):
'''
Full SysFS path of a device
'''
dev = _devbase(dev)
dev = re.sub(r'^([vhs][a-z]+)([0-9]+)', r'\1/\1\2', dev)
# name = re.sub(r'^([a-z]+)(?<!(bcache|md|dm))([0-9]+)', r'\1/\1\2', name)
return os.path.join('/sys/block/', dev)
|
Full SysFS path of a device
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bcache.py#L641-L649
|
[
"def _devbase(dev):\n '''\n Basename of just about any dev\n '''\n dev = os.path.realpath(os.path.expandvars(dev))\n dev = os.path.basename(dev)\n return dev\n"
] |
# -*- coding: utf-8 -*-
'''
Module for managing BCache sets
BCache is a block-level caching mechanism similar to ZFS L2ARC/ZIL, dm-cache and fscache.
It works by formatting one block device as a cache set, then adding backend devices
(which need to be formatted as such) to the set and activating them.
It's available in Linux mainline kernel since 3.10
https://www.kernel.org/doc/Documentation/bcache.txt
This module needs the bcache userspace tools to function.
.. versionadded: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import time
import re
from salt.ext import six
# Import salt libs
import salt.utils.path
log = logging.getLogger(__name__)
LOG = {
'trace': logging.TRACE,
'debug': logging.DEBUG,
'info': logging.INFO,
'warn': logging.WARNING,
'error': logging.ERROR,
'crit': logging.CRITICAL,
}
__func_alias__ = {
'attach_': 'attach',
'config_': 'config',
'super_': 'super',
}
HAS_BLKDISCARD = salt.utils.path.which('blkdiscard') is not None
def __virtual__():
'''
Only work when make-bcache is installed
'''
return salt.utils.path.which('make-bcache') is not None
def uuid(dev=None):
'''
Return the bcache UUID of a block device.
If no device is given, the Cache UUID is returned.
CLI example:
.. code-block:: bash
salt '*' bcache.uuid
salt '*' bcache.uuid /dev/sda
salt '*' bcache.uuid bcache0
'''
try:
if dev is None:
# take the only directory in /sys/fs/bcache and return it's basename
return list(salt.utils.path.os_walk('/sys/fs/bcache/'))[0][1][0]
else:
# basename of the /sys/block/{dev}/bcache/cache symlink target
return os.path.basename(_bcsys(dev, 'cache'))
except Exception:
return False
def attach_(dev=None):
'''
Attach a backing devices to a cache set
If no dev is given, all backing devices will be attached.
CLI example:
.. code-block:: bash
salt '*' bcache.attach sdc
salt '*' bcache.attach /dev/bcache1
:return: bool or None if nuttin' happened
'''
cache = uuid()
if not cache:
log.error('No cache to attach %s to', dev)
return False
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = attach_(dev)
return res if res else None
bcache = uuid(dev)
if bcache:
if bcache == cache:
log.info('%s is already attached to bcache %s, doing nothing', dev, cache)
return None
elif not detach(dev):
return False
log.debug('Attaching %s to bcache %s', dev, cache)
if not _bcsys(dev, 'attach', cache,
'error', 'Error attaching {0} to bcache {1}'.format(dev, cache)):
return False
return _wait(lambda: uuid(dev) == cache,
'error', '{0} received attach to bcache {1}, but did not comply'.format(dev, cache))
def detach(dev=None):
'''
Detach a backing device(s) from a cache set
If no dev is given, all backing devices will be attached.
Detaching a backing device will flush it's write cache.
This should leave the underlying device in a consistent state, but might take a while.
CLI example:
.. code-block:: bash
salt '*' bcache.detach sdc
salt '*' bcache.detach bcache1
'''
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = detach(dev)
return res if res else None
log.debug('Detaching %s', dev)
if not _bcsys(dev, 'detach', 'goaway', 'error', 'Error detaching {0}'.format(dev)):
return False
return _wait(lambda: uuid(dev) is False, 'error', '{0} received detach, but did not comply'.format(dev), 300)
def start():
'''
Trigger a start of the full bcache system through udev.
CLI example:
.. code-block:: bash
salt '*' bcache.start
'''
if not _run_all('udevadm trigger', 'error', 'Error starting bcache: %s'):
return False
elif not _wait(lambda: uuid() is not False, 'warn', 'Bcache system started, but no active cache set found.'):
return False
return True
def stop(dev=None):
'''
Stop a bcache device
If no device is given, all backing devices will be detached from the cache, which will subsequently be stopped.
.. warning::
'Stop' on an individual backing device means hard-stop;
no attempt at flushing will be done and the bcache device will seemingly 'disappear' from the device lists
CLI example:
.. code-block:: bash
salt '*' bcache.stop
'''
if dev is not None:
log.warning('Stopping %s, device will only reappear after reregistering!', dev)
if not _bcsys(dev, 'stop', 'goaway', 'error', 'Error stopping {0}'.format(dev)):
return False
return _wait(lambda: _sysfs_attr(_bcpath(dev)) is False, 'error', 'Device {0} did not stop'.format(dev), 300)
else:
cache = uuid()
if not cache:
log.warning('bcache already stopped?')
return None
if not _alltrue(detach()):
return False
elif not _fssys('stop', 'goaway', 'error', 'Error stopping cache'):
return False
return _wait(lambda: uuid() is False, 'error', 'Cache did not stop', 300)
def back_make(dev, cache_mode='writeback', force=False, attach=True, bucket_size=None):
'''
Create a backing device for attachment to a set.
Because the block size must be the same, a cache set already needs to exist.
CLI example:
.. code-block:: bash
salt '*' bcache.back_make sdc cache_mode=writeback attach=True
:param cache_mode: writethrough, writeback, writearound or none.
:param force: Overwrite existing bcaches
:param attach: Immediately attach the backing device to the set
:param bucket_size: Size of a bucket (see kernel doc)
'''
# pylint: disable=too-many-return-statements
cache = uuid()
if not cache:
log.error('No bcache set found')
return False
elif _sysfs_attr(_bcpath(dev)):
if not force:
log.error('%s already contains a bcache. Wipe it manually or use force', dev)
return False
elif uuid(dev) and not detach(dev):
return False
elif not stop(dev):
return False
dev = _devpath(dev)
block_size = _size_map(_fssys('block_size'))
# You might want to override, we pick the cache set's as sane default
if bucket_size is None:
bucket_size = _size_map(_fssys('bucket_size'))
cmd = 'make-bcache --block {0} --bucket {1} --{2} --bdev {3}'.format(block_size, bucket_size, cache_mode, dev)
if force:
cmd += ' --wipe-bcache'
if not _run_all(cmd, 'error', 'Error creating backing device {0}: %s'.format(dev)):
return False
elif not _sysfs_attr('fs/bcache/register', _devpath(dev),
'error', 'Error registering backing device {0}'.format(dev)):
return False
elif not _wait(lambda: _sysfs_attr(_bcpath(dev)) is not False,
'error', 'Backing device {0} did not register'.format(dev)):
return False
elif attach:
return attach_(dev)
return True
def cache_make(dev, reserved=None, force=False, block_size=None, bucket_size=None, attach=True):
'''
Create BCache cache on a block device.
If blkdiscard is available the entire device will be properly cleared in advance.
CLI example:
.. code-block:: bash
salt '*' bcache.cache_make sdb reserved=10% block_size=4096
:param reserved: if dev is a full device, create a partition table with this size empty.
.. note::
this increases the amount of reserved space available to SSD garbage collectors,
potentially (vastly) increasing performance
:param block_size: Block size of the cache; defaults to devices' logical block size
:param force: Overwrite existing BCache sets
:param attach: Attach all existing backend devices immediately
'''
# TODO: multiple devs == md jbod
# pylint: disable=too-many-return-statements
# ---------------- Preflight checks ----------------
cache = uuid()
if cache:
if not force:
log.error('BCache cache %s is already on the system', cache)
return False
cache = _bdev()
dev = _devbase(dev)
udev = __salt__['udev.env'](dev)
if ('ID_FS_TYPE' in udev or (udev.get('DEVTYPE', None) != 'partition' and 'ID_PART_TABLE_TYPE' in udev)) \
and not force:
log.error('%s already contains data, wipe first or force', dev)
return False
elif reserved is not None and udev.get('DEVTYPE', None) != 'disk':
log.error('Need a partitionable blockdev for reserved to work')
return False
_, block, bucket = _sizes(dev)
if bucket_size is None:
bucket_size = bucket
# TODO: bucket from _sizes() makes no sense
bucket_size = False
if block_size is None:
block_size = block
# ---------------- Still here, start doing destructive stuff ----------------
if cache:
if not stop():
return False
# Wipe the current cache device as well,
# forever ruining any chance of it accidentally popping up again
elif not _wipe(cache):
return False
# Can't do enough wiping
if not _wipe(dev):
return False
if reserved:
cmd = 'parted -m -s -a optimal -- ' \
'/dev/{0} mklabel gpt mkpart bcache-reserved 1M {1} mkpart bcache {1} 100%'.format(dev, reserved)
# if wipe was incomplete & part layout remains the same,
# this is one condition set where udev would make it accidentally popup again
if not _run_all(cmd, 'error', 'Error creating bcache partitions on {0}: %s'.format(dev)):
return False
dev = '{0}2'.format(dev)
# ---------------- Finally, create a cache ----------------
cmd = 'make-bcache --cache /dev/{0} --block {1} --wipe-bcache'.format(dev, block_size)
# Actually bucket_size should always have a value, but for testing 0 is possible as well
if bucket_size:
cmd += ' --bucket {0}'.format(bucket_size)
if not _run_all(cmd, 'error', 'Error creating cache {0}: %s'.format(dev)):
return False
elif not _wait(lambda: uuid() is not False,
'error', 'Cache {0} seemingly created OK, but FS did not activate'.format(dev)):
return False
if attach:
return _alltrue(attach_())
else:
return True
def config_(dev=None, **kwargs):
'''
Show or update config of a bcache device.
If no device is given, operate on the cache set itself.
CLI example:
.. code-block:: bash
salt '*' bcache.config
salt '*' bcache.config bcache1
salt '*' bcache.config errors=panic journal_delay_ms=150
salt '*' bcache.config bcache1 cache_mode=writeback writeback_percent=15
:return: config or True/False
'''
if dev is None:
spath = _fspath()
else:
spath = _bcpath(dev)
# filter out 'hidden' kwargs added by our favourite orchestration system
updates = dict([(key, val) for key, val in kwargs.items() if not key.startswith('__')])
if updates:
endres = 0
for key, val in updates.items():
endres += _sysfs_attr([spath, key], val,
'warn', 'Failed to update {0} with {1}'.format(os.path.join(spath, key), val))
return endres > 0
else:
result = {}
data = _sysfs_parse(spath, config=True, internals=True, options=True)
for key in ('other_ro', 'inter_ro'):
if key in data:
del data[key]
for key in data:
result.update(data[key])
return result
def status(stats=False, config=False, internals=False, superblock=False, alldevs=False):
'''
Show the full status of the BCache system and optionally all it's involved devices
CLI example:
.. code-block:: bash
salt '*' bcache.status
salt '*' bcache.status stats=True
salt '*' bcache.status internals=True alldevs=True
:param stats: include statistics
:param config: include settings
:param internals: include internals
:param superblock: include superblock
'''
bdevs = []
for _, links, _ in salt.utils.path.os_walk('/sys/block/'):
for block in links:
if 'bcache' in block:
continue
for spath, sdirs, _ in salt.utils.path.os_walk('/sys/block/{0}'.format(block), followlinks=False):
if 'bcache' in sdirs:
bdevs.append(os.path.basename(spath))
statii = {}
for bcache in bdevs:
statii[bcache] = device(bcache, stats, config, internals, superblock)
cuuid = uuid()
cdev = _bdev()
if cdev:
count = 0
for dev in statii:
if dev != cdev:
# it's a backing dev
if statii[dev]['cache'] == cuuid:
count += 1
statii[cdev]['attached_backing_devices'] = count
if not alldevs:
statii = statii[cdev]
return statii
def device(dev, stats=False, config=False, internals=False, superblock=False):
'''
Check the state of a single bcache device
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc stats=True
:param stats: include statistics
:param settings: include all settings
:param internals: include all internals
:param superblock: include superblock info
'''
result = {}
if not _sysfs_attr(_bcpath(dev), None, 'error', '{0} is not a bcache fo any kind'.format(dev)):
return False
elif _bcsys(dev, 'set'):
# ---------------- It's the cache itself ----------------
result['uuid'] = uuid()
base_attr = ['block_size', 'bucket_size', 'cache_available_percent', 'cache_replacement_policy', 'congested']
# ---------------- Parse through both the blockdev & the FS ----------------
result.update(_sysfs_parse(_bcpath(dev), base_attr, stats, config, internals))
result.update(_sysfs_parse(_fspath(), base_attr, stats, config, internals))
result.update(result.pop('base'))
else:
# ---------------- It's a backing device ----------------
back_uuid = uuid(dev)
if back_uuid is not None:
result['cache'] = back_uuid
try:
result['dev'] = os.path.basename(_bcsys(dev, 'dev'))
except Exception:
pass
result['bdev'] = _bdev(dev)
base_attr = ['cache_mode', 'running', 'state', 'writeback_running']
base_path = _bcpath(dev)
result.update(_sysfs_parse(base_path, base_attr, stats, config, internals))
result.update(result.pop('base'))
# ---------------- Modifications ----------------
state = [result['state']]
if result.pop('running'):
state.append('running')
else:
state.append('stopped')
if 'writeback_running' in result:
if result.pop('writeback_running'):
state.append('writeback_running')
else:
state.append('writeback_stopped')
result['state'] = state
# ---------------- Statistics ----------------
if 'stats' in result:
replre = r'(stats|cache)_'
statres = result['stats']
for attr in result['stats']:
if '/' not in attr:
key = re.sub(replre, '', attr)
statres[key] = statres.pop(attr)
else:
stat, key = attr.split('/', 1)
stat = re.sub(replre, '', stat)
key = re.sub(replre, '', key)
if stat not in statres:
statres[stat] = {}
statres[stat][key] = statres.pop(attr)
result['stats'] = statres
# ---------------- Internals ----------------
if internals:
interres = result.pop('inter_ro', {})
interres.update(result.pop('inter_rw', {}))
if interres:
for key in interres:
if key.startswith('internal'):
nkey = re.sub(r'internal[s/]*', '', key)
interres[nkey] = interres.pop(key)
key = nkey
if key.startswith(('btree', 'writeback')):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in interres:
interres[mkey] = {}
interres[mkey][skey] = interres.pop(key)
result['internals'] = interres
# ---------------- Config ----------------
if config:
configres = result['config']
for key in configres:
if key.startswith('writeback'):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in configres:
configres[mkey] = {}
configres[mkey][skey] = configres.pop(key)
result['config'] = configres
# ---------------- Superblock ----------------
if superblock:
result['superblock'] = super_(dev)
return result
def super_(dev):
'''
Read out BCache SuperBlock
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc
'''
dev = _devpath(dev)
ret = {}
res = _run_all('bcache-super-show {0}'.format(dev), 'error', 'Error reading superblock on {0}: %s'.format(dev))
if not res:
return False
for line in res.splitlines(): # pylint: disable=no-member
line = line.strip()
if not line:
continue
key, val = [val.strip() for val in re.split(r'[\s]+', line, maxsplit=1)]
if not (key and val):
continue
mval = None
if ' ' in val:
rval, mval = [val.strip() for val in re.split(r'[\s]+', val, maxsplit=1)]
mval = mval[1:-1]
else:
rval = val
try:
rval = int(rval)
except Exception:
try:
rval = float(rval)
except Exception:
if rval == 'yes':
rval = True
elif rval == 'no':
rval = False
pkey, key = re.split(r'\.', key, maxsplit=1)
if pkey not in ret:
ret[pkey] = {}
if mval is not None:
ret[pkey][key] = (rval, mval)
else:
ret[pkey][key] = rval
return ret
# -------------------------------- HELPER FUNCTIONS --------------------------------
def _devbase(dev):
'''
Basename of just about any dev
'''
dev = os.path.realpath(os.path.expandvars(dev))
dev = os.path.basename(dev)
return dev
def _devpath(dev):
'''
Return /dev name of just about any dev
:return: /dev/devicename
'''
return os.path.join('/dev', _devbase(dev))
def _bdev(dev=None):
'''
Resolve a bcacheX or cache to a real dev
:return: basename of bcache dev
'''
if dev is None:
dev = _fssys('cache0')
else:
dev = _bcpath(dev)
if not dev:
return False
else:
return _devbase(os.path.dirname(dev))
def _bcpath(dev):
'''
Full SysFS path of a bcache device
'''
return os.path.join(_syspath(dev), 'bcache')
def _fspath():
'''
:return: path of active bcache
'''
cuuid = uuid()
if not cuuid:
return False
else:
return os.path.join('/sys/fs/bcache/', cuuid)
def _fssys(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with bcache SysFS
'''
fspath = _fspath()
if not fspath:
return False
else:
return _sysfs_attr([fspath, name], value, log_lvl, log_msg)
def _bcsys(dev, name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with backing devs SysFS
'''
return _sysfs_attr([_bcpath(dev), name], value, log_lvl, log_msg)
def _sysfs_attr(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper with logging around sysfs.attr
'''
if isinstance(name, six.string_types):
name = [name]
res = __salt__['sysfs.attr'](os.path.join(*name), value)
if not res and log_lvl is not None and log_msg is not None:
log.log(LOG[log_lvl], log_msg)
return res
def _sysfs_parse(path, base_attr=None, stats=False, config=False, internals=False, options=False):
'''
Helper function for parsing BCache's SysFS interface
'''
result = {}
# ---------------- Parse through the interfaces list ----------------
intfs = __salt__['sysfs.interfaces'](path)
# Actions, we ignore
del intfs['w']
# -------- Sorting hat --------
binkeys = []
if internals:
binkeys.extend(['inter_ro', 'inter_rw'])
if config:
binkeys.append('config')
if stats:
binkeys.append('stats')
bintf = {}
for key in binkeys:
bintf[key] = []
for intf in intfs['r']:
if intf.startswith('internal'):
key = 'inter_ro'
elif 'stats' in intf:
key = 'stats'
else:
# What to do with these???
# I'll utilize 'inter_ro' as 'misc' as well
key = 'inter_ro'
if key in bintf:
bintf[key].append(intf)
for intf in intfs['rw']:
if intf.startswith('internal'):
key = 'inter_rw'
else:
key = 'config'
if key in bintf:
bintf[key].append(intf)
if base_attr is not None:
for intf in bintf:
bintf[intf] = [sintf for sintf in bintf[intf] if sintf not in base_attr]
bintf['base'] = base_attr
mods = {
'stats': ['internal/bset_tree_stats', 'writeback_rate_debug', 'metadata_written', 'nbuckets', 'written',
'average_key_size', 'btree_cache_size'],
}
for modt, modlist in mods.items():
found = []
if modt not in bintf:
continue
for mod in modlist:
for intflist in bintf.values():
if mod in intflist:
found.append(mod)
intflist.remove(mod)
bintf[modt] += found
# -------- Fetch SysFS vals --------
bintflist = [intf for iflist in bintf.values() for intf in iflist]
result.update(__salt__['sysfs.read'](bintflist, path))
# -------- Parse through well known string lists --------
for strlist in ('writeback_rate_debug', 'internal/bset_tree_stats', 'priority_stats'):
if strlist in result:
listres = {}
for line in result[strlist].split('\n'):
key, val = line.split(':', 1)
val = val.strip()
try:
val = int(val)
except Exception:
try:
val = float(val)
except Exception:
pass
listres[key.strip()] = val
result[strlist] = listres
# -------- Parse through selection lists --------
if not options:
for sellist in ('cache_mode', 'cache_replacement_policy', 'errors'):
if sellist in result:
result[sellist] = re.search(r'\[(.+)\]', result[sellist]).groups()[0]
# -------- Parse through well known bools --------
for boolkey in ('running', 'writeback_running', 'congested'):
if boolkey in result:
result[boolkey] = bool(result[boolkey])
# -------- Recategorize results --------
bresult = {}
for iftype, intflist in bintf.items():
ifres = {}
for intf in intflist:
if intf in result:
ifres[intf] = result.pop(intf)
if ifres:
bresult[iftype] = ifres
return bresult
def _size_map(size):
'''
Map Bcache's size strings to real bytes
'''
try:
# I know, I know, EAFP.
# But everything else is reason for None
if not isinstance(size, int):
if re.search(r'[Kk]', size):
size = 1024 * float(re.sub(r'[Kk]', '', size))
elif re.search(r'[Mm]', size):
size = 1024**2 * float(re.sub(r'[Mm]', '', size))
size = int(size)
return size
except Exception:
return None
def _sizes(dev):
'''
Return neigh useless sizing info about a blockdev
:return: (total size in blocks, blocksize, maximum discard size in bytes)
'''
dev = _devbase(dev)
# standarization yay
block_sizes = ('hw_sector_size', 'minimum_io_size', 'physical_block_size', 'logical_block_size')
discard_sizes = ('discard_max_bytes', 'discard_max_hw_bytes', )
sysfs = __salt__['sysfs.read'](
('size',
'queue/hw_sector_size', '../queue/hw_sector_size',
'queue/discard_max_bytes', '../queue/discard_max_bytes'),
root=_syspath(dev))
# TODO: makes no sense
# First of all, it has to be a power of 2
# Secondly, this returns 4GiB - 512b on Intel 3500's for some weird reason
# discard_granularity seems in bytes, resolves to 512b ???
# max_hw_sectors_kb???
# There's also discard_max_hw_bytes more recently
# See: https://www.kernel.org/doc/Documentation/block/queue-sysfs.txt
# Also, I cant find any docs yet regarding bucket sizes;
# it's supposed to be discard_max_hw_bytes,
# but no way to figure that one reliably out apparently
discard = sysfs.get('queue/discard_max_bytes', sysfs.get('../queue/discard_max_bytes', None))
block = sysfs.get('queue/hw_sector_size', sysfs.get('../queue/hw_sector_size', None))
return 512*sysfs['size'], block, discard
def _wipe(dev):
'''
REALLY DESTRUCTIVE STUFF RIGHT AHEAD
'''
endres = 0
dev = _devbase(dev)
size, block, discard = _sizes(dev)
if discard is None:
log.error('Unable to read SysFS props for %s', dev)
return None
elif not discard:
log.warning('%s seems unable to discard', dev)
wiper = 'dd'
elif not HAS_BLKDISCARD:
log.warning('blkdiscard binary not available, properly wipe the dev manually for optimal results')
wiper = 'dd'
else:
wiper = 'blkdiscard'
wipe_failmsg = 'Error wiping {0}: %s'.format(dev)
if wiper == 'dd':
blocks = 4
cmd = 'dd if=/dev/zero of=/dev/{0} bs=1M count={1}'.format(dev, blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# Some stuff (<cough>GPT</cough>) writes stuff at the end of a dev as well
cmd += ' seek={0}'.format((size/1024**2) - blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
elif wiper == 'blkdiscard':
cmd = 'blkdiscard /dev/{0}'.format(dev)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# TODO: fix annoying bug failing blkdiscard by trying to discard 1 sector past blkdev
endres = 1
return endres > 0
def _wait(lfunc, log_lvl=None, log_msg=None, tries=10):
'''
Wait for lfunc to be True
:return: True if lfunc succeeded within tries, False if it didn't
'''
i = 0
while i < tries:
time.sleep(1)
if lfunc():
return True
else:
i += 1
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg)
return False
def _run_all(cmd, log_lvl=None, log_msg=None, exitcode=0):
'''
Simple wrapper around cmd.run_all
log_msg can contain {0} for stderr
:return: True or stdout, False if retcode wasn't exitcode
'''
res = __salt__['cmd.run_all'](cmd)
if res['retcode'] == exitcode:
if res['stdout']:
return res['stdout']
else:
return True
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg, res['stderr'])
return False
def _alltrue(resdict):
if resdict is None:
return True
return len([val for val in resdict.values() if val]) > 0
|
saltstack/salt
|
salt/modules/bcache.py
|
_bdev
|
python
|
def _bdev(dev=None):
'''
Resolve a bcacheX or cache to a real dev
:return: basename of bcache dev
'''
if dev is None:
dev = _fssys('cache0')
else:
dev = _bcpath(dev)
if not dev:
return False
else:
return _devbase(os.path.dirname(dev))
|
Resolve a bcacheX or cache to a real dev
:return: basename of bcache dev
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bcache.py#L652-L665
|
[
"def _fssys(name, value=None, log_lvl=None, log_msg=None):\n '''\n Simple wrapper to interface with bcache SysFS\n '''\n fspath = _fspath()\n if not fspath:\n return False\n else:\n return _sysfs_attr([fspath, name], value, log_lvl, log_msg)\n",
"def _devbase(dev):\n '''\n Basename of just about any dev\n '''\n dev = os.path.realpath(os.path.expandvars(dev))\n dev = os.path.basename(dev)\n return dev\n"
] |
# -*- coding: utf-8 -*-
'''
Module for managing BCache sets
BCache is a block-level caching mechanism similar to ZFS L2ARC/ZIL, dm-cache and fscache.
It works by formatting one block device as a cache set, then adding backend devices
(which need to be formatted as such) to the set and activating them.
It's available in Linux mainline kernel since 3.10
https://www.kernel.org/doc/Documentation/bcache.txt
This module needs the bcache userspace tools to function.
.. versionadded: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import time
import re
from salt.ext import six
# Import salt libs
import salt.utils.path
log = logging.getLogger(__name__)
LOG = {
'trace': logging.TRACE,
'debug': logging.DEBUG,
'info': logging.INFO,
'warn': logging.WARNING,
'error': logging.ERROR,
'crit': logging.CRITICAL,
}
__func_alias__ = {
'attach_': 'attach',
'config_': 'config',
'super_': 'super',
}
HAS_BLKDISCARD = salt.utils.path.which('blkdiscard') is not None
def __virtual__():
'''
Only work when make-bcache is installed
'''
return salt.utils.path.which('make-bcache') is not None
def uuid(dev=None):
'''
Return the bcache UUID of a block device.
If no device is given, the Cache UUID is returned.
CLI example:
.. code-block:: bash
salt '*' bcache.uuid
salt '*' bcache.uuid /dev/sda
salt '*' bcache.uuid bcache0
'''
try:
if dev is None:
# take the only directory in /sys/fs/bcache and return it's basename
return list(salt.utils.path.os_walk('/sys/fs/bcache/'))[0][1][0]
else:
# basename of the /sys/block/{dev}/bcache/cache symlink target
return os.path.basename(_bcsys(dev, 'cache'))
except Exception:
return False
def attach_(dev=None):
'''
Attach a backing devices to a cache set
If no dev is given, all backing devices will be attached.
CLI example:
.. code-block:: bash
salt '*' bcache.attach sdc
salt '*' bcache.attach /dev/bcache1
:return: bool or None if nuttin' happened
'''
cache = uuid()
if not cache:
log.error('No cache to attach %s to', dev)
return False
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = attach_(dev)
return res if res else None
bcache = uuid(dev)
if bcache:
if bcache == cache:
log.info('%s is already attached to bcache %s, doing nothing', dev, cache)
return None
elif not detach(dev):
return False
log.debug('Attaching %s to bcache %s', dev, cache)
if not _bcsys(dev, 'attach', cache,
'error', 'Error attaching {0} to bcache {1}'.format(dev, cache)):
return False
return _wait(lambda: uuid(dev) == cache,
'error', '{0} received attach to bcache {1}, but did not comply'.format(dev, cache))
def detach(dev=None):
'''
Detach a backing device(s) from a cache set
If no dev is given, all backing devices will be attached.
Detaching a backing device will flush it's write cache.
This should leave the underlying device in a consistent state, but might take a while.
CLI example:
.. code-block:: bash
salt '*' bcache.detach sdc
salt '*' bcache.detach bcache1
'''
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = detach(dev)
return res if res else None
log.debug('Detaching %s', dev)
if not _bcsys(dev, 'detach', 'goaway', 'error', 'Error detaching {0}'.format(dev)):
return False
return _wait(lambda: uuid(dev) is False, 'error', '{0} received detach, but did not comply'.format(dev), 300)
def start():
'''
Trigger a start of the full bcache system through udev.
CLI example:
.. code-block:: bash
salt '*' bcache.start
'''
if not _run_all('udevadm trigger', 'error', 'Error starting bcache: %s'):
return False
elif not _wait(lambda: uuid() is not False, 'warn', 'Bcache system started, but no active cache set found.'):
return False
return True
def stop(dev=None):
'''
Stop a bcache device
If no device is given, all backing devices will be detached from the cache, which will subsequently be stopped.
.. warning::
'Stop' on an individual backing device means hard-stop;
no attempt at flushing will be done and the bcache device will seemingly 'disappear' from the device lists
CLI example:
.. code-block:: bash
salt '*' bcache.stop
'''
if dev is not None:
log.warning('Stopping %s, device will only reappear after reregistering!', dev)
if not _bcsys(dev, 'stop', 'goaway', 'error', 'Error stopping {0}'.format(dev)):
return False
return _wait(lambda: _sysfs_attr(_bcpath(dev)) is False, 'error', 'Device {0} did not stop'.format(dev), 300)
else:
cache = uuid()
if not cache:
log.warning('bcache already stopped?')
return None
if not _alltrue(detach()):
return False
elif not _fssys('stop', 'goaway', 'error', 'Error stopping cache'):
return False
return _wait(lambda: uuid() is False, 'error', 'Cache did not stop', 300)
def back_make(dev, cache_mode='writeback', force=False, attach=True, bucket_size=None):
'''
Create a backing device for attachment to a set.
Because the block size must be the same, a cache set already needs to exist.
CLI example:
.. code-block:: bash
salt '*' bcache.back_make sdc cache_mode=writeback attach=True
:param cache_mode: writethrough, writeback, writearound or none.
:param force: Overwrite existing bcaches
:param attach: Immediately attach the backing device to the set
:param bucket_size: Size of a bucket (see kernel doc)
'''
# pylint: disable=too-many-return-statements
cache = uuid()
if not cache:
log.error('No bcache set found')
return False
elif _sysfs_attr(_bcpath(dev)):
if not force:
log.error('%s already contains a bcache. Wipe it manually or use force', dev)
return False
elif uuid(dev) and not detach(dev):
return False
elif not stop(dev):
return False
dev = _devpath(dev)
block_size = _size_map(_fssys('block_size'))
# You might want to override, we pick the cache set's as sane default
if bucket_size is None:
bucket_size = _size_map(_fssys('bucket_size'))
cmd = 'make-bcache --block {0} --bucket {1} --{2} --bdev {3}'.format(block_size, bucket_size, cache_mode, dev)
if force:
cmd += ' --wipe-bcache'
if not _run_all(cmd, 'error', 'Error creating backing device {0}: %s'.format(dev)):
return False
elif not _sysfs_attr('fs/bcache/register', _devpath(dev),
'error', 'Error registering backing device {0}'.format(dev)):
return False
elif not _wait(lambda: _sysfs_attr(_bcpath(dev)) is not False,
'error', 'Backing device {0} did not register'.format(dev)):
return False
elif attach:
return attach_(dev)
return True
def cache_make(dev, reserved=None, force=False, block_size=None, bucket_size=None, attach=True):
'''
Create BCache cache on a block device.
If blkdiscard is available the entire device will be properly cleared in advance.
CLI example:
.. code-block:: bash
salt '*' bcache.cache_make sdb reserved=10% block_size=4096
:param reserved: if dev is a full device, create a partition table with this size empty.
.. note::
this increases the amount of reserved space available to SSD garbage collectors,
potentially (vastly) increasing performance
:param block_size: Block size of the cache; defaults to devices' logical block size
:param force: Overwrite existing BCache sets
:param attach: Attach all existing backend devices immediately
'''
# TODO: multiple devs == md jbod
# pylint: disable=too-many-return-statements
# ---------------- Preflight checks ----------------
cache = uuid()
if cache:
if not force:
log.error('BCache cache %s is already on the system', cache)
return False
cache = _bdev()
dev = _devbase(dev)
udev = __salt__['udev.env'](dev)
if ('ID_FS_TYPE' in udev or (udev.get('DEVTYPE', None) != 'partition' and 'ID_PART_TABLE_TYPE' in udev)) \
and not force:
log.error('%s already contains data, wipe first or force', dev)
return False
elif reserved is not None and udev.get('DEVTYPE', None) != 'disk':
log.error('Need a partitionable blockdev for reserved to work')
return False
_, block, bucket = _sizes(dev)
if bucket_size is None:
bucket_size = bucket
# TODO: bucket from _sizes() makes no sense
bucket_size = False
if block_size is None:
block_size = block
# ---------------- Still here, start doing destructive stuff ----------------
if cache:
if not stop():
return False
# Wipe the current cache device as well,
# forever ruining any chance of it accidentally popping up again
elif not _wipe(cache):
return False
# Can't do enough wiping
if not _wipe(dev):
return False
if reserved:
cmd = 'parted -m -s -a optimal -- ' \
'/dev/{0} mklabel gpt mkpart bcache-reserved 1M {1} mkpart bcache {1} 100%'.format(dev, reserved)
# if wipe was incomplete & part layout remains the same,
# this is one condition set where udev would make it accidentally popup again
if not _run_all(cmd, 'error', 'Error creating bcache partitions on {0}: %s'.format(dev)):
return False
dev = '{0}2'.format(dev)
# ---------------- Finally, create a cache ----------------
cmd = 'make-bcache --cache /dev/{0} --block {1} --wipe-bcache'.format(dev, block_size)
# Actually bucket_size should always have a value, but for testing 0 is possible as well
if bucket_size:
cmd += ' --bucket {0}'.format(bucket_size)
if not _run_all(cmd, 'error', 'Error creating cache {0}: %s'.format(dev)):
return False
elif not _wait(lambda: uuid() is not False,
'error', 'Cache {0} seemingly created OK, but FS did not activate'.format(dev)):
return False
if attach:
return _alltrue(attach_())
else:
return True
def config_(dev=None, **kwargs):
'''
Show or update config of a bcache device.
If no device is given, operate on the cache set itself.
CLI example:
.. code-block:: bash
salt '*' bcache.config
salt '*' bcache.config bcache1
salt '*' bcache.config errors=panic journal_delay_ms=150
salt '*' bcache.config bcache1 cache_mode=writeback writeback_percent=15
:return: config or True/False
'''
if dev is None:
spath = _fspath()
else:
spath = _bcpath(dev)
# filter out 'hidden' kwargs added by our favourite orchestration system
updates = dict([(key, val) for key, val in kwargs.items() if not key.startswith('__')])
if updates:
endres = 0
for key, val in updates.items():
endres += _sysfs_attr([spath, key], val,
'warn', 'Failed to update {0} with {1}'.format(os.path.join(spath, key), val))
return endres > 0
else:
result = {}
data = _sysfs_parse(spath, config=True, internals=True, options=True)
for key in ('other_ro', 'inter_ro'):
if key in data:
del data[key]
for key in data:
result.update(data[key])
return result
def status(stats=False, config=False, internals=False, superblock=False, alldevs=False):
'''
Show the full status of the BCache system and optionally all it's involved devices
CLI example:
.. code-block:: bash
salt '*' bcache.status
salt '*' bcache.status stats=True
salt '*' bcache.status internals=True alldevs=True
:param stats: include statistics
:param config: include settings
:param internals: include internals
:param superblock: include superblock
'''
bdevs = []
for _, links, _ in salt.utils.path.os_walk('/sys/block/'):
for block in links:
if 'bcache' in block:
continue
for spath, sdirs, _ in salt.utils.path.os_walk('/sys/block/{0}'.format(block), followlinks=False):
if 'bcache' in sdirs:
bdevs.append(os.path.basename(spath))
statii = {}
for bcache in bdevs:
statii[bcache] = device(bcache, stats, config, internals, superblock)
cuuid = uuid()
cdev = _bdev()
if cdev:
count = 0
for dev in statii:
if dev != cdev:
# it's a backing dev
if statii[dev]['cache'] == cuuid:
count += 1
statii[cdev]['attached_backing_devices'] = count
if not alldevs:
statii = statii[cdev]
return statii
def device(dev, stats=False, config=False, internals=False, superblock=False):
'''
Check the state of a single bcache device
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc stats=True
:param stats: include statistics
:param settings: include all settings
:param internals: include all internals
:param superblock: include superblock info
'''
result = {}
if not _sysfs_attr(_bcpath(dev), None, 'error', '{0} is not a bcache fo any kind'.format(dev)):
return False
elif _bcsys(dev, 'set'):
# ---------------- It's the cache itself ----------------
result['uuid'] = uuid()
base_attr = ['block_size', 'bucket_size', 'cache_available_percent', 'cache_replacement_policy', 'congested']
# ---------------- Parse through both the blockdev & the FS ----------------
result.update(_sysfs_parse(_bcpath(dev), base_attr, stats, config, internals))
result.update(_sysfs_parse(_fspath(), base_attr, stats, config, internals))
result.update(result.pop('base'))
else:
# ---------------- It's a backing device ----------------
back_uuid = uuid(dev)
if back_uuid is not None:
result['cache'] = back_uuid
try:
result['dev'] = os.path.basename(_bcsys(dev, 'dev'))
except Exception:
pass
result['bdev'] = _bdev(dev)
base_attr = ['cache_mode', 'running', 'state', 'writeback_running']
base_path = _bcpath(dev)
result.update(_sysfs_parse(base_path, base_attr, stats, config, internals))
result.update(result.pop('base'))
# ---------------- Modifications ----------------
state = [result['state']]
if result.pop('running'):
state.append('running')
else:
state.append('stopped')
if 'writeback_running' in result:
if result.pop('writeback_running'):
state.append('writeback_running')
else:
state.append('writeback_stopped')
result['state'] = state
# ---------------- Statistics ----------------
if 'stats' in result:
replre = r'(stats|cache)_'
statres = result['stats']
for attr in result['stats']:
if '/' not in attr:
key = re.sub(replre, '', attr)
statres[key] = statres.pop(attr)
else:
stat, key = attr.split('/', 1)
stat = re.sub(replre, '', stat)
key = re.sub(replre, '', key)
if stat not in statres:
statres[stat] = {}
statres[stat][key] = statres.pop(attr)
result['stats'] = statres
# ---------------- Internals ----------------
if internals:
interres = result.pop('inter_ro', {})
interres.update(result.pop('inter_rw', {}))
if interres:
for key in interres:
if key.startswith('internal'):
nkey = re.sub(r'internal[s/]*', '', key)
interres[nkey] = interres.pop(key)
key = nkey
if key.startswith(('btree', 'writeback')):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in interres:
interres[mkey] = {}
interres[mkey][skey] = interres.pop(key)
result['internals'] = interres
# ---------------- Config ----------------
if config:
configres = result['config']
for key in configres:
if key.startswith('writeback'):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in configres:
configres[mkey] = {}
configres[mkey][skey] = configres.pop(key)
result['config'] = configres
# ---------------- Superblock ----------------
if superblock:
result['superblock'] = super_(dev)
return result
def super_(dev):
'''
Read out BCache SuperBlock
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc
'''
dev = _devpath(dev)
ret = {}
res = _run_all('bcache-super-show {0}'.format(dev), 'error', 'Error reading superblock on {0}: %s'.format(dev))
if not res:
return False
for line in res.splitlines(): # pylint: disable=no-member
line = line.strip()
if not line:
continue
key, val = [val.strip() for val in re.split(r'[\s]+', line, maxsplit=1)]
if not (key and val):
continue
mval = None
if ' ' in val:
rval, mval = [val.strip() for val in re.split(r'[\s]+', val, maxsplit=1)]
mval = mval[1:-1]
else:
rval = val
try:
rval = int(rval)
except Exception:
try:
rval = float(rval)
except Exception:
if rval == 'yes':
rval = True
elif rval == 'no':
rval = False
pkey, key = re.split(r'\.', key, maxsplit=1)
if pkey not in ret:
ret[pkey] = {}
if mval is not None:
ret[pkey][key] = (rval, mval)
else:
ret[pkey][key] = rval
return ret
# -------------------------------- HELPER FUNCTIONS --------------------------------
def _devbase(dev):
'''
Basename of just about any dev
'''
dev = os.path.realpath(os.path.expandvars(dev))
dev = os.path.basename(dev)
return dev
def _devpath(dev):
'''
Return /dev name of just about any dev
:return: /dev/devicename
'''
return os.path.join('/dev', _devbase(dev))
def _syspath(dev):
'''
Full SysFS path of a device
'''
dev = _devbase(dev)
dev = re.sub(r'^([vhs][a-z]+)([0-9]+)', r'\1/\1\2', dev)
# name = re.sub(r'^([a-z]+)(?<!(bcache|md|dm))([0-9]+)', r'\1/\1\2', name)
return os.path.join('/sys/block/', dev)
def _bcpath(dev):
'''
Full SysFS path of a bcache device
'''
return os.path.join(_syspath(dev), 'bcache')
def _fspath():
'''
:return: path of active bcache
'''
cuuid = uuid()
if not cuuid:
return False
else:
return os.path.join('/sys/fs/bcache/', cuuid)
def _fssys(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with bcache SysFS
'''
fspath = _fspath()
if not fspath:
return False
else:
return _sysfs_attr([fspath, name], value, log_lvl, log_msg)
def _bcsys(dev, name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with backing devs SysFS
'''
return _sysfs_attr([_bcpath(dev), name], value, log_lvl, log_msg)
def _sysfs_attr(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper with logging around sysfs.attr
'''
if isinstance(name, six.string_types):
name = [name]
res = __salt__['sysfs.attr'](os.path.join(*name), value)
if not res and log_lvl is not None and log_msg is not None:
log.log(LOG[log_lvl], log_msg)
return res
def _sysfs_parse(path, base_attr=None, stats=False, config=False, internals=False, options=False):
'''
Helper function for parsing BCache's SysFS interface
'''
result = {}
# ---------------- Parse through the interfaces list ----------------
intfs = __salt__['sysfs.interfaces'](path)
# Actions, we ignore
del intfs['w']
# -------- Sorting hat --------
binkeys = []
if internals:
binkeys.extend(['inter_ro', 'inter_rw'])
if config:
binkeys.append('config')
if stats:
binkeys.append('stats')
bintf = {}
for key in binkeys:
bintf[key] = []
for intf in intfs['r']:
if intf.startswith('internal'):
key = 'inter_ro'
elif 'stats' in intf:
key = 'stats'
else:
# What to do with these???
# I'll utilize 'inter_ro' as 'misc' as well
key = 'inter_ro'
if key in bintf:
bintf[key].append(intf)
for intf in intfs['rw']:
if intf.startswith('internal'):
key = 'inter_rw'
else:
key = 'config'
if key in bintf:
bintf[key].append(intf)
if base_attr is not None:
for intf in bintf:
bintf[intf] = [sintf for sintf in bintf[intf] if sintf not in base_attr]
bintf['base'] = base_attr
mods = {
'stats': ['internal/bset_tree_stats', 'writeback_rate_debug', 'metadata_written', 'nbuckets', 'written',
'average_key_size', 'btree_cache_size'],
}
for modt, modlist in mods.items():
found = []
if modt not in bintf:
continue
for mod in modlist:
for intflist in bintf.values():
if mod in intflist:
found.append(mod)
intflist.remove(mod)
bintf[modt] += found
# -------- Fetch SysFS vals --------
bintflist = [intf for iflist in bintf.values() for intf in iflist]
result.update(__salt__['sysfs.read'](bintflist, path))
# -------- Parse through well known string lists --------
for strlist in ('writeback_rate_debug', 'internal/bset_tree_stats', 'priority_stats'):
if strlist in result:
listres = {}
for line in result[strlist].split('\n'):
key, val = line.split(':', 1)
val = val.strip()
try:
val = int(val)
except Exception:
try:
val = float(val)
except Exception:
pass
listres[key.strip()] = val
result[strlist] = listres
# -------- Parse through selection lists --------
if not options:
for sellist in ('cache_mode', 'cache_replacement_policy', 'errors'):
if sellist in result:
result[sellist] = re.search(r'\[(.+)\]', result[sellist]).groups()[0]
# -------- Parse through well known bools --------
for boolkey in ('running', 'writeback_running', 'congested'):
if boolkey in result:
result[boolkey] = bool(result[boolkey])
# -------- Recategorize results --------
bresult = {}
for iftype, intflist in bintf.items():
ifres = {}
for intf in intflist:
if intf in result:
ifres[intf] = result.pop(intf)
if ifres:
bresult[iftype] = ifres
return bresult
def _size_map(size):
'''
Map Bcache's size strings to real bytes
'''
try:
# I know, I know, EAFP.
# But everything else is reason for None
if not isinstance(size, int):
if re.search(r'[Kk]', size):
size = 1024 * float(re.sub(r'[Kk]', '', size))
elif re.search(r'[Mm]', size):
size = 1024**2 * float(re.sub(r'[Mm]', '', size))
size = int(size)
return size
except Exception:
return None
def _sizes(dev):
'''
Return neigh useless sizing info about a blockdev
:return: (total size in blocks, blocksize, maximum discard size in bytes)
'''
dev = _devbase(dev)
# standarization yay
block_sizes = ('hw_sector_size', 'minimum_io_size', 'physical_block_size', 'logical_block_size')
discard_sizes = ('discard_max_bytes', 'discard_max_hw_bytes', )
sysfs = __salt__['sysfs.read'](
('size',
'queue/hw_sector_size', '../queue/hw_sector_size',
'queue/discard_max_bytes', '../queue/discard_max_bytes'),
root=_syspath(dev))
# TODO: makes no sense
# First of all, it has to be a power of 2
# Secondly, this returns 4GiB - 512b on Intel 3500's for some weird reason
# discard_granularity seems in bytes, resolves to 512b ???
# max_hw_sectors_kb???
# There's also discard_max_hw_bytes more recently
# See: https://www.kernel.org/doc/Documentation/block/queue-sysfs.txt
# Also, I cant find any docs yet regarding bucket sizes;
# it's supposed to be discard_max_hw_bytes,
# but no way to figure that one reliably out apparently
discard = sysfs.get('queue/discard_max_bytes', sysfs.get('../queue/discard_max_bytes', None))
block = sysfs.get('queue/hw_sector_size', sysfs.get('../queue/hw_sector_size', None))
return 512*sysfs['size'], block, discard
def _wipe(dev):
'''
REALLY DESTRUCTIVE STUFF RIGHT AHEAD
'''
endres = 0
dev = _devbase(dev)
size, block, discard = _sizes(dev)
if discard is None:
log.error('Unable to read SysFS props for %s', dev)
return None
elif not discard:
log.warning('%s seems unable to discard', dev)
wiper = 'dd'
elif not HAS_BLKDISCARD:
log.warning('blkdiscard binary not available, properly wipe the dev manually for optimal results')
wiper = 'dd'
else:
wiper = 'blkdiscard'
wipe_failmsg = 'Error wiping {0}: %s'.format(dev)
if wiper == 'dd':
blocks = 4
cmd = 'dd if=/dev/zero of=/dev/{0} bs=1M count={1}'.format(dev, blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# Some stuff (<cough>GPT</cough>) writes stuff at the end of a dev as well
cmd += ' seek={0}'.format((size/1024**2) - blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
elif wiper == 'blkdiscard':
cmd = 'blkdiscard /dev/{0}'.format(dev)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# TODO: fix annoying bug failing blkdiscard by trying to discard 1 sector past blkdev
endres = 1
return endres > 0
def _wait(lfunc, log_lvl=None, log_msg=None, tries=10):
'''
Wait for lfunc to be True
:return: True if lfunc succeeded within tries, False if it didn't
'''
i = 0
while i < tries:
time.sleep(1)
if lfunc():
return True
else:
i += 1
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg)
return False
def _run_all(cmd, log_lvl=None, log_msg=None, exitcode=0):
'''
Simple wrapper around cmd.run_all
log_msg can contain {0} for stderr
:return: True or stdout, False if retcode wasn't exitcode
'''
res = __salt__['cmd.run_all'](cmd)
if res['retcode'] == exitcode:
if res['stdout']:
return res['stdout']
else:
return True
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg, res['stderr'])
return False
def _alltrue(resdict):
if resdict is None:
return True
return len([val for val in resdict.values() if val]) > 0
|
saltstack/salt
|
salt/modules/bcache.py
|
_fssys
|
python
|
def _fssys(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with bcache SysFS
'''
fspath = _fspath()
if not fspath:
return False
else:
return _sysfs_attr([fspath, name], value, log_lvl, log_msg)
|
Simple wrapper to interface with bcache SysFS
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bcache.py#L686-L694
|
[
"def _sysfs_attr(name, value=None, log_lvl=None, log_msg=None):\n '''\n Simple wrapper with logging around sysfs.attr\n '''\n if isinstance(name, six.string_types):\n name = [name]\n res = __salt__['sysfs.attr'](os.path.join(*name), value)\n if not res and log_lvl is not None and log_msg is not None:\n log.log(LOG[log_lvl], log_msg)\n return res\n",
"def _fspath():\n '''\n :return: path of active bcache\n '''\n cuuid = uuid()\n if not cuuid:\n return False\n else:\n return os.path.join('/sys/fs/bcache/', cuuid)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for managing BCache sets
BCache is a block-level caching mechanism similar to ZFS L2ARC/ZIL, dm-cache and fscache.
It works by formatting one block device as a cache set, then adding backend devices
(which need to be formatted as such) to the set and activating them.
It's available in Linux mainline kernel since 3.10
https://www.kernel.org/doc/Documentation/bcache.txt
This module needs the bcache userspace tools to function.
.. versionadded: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import time
import re
from salt.ext import six
# Import salt libs
import salt.utils.path
log = logging.getLogger(__name__)
LOG = {
'trace': logging.TRACE,
'debug': logging.DEBUG,
'info': logging.INFO,
'warn': logging.WARNING,
'error': logging.ERROR,
'crit': logging.CRITICAL,
}
__func_alias__ = {
'attach_': 'attach',
'config_': 'config',
'super_': 'super',
}
HAS_BLKDISCARD = salt.utils.path.which('blkdiscard') is not None
def __virtual__():
'''
Only work when make-bcache is installed
'''
return salt.utils.path.which('make-bcache') is not None
def uuid(dev=None):
'''
Return the bcache UUID of a block device.
If no device is given, the Cache UUID is returned.
CLI example:
.. code-block:: bash
salt '*' bcache.uuid
salt '*' bcache.uuid /dev/sda
salt '*' bcache.uuid bcache0
'''
try:
if dev is None:
# take the only directory in /sys/fs/bcache and return it's basename
return list(salt.utils.path.os_walk('/sys/fs/bcache/'))[0][1][0]
else:
# basename of the /sys/block/{dev}/bcache/cache symlink target
return os.path.basename(_bcsys(dev, 'cache'))
except Exception:
return False
def attach_(dev=None):
'''
Attach a backing devices to a cache set
If no dev is given, all backing devices will be attached.
CLI example:
.. code-block:: bash
salt '*' bcache.attach sdc
salt '*' bcache.attach /dev/bcache1
:return: bool or None if nuttin' happened
'''
cache = uuid()
if not cache:
log.error('No cache to attach %s to', dev)
return False
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = attach_(dev)
return res if res else None
bcache = uuid(dev)
if bcache:
if bcache == cache:
log.info('%s is already attached to bcache %s, doing nothing', dev, cache)
return None
elif not detach(dev):
return False
log.debug('Attaching %s to bcache %s', dev, cache)
if not _bcsys(dev, 'attach', cache,
'error', 'Error attaching {0} to bcache {1}'.format(dev, cache)):
return False
return _wait(lambda: uuid(dev) == cache,
'error', '{0} received attach to bcache {1}, but did not comply'.format(dev, cache))
def detach(dev=None):
'''
Detach a backing device(s) from a cache set
If no dev is given, all backing devices will be attached.
Detaching a backing device will flush it's write cache.
This should leave the underlying device in a consistent state, but might take a while.
CLI example:
.. code-block:: bash
salt '*' bcache.detach sdc
salt '*' bcache.detach bcache1
'''
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = detach(dev)
return res if res else None
log.debug('Detaching %s', dev)
if not _bcsys(dev, 'detach', 'goaway', 'error', 'Error detaching {0}'.format(dev)):
return False
return _wait(lambda: uuid(dev) is False, 'error', '{0} received detach, but did not comply'.format(dev), 300)
def start():
'''
Trigger a start of the full bcache system through udev.
CLI example:
.. code-block:: bash
salt '*' bcache.start
'''
if not _run_all('udevadm trigger', 'error', 'Error starting bcache: %s'):
return False
elif not _wait(lambda: uuid() is not False, 'warn', 'Bcache system started, but no active cache set found.'):
return False
return True
def stop(dev=None):
'''
Stop a bcache device
If no device is given, all backing devices will be detached from the cache, which will subsequently be stopped.
.. warning::
'Stop' on an individual backing device means hard-stop;
no attempt at flushing will be done and the bcache device will seemingly 'disappear' from the device lists
CLI example:
.. code-block:: bash
salt '*' bcache.stop
'''
if dev is not None:
log.warning('Stopping %s, device will only reappear after reregistering!', dev)
if not _bcsys(dev, 'stop', 'goaway', 'error', 'Error stopping {0}'.format(dev)):
return False
return _wait(lambda: _sysfs_attr(_bcpath(dev)) is False, 'error', 'Device {0} did not stop'.format(dev), 300)
else:
cache = uuid()
if not cache:
log.warning('bcache already stopped?')
return None
if not _alltrue(detach()):
return False
elif not _fssys('stop', 'goaway', 'error', 'Error stopping cache'):
return False
return _wait(lambda: uuid() is False, 'error', 'Cache did not stop', 300)
def back_make(dev, cache_mode='writeback', force=False, attach=True, bucket_size=None):
'''
Create a backing device for attachment to a set.
Because the block size must be the same, a cache set already needs to exist.
CLI example:
.. code-block:: bash
salt '*' bcache.back_make sdc cache_mode=writeback attach=True
:param cache_mode: writethrough, writeback, writearound or none.
:param force: Overwrite existing bcaches
:param attach: Immediately attach the backing device to the set
:param bucket_size: Size of a bucket (see kernel doc)
'''
# pylint: disable=too-many-return-statements
cache = uuid()
if not cache:
log.error('No bcache set found')
return False
elif _sysfs_attr(_bcpath(dev)):
if not force:
log.error('%s already contains a bcache. Wipe it manually or use force', dev)
return False
elif uuid(dev) and not detach(dev):
return False
elif not stop(dev):
return False
dev = _devpath(dev)
block_size = _size_map(_fssys('block_size'))
# You might want to override, we pick the cache set's as sane default
if bucket_size is None:
bucket_size = _size_map(_fssys('bucket_size'))
cmd = 'make-bcache --block {0} --bucket {1} --{2} --bdev {3}'.format(block_size, bucket_size, cache_mode, dev)
if force:
cmd += ' --wipe-bcache'
if not _run_all(cmd, 'error', 'Error creating backing device {0}: %s'.format(dev)):
return False
elif not _sysfs_attr('fs/bcache/register', _devpath(dev),
'error', 'Error registering backing device {0}'.format(dev)):
return False
elif not _wait(lambda: _sysfs_attr(_bcpath(dev)) is not False,
'error', 'Backing device {0} did not register'.format(dev)):
return False
elif attach:
return attach_(dev)
return True
def cache_make(dev, reserved=None, force=False, block_size=None, bucket_size=None, attach=True):
'''
Create BCache cache on a block device.
If blkdiscard is available the entire device will be properly cleared in advance.
CLI example:
.. code-block:: bash
salt '*' bcache.cache_make sdb reserved=10% block_size=4096
:param reserved: if dev is a full device, create a partition table with this size empty.
.. note::
this increases the amount of reserved space available to SSD garbage collectors,
potentially (vastly) increasing performance
:param block_size: Block size of the cache; defaults to devices' logical block size
:param force: Overwrite existing BCache sets
:param attach: Attach all existing backend devices immediately
'''
# TODO: multiple devs == md jbod
# pylint: disable=too-many-return-statements
# ---------------- Preflight checks ----------------
cache = uuid()
if cache:
if not force:
log.error('BCache cache %s is already on the system', cache)
return False
cache = _bdev()
dev = _devbase(dev)
udev = __salt__['udev.env'](dev)
if ('ID_FS_TYPE' in udev or (udev.get('DEVTYPE', None) != 'partition' and 'ID_PART_TABLE_TYPE' in udev)) \
and not force:
log.error('%s already contains data, wipe first or force', dev)
return False
elif reserved is not None and udev.get('DEVTYPE', None) != 'disk':
log.error('Need a partitionable blockdev for reserved to work')
return False
_, block, bucket = _sizes(dev)
if bucket_size is None:
bucket_size = bucket
# TODO: bucket from _sizes() makes no sense
bucket_size = False
if block_size is None:
block_size = block
# ---------------- Still here, start doing destructive stuff ----------------
if cache:
if not stop():
return False
# Wipe the current cache device as well,
# forever ruining any chance of it accidentally popping up again
elif not _wipe(cache):
return False
# Can't do enough wiping
if not _wipe(dev):
return False
if reserved:
cmd = 'parted -m -s -a optimal -- ' \
'/dev/{0} mklabel gpt mkpart bcache-reserved 1M {1} mkpart bcache {1} 100%'.format(dev, reserved)
# if wipe was incomplete & part layout remains the same,
# this is one condition set where udev would make it accidentally popup again
if not _run_all(cmd, 'error', 'Error creating bcache partitions on {0}: %s'.format(dev)):
return False
dev = '{0}2'.format(dev)
# ---------------- Finally, create a cache ----------------
cmd = 'make-bcache --cache /dev/{0} --block {1} --wipe-bcache'.format(dev, block_size)
# Actually bucket_size should always have a value, but for testing 0 is possible as well
if bucket_size:
cmd += ' --bucket {0}'.format(bucket_size)
if not _run_all(cmd, 'error', 'Error creating cache {0}: %s'.format(dev)):
return False
elif not _wait(lambda: uuid() is not False,
'error', 'Cache {0} seemingly created OK, but FS did not activate'.format(dev)):
return False
if attach:
return _alltrue(attach_())
else:
return True
def config_(dev=None, **kwargs):
'''
Show or update config of a bcache device.
If no device is given, operate on the cache set itself.
CLI example:
.. code-block:: bash
salt '*' bcache.config
salt '*' bcache.config bcache1
salt '*' bcache.config errors=panic journal_delay_ms=150
salt '*' bcache.config bcache1 cache_mode=writeback writeback_percent=15
:return: config or True/False
'''
if dev is None:
spath = _fspath()
else:
spath = _bcpath(dev)
# filter out 'hidden' kwargs added by our favourite orchestration system
updates = dict([(key, val) for key, val in kwargs.items() if not key.startswith('__')])
if updates:
endres = 0
for key, val in updates.items():
endres += _sysfs_attr([spath, key], val,
'warn', 'Failed to update {0} with {1}'.format(os.path.join(spath, key), val))
return endres > 0
else:
result = {}
data = _sysfs_parse(spath, config=True, internals=True, options=True)
for key in ('other_ro', 'inter_ro'):
if key in data:
del data[key]
for key in data:
result.update(data[key])
return result
def status(stats=False, config=False, internals=False, superblock=False, alldevs=False):
'''
Show the full status of the BCache system and optionally all it's involved devices
CLI example:
.. code-block:: bash
salt '*' bcache.status
salt '*' bcache.status stats=True
salt '*' bcache.status internals=True alldevs=True
:param stats: include statistics
:param config: include settings
:param internals: include internals
:param superblock: include superblock
'''
bdevs = []
for _, links, _ in salt.utils.path.os_walk('/sys/block/'):
for block in links:
if 'bcache' in block:
continue
for spath, sdirs, _ in salt.utils.path.os_walk('/sys/block/{0}'.format(block), followlinks=False):
if 'bcache' in sdirs:
bdevs.append(os.path.basename(spath))
statii = {}
for bcache in bdevs:
statii[bcache] = device(bcache, stats, config, internals, superblock)
cuuid = uuid()
cdev = _bdev()
if cdev:
count = 0
for dev in statii:
if dev != cdev:
# it's a backing dev
if statii[dev]['cache'] == cuuid:
count += 1
statii[cdev]['attached_backing_devices'] = count
if not alldevs:
statii = statii[cdev]
return statii
def device(dev, stats=False, config=False, internals=False, superblock=False):
'''
Check the state of a single bcache device
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc stats=True
:param stats: include statistics
:param settings: include all settings
:param internals: include all internals
:param superblock: include superblock info
'''
result = {}
if not _sysfs_attr(_bcpath(dev), None, 'error', '{0} is not a bcache fo any kind'.format(dev)):
return False
elif _bcsys(dev, 'set'):
# ---------------- It's the cache itself ----------------
result['uuid'] = uuid()
base_attr = ['block_size', 'bucket_size', 'cache_available_percent', 'cache_replacement_policy', 'congested']
# ---------------- Parse through both the blockdev & the FS ----------------
result.update(_sysfs_parse(_bcpath(dev), base_attr, stats, config, internals))
result.update(_sysfs_parse(_fspath(), base_attr, stats, config, internals))
result.update(result.pop('base'))
else:
# ---------------- It's a backing device ----------------
back_uuid = uuid(dev)
if back_uuid is not None:
result['cache'] = back_uuid
try:
result['dev'] = os.path.basename(_bcsys(dev, 'dev'))
except Exception:
pass
result['bdev'] = _bdev(dev)
base_attr = ['cache_mode', 'running', 'state', 'writeback_running']
base_path = _bcpath(dev)
result.update(_sysfs_parse(base_path, base_attr, stats, config, internals))
result.update(result.pop('base'))
# ---------------- Modifications ----------------
state = [result['state']]
if result.pop('running'):
state.append('running')
else:
state.append('stopped')
if 'writeback_running' in result:
if result.pop('writeback_running'):
state.append('writeback_running')
else:
state.append('writeback_stopped')
result['state'] = state
# ---------------- Statistics ----------------
if 'stats' in result:
replre = r'(stats|cache)_'
statres = result['stats']
for attr in result['stats']:
if '/' not in attr:
key = re.sub(replre, '', attr)
statres[key] = statres.pop(attr)
else:
stat, key = attr.split('/', 1)
stat = re.sub(replre, '', stat)
key = re.sub(replre, '', key)
if stat not in statres:
statres[stat] = {}
statres[stat][key] = statres.pop(attr)
result['stats'] = statres
# ---------------- Internals ----------------
if internals:
interres = result.pop('inter_ro', {})
interres.update(result.pop('inter_rw', {}))
if interres:
for key in interres:
if key.startswith('internal'):
nkey = re.sub(r'internal[s/]*', '', key)
interres[nkey] = interres.pop(key)
key = nkey
if key.startswith(('btree', 'writeback')):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in interres:
interres[mkey] = {}
interres[mkey][skey] = interres.pop(key)
result['internals'] = interres
# ---------------- Config ----------------
if config:
configres = result['config']
for key in configres:
if key.startswith('writeback'):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in configres:
configres[mkey] = {}
configres[mkey][skey] = configres.pop(key)
result['config'] = configres
# ---------------- Superblock ----------------
if superblock:
result['superblock'] = super_(dev)
return result
def super_(dev):
'''
Read out BCache SuperBlock
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc
'''
dev = _devpath(dev)
ret = {}
res = _run_all('bcache-super-show {0}'.format(dev), 'error', 'Error reading superblock on {0}: %s'.format(dev))
if not res:
return False
for line in res.splitlines(): # pylint: disable=no-member
line = line.strip()
if not line:
continue
key, val = [val.strip() for val in re.split(r'[\s]+', line, maxsplit=1)]
if not (key and val):
continue
mval = None
if ' ' in val:
rval, mval = [val.strip() for val in re.split(r'[\s]+', val, maxsplit=1)]
mval = mval[1:-1]
else:
rval = val
try:
rval = int(rval)
except Exception:
try:
rval = float(rval)
except Exception:
if rval == 'yes':
rval = True
elif rval == 'no':
rval = False
pkey, key = re.split(r'\.', key, maxsplit=1)
if pkey not in ret:
ret[pkey] = {}
if mval is not None:
ret[pkey][key] = (rval, mval)
else:
ret[pkey][key] = rval
return ret
# -------------------------------- HELPER FUNCTIONS --------------------------------
def _devbase(dev):
'''
Basename of just about any dev
'''
dev = os.path.realpath(os.path.expandvars(dev))
dev = os.path.basename(dev)
return dev
def _devpath(dev):
'''
Return /dev name of just about any dev
:return: /dev/devicename
'''
return os.path.join('/dev', _devbase(dev))
def _syspath(dev):
'''
Full SysFS path of a device
'''
dev = _devbase(dev)
dev = re.sub(r'^([vhs][a-z]+)([0-9]+)', r'\1/\1\2', dev)
# name = re.sub(r'^([a-z]+)(?<!(bcache|md|dm))([0-9]+)', r'\1/\1\2', name)
return os.path.join('/sys/block/', dev)
def _bdev(dev=None):
'''
Resolve a bcacheX or cache to a real dev
:return: basename of bcache dev
'''
if dev is None:
dev = _fssys('cache0')
else:
dev = _bcpath(dev)
if not dev:
return False
else:
return _devbase(os.path.dirname(dev))
def _bcpath(dev):
'''
Full SysFS path of a bcache device
'''
return os.path.join(_syspath(dev), 'bcache')
def _fspath():
'''
:return: path of active bcache
'''
cuuid = uuid()
if not cuuid:
return False
else:
return os.path.join('/sys/fs/bcache/', cuuid)
def _bcsys(dev, name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with backing devs SysFS
'''
return _sysfs_attr([_bcpath(dev), name], value, log_lvl, log_msg)
def _sysfs_attr(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper with logging around sysfs.attr
'''
if isinstance(name, six.string_types):
name = [name]
res = __salt__['sysfs.attr'](os.path.join(*name), value)
if not res and log_lvl is not None and log_msg is not None:
log.log(LOG[log_lvl], log_msg)
return res
def _sysfs_parse(path, base_attr=None, stats=False, config=False, internals=False, options=False):
'''
Helper function for parsing BCache's SysFS interface
'''
result = {}
# ---------------- Parse through the interfaces list ----------------
intfs = __salt__['sysfs.interfaces'](path)
# Actions, we ignore
del intfs['w']
# -------- Sorting hat --------
binkeys = []
if internals:
binkeys.extend(['inter_ro', 'inter_rw'])
if config:
binkeys.append('config')
if stats:
binkeys.append('stats')
bintf = {}
for key in binkeys:
bintf[key] = []
for intf in intfs['r']:
if intf.startswith('internal'):
key = 'inter_ro'
elif 'stats' in intf:
key = 'stats'
else:
# What to do with these???
# I'll utilize 'inter_ro' as 'misc' as well
key = 'inter_ro'
if key in bintf:
bintf[key].append(intf)
for intf in intfs['rw']:
if intf.startswith('internal'):
key = 'inter_rw'
else:
key = 'config'
if key in bintf:
bintf[key].append(intf)
if base_attr is not None:
for intf in bintf:
bintf[intf] = [sintf for sintf in bintf[intf] if sintf not in base_attr]
bintf['base'] = base_attr
mods = {
'stats': ['internal/bset_tree_stats', 'writeback_rate_debug', 'metadata_written', 'nbuckets', 'written',
'average_key_size', 'btree_cache_size'],
}
for modt, modlist in mods.items():
found = []
if modt not in bintf:
continue
for mod in modlist:
for intflist in bintf.values():
if mod in intflist:
found.append(mod)
intflist.remove(mod)
bintf[modt] += found
# -------- Fetch SysFS vals --------
bintflist = [intf for iflist in bintf.values() for intf in iflist]
result.update(__salt__['sysfs.read'](bintflist, path))
# -------- Parse through well known string lists --------
for strlist in ('writeback_rate_debug', 'internal/bset_tree_stats', 'priority_stats'):
if strlist in result:
listres = {}
for line in result[strlist].split('\n'):
key, val = line.split(':', 1)
val = val.strip()
try:
val = int(val)
except Exception:
try:
val = float(val)
except Exception:
pass
listres[key.strip()] = val
result[strlist] = listres
# -------- Parse through selection lists --------
if not options:
for sellist in ('cache_mode', 'cache_replacement_policy', 'errors'):
if sellist in result:
result[sellist] = re.search(r'\[(.+)\]', result[sellist]).groups()[0]
# -------- Parse through well known bools --------
for boolkey in ('running', 'writeback_running', 'congested'):
if boolkey in result:
result[boolkey] = bool(result[boolkey])
# -------- Recategorize results --------
bresult = {}
for iftype, intflist in bintf.items():
ifres = {}
for intf in intflist:
if intf in result:
ifres[intf] = result.pop(intf)
if ifres:
bresult[iftype] = ifres
return bresult
def _size_map(size):
'''
Map Bcache's size strings to real bytes
'''
try:
# I know, I know, EAFP.
# But everything else is reason for None
if not isinstance(size, int):
if re.search(r'[Kk]', size):
size = 1024 * float(re.sub(r'[Kk]', '', size))
elif re.search(r'[Mm]', size):
size = 1024**2 * float(re.sub(r'[Mm]', '', size))
size = int(size)
return size
except Exception:
return None
def _sizes(dev):
'''
Return neigh useless sizing info about a blockdev
:return: (total size in blocks, blocksize, maximum discard size in bytes)
'''
dev = _devbase(dev)
# standarization yay
block_sizes = ('hw_sector_size', 'minimum_io_size', 'physical_block_size', 'logical_block_size')
discard_sizes = ('discard_max_bytes', 'discard_max_hw_bytes', )
sysfs = __salt__['sysfs.read'](
('size',
'queue/hw_sector_size', '../queue/hw_sector_size',
'queue/discard_max_bytes', '../queue/discard_max_bytes'),
root=_syspath(dev))
# TODO: makes no sense
# First of all, it has to be a power of 2
# Secondly, this returns 4GiB - 512b on Intel 3500's for some weird reason
# discard_granularity seems in bytes, resolves to 512b ???
# max_hw_sectors_kb???
# There's also discard_max_hw_bytes more recently
# See: https://www.kernel.org/doc/Documentation/block/queue-sysfs.txt
# Also, I cant find any docs yet regarding bucket sizes;
# it's supposed to be discard_max_hw_bytes,
# but no way to figure that one reliably out apparently
discard = sysfs.get('queue/discard_max_bytes', sysfs.get('../queue/discard_max_bytes', None))
block = sysfs.get('queue/hw_sector_size', sysfs.get('../queue/hw_sector_size', None))
return 512*sysfs['size'], block, discard
def _wipe(dev):
'''
REALLY DESTRUCTIVE STUFF RIGHT AHEAD
'''
endres = 0
dev = _devbase(dev)
size, block, discard = _sizes(dev)
if discard is None:
log.error('Unable to read SysFS props for %s', dev)
return None
elif not discard:
log.warning('%s seems unable to discard', dev)
wiper = 'dd'
elif not HAS_BLKDISCARD:
log.warning('blkdiscard binary not available, properly wipe the dev manually for optimal results')
wiper = 'dd'
else:
wiper = 'blkdiscard'
wipe_failmsg = 'Error wiping {0}: %s'.format(dev)
if wiper == 'dd':
blocks = 4
cmd = 'dd if=/dev/zero of=/dev/{0} bs=1M count={1}'.format(dev, blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# Some stuff (<cough>GPT</cough>) writes stuff at the end of a dev as well
cmd += ' seek={0}'.format((size/1024**2) - blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
elif wiper == 'blkdiscard':
cmd = 'blkdiscard /dev/{0}'.format(dev)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# TODO: fix annoying bug failing blkdiscard by trying to discard 1 sector past blkdev
endres = 1
return endres > 0
def _wait(lfunc, log_lvl=None, log_msg=None, tries=10):
'''
Wait for lfunc to be True
:return: True if lfunc succeeded within tries, False if it didn't
'''
i = 0
while i < tries:
time.sleep(1)
if lfunc():
return True
else:
i += 1
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg)
return False
def _run_all(cmd, log_lvl=None, log_msg=None, exitcode=0):
'''
Simple wrapper around cmd.run_all
log_msg can contain {0} for stderr
:return: True or stdout, False if retcode wasn't exitcode
'''
res = __salt__['cmd.run_all'](cmd)
if res['retcode'] == exitcode:
if res['stdout']:
return res['stdout']
else:
return True
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg, res['stderr'])
return False
def _alltrue(resdict):
if resdict is None:
return True
return len([val for val in resdict.values() if val]) > 0
|
saltstack/salt
|
salt/modules/bcache.py
|
_bcsys
|
python
|
def _bcsys(dev, name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with backing devs SysFS
'''
return _sysfs_attr([_bcpath(dev), name], value, log_lvl, log_msg)
|
Simple wrapper to interface with backing devs SysFS
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bcache.py#L697-L701
|
[
"def _sysfs_attr(name, value=None, log_lvl=None, log_msg=None):\n '''\n Simple wrapper with logging around sysfs.attr\n '''\n if isinstance(name, six.string_types):\n name = [name]\n res = __salt__['sysfs.attr'](os.path.join(*name), value)\n if not res and log_lvl is not None and log_msg is not None:\n log.log(LOG[log_lvl], log_msg)\n return res\n",
"def _bcpath(dev):\n '''\n Full SysFS path of a bcache device\n '''\n return os.path.join(_syspath(dev), 'bcache')\n"
] |
# -*- coding: utf-8 -*-
'''
Module for managing BCache sets
BCache is a block-level caching mechanism similar to ZFS L2ARC/ZIL, dm-cache and fscache.
It works by formatting one block device as a cache set, then adding backend devices
(which need to be formatted as such) to the set and activating them.
It's available in Linux mainline kernel since 3.10
https://www.kernel.org/doc/Documentation/bcache.txt
This module needs the bcache userspace tools to function.
.. versionadded: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import time
import re
from salt.ext import six
# Import salt libs
import salt.utils.path
log = logging.getLogger(__name__)
LOG = {
'trace': logging.TRACE,
'debug': logging.DEBUG,
'info': logging.INFO,
'warn': logging.WARNING,
'error': logging.ERROR,
'crit': logging.CRITICAL,
}
__func_alias__ = {
'attach_': 'attach',
'config_': 'config',
'super_': 'super',
}
HAS_BLKDISCARD = salt.utils.path.which('blkdiscard') is not None
def __virtual__():
'''
Only work when make-bcache is installed
'''
return salt.utils.path.which('make-bcache') is not None
def uuid(dev=None):
'''
Return the bcache UUID of a block device.
If no device is given, the Cache UUID is returned.
CLI example:
.. code-block:: bash
salt '*' bcache.uuid
salt '*' bcache.uuid /dev/sda
salt '*' bcache.uuid bcache0
'''
try:
if dev is None:
# take the only directory in /sys/fs/bcache and return it's basename
return list(salt.utils.path.os_walk('/sys/fs/bcache/'))[0][1][0]
else:
# basename of the /sys/block/{dev}/bcache/cache symlink target
return os.path.basename(_bcsys(dev, 'cache'))
except Exception:
return False
def attach_(dev=None):
'''
Attach a backing devices to a cache set
If no dev is given, all backing devices will be attached.
CLI example:
.. code-block:: bash
salt '*' bcache.attach sdc
salt '*' bcache.attach /dev/bcache1
:return: bool or None if nuttin' happened
'''
cache = uuid()
if not cache:
log.error('No cache to attach %s to', dev)
return False
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = attach_(dev)
return res if res else None
bcache = uuid(dev)
if bcache:
if bcache == cache:
log.info('%s is already attached to bcache %s, doing nothing', dev, cache)
return None
elif not detach(dev):
return False
log.debug('Attaching %s to bcache %s', dev, cache)
if not _bcsys(dev, 'attach', cache,
'error', 'Error attaching {0} to bcache {1}'.format(dev, cache)):
return False
return _wait(lambda: uuid(dev) == cache,
'error', '{0} received attach to bcache {1}, but did not comply'.format(dev, cache))
def detach(dev=None):
'''
Detach a backing device(s) from a cache set
If no dev is given, all backing devices will be attached.
Detaching a backing device will flush it's write cache.
This should leave the underlying device in a consistent state, but might take a while.
CLI example:
.. code-block:: bash
salt '*' bcache.detach sdc
salt '*' bcache.detach bcache1
'''
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = detach(dev)
return res if res else None
log.debug('Detaching %s', dev)
if not _bcsys(dev, 'detach', 'goaway', 'error', 'Error detaching {0}'.format(dev)):
return False
return _wait(lambda: uuid(dev) is False, 'error', '{0} received detach, but did not comply'.format(dev), 300)
def start():
'''
Trigger a start of the full bcache system through udev.
CLI example:
.. code-block:: bash
salt '*' bcache.start
'''
if not _run_all('udevadm trigger', 'error', 'Error starting bcache: %s'):
return False
elif not _wait(lambda: uuid() is not False, 'warn', 'Bcache system started, but no active cache set found.'):
return False
return True
def stop(dev=None):
'''
Stop a bcache device
If no device is given, all backing devices will be detached from the cache, which will subsequently be stopped.
.. warning::
'Stop' on an individual backing device means hard-stop;
no attempt at flushing will be done and the bcache device will seemingly 'disappear' from the device lists
CLI example:
.. code-block:: bash
salt '*' bcache.stop
'''
if dev is not None:
log.warning('Stopping %s, device will only reappear after reregistering!', dev)
if not _bcsys(dev, 'stop', 'goaway', 'error', 'Error stopping {0}'.format(dev)):
return False
return _wait(lambda: _sysfs_attr(_bcpath(dev)) is False, 'error', 'Device {0} did not stop'.format(dev), 300)
else:
cache = uuid()
if not cache:
log.warning('bcache already stopped?')
return None
if not _alltrue(detach()):
return False
elif not _fssys('stop', 'goaway', 'error', 'Error stopping cache'):
return False
return _wait(lambda: uuid() is False, 'error', 'Cache did not stop', 300)
def back_make(dev, cache_mode='writeback', force=False, attach=True, bucket_size=None):
'''
Create a backing device for attachment to a set.
Because the block size must be the same, a cache set already needs to exist.
CLI example:
.. code-block:: bash
salt '*' bcache.back_make sdc cache_mode=writeback attach=True
:param cache_mode: writethrough, writeback, writearound or none.
:param force: Overwrite existing bcaches
:param attach: Immediately attach the backing device to the set
:param bucket_size: Size of a bucket (see kernel doc)
'''
# pylint: disable=too-many-return-statements
cache = uuid()
if not cache:
log.error('No bcache set found')
return False
elif _sysfs_attr(_bcpath(dev)):
if not force:
log.error('%s already contains a bcache. Wipe it manually or use force', dev)
return False
elif uuid(dev) and not detach(dev):
return False
elif not stop(dev):
return False
dev = _devpath(dev)
block_size = _size_map(_fssys('block_size'))
# You might want to override, we pick the cache set's as sane default
if bucket_size is None:
bucket_size = _size_map(_fssys('bucket_size'))
cmd = 'make-bcache --block {0} --bucket {1} --{2} --bdev {3}'.format(block_size, bucket_size, cache_mode, dev)
if force:
cmd += ' --wipe-bcache'
if not _run_all(cmd, 'error', 'Error creating backing device {0}: %s'.format(dev)):
return False
elif not _sysfs_attr('fs/bcache/register', _devpath(dev),
'error', 'Error registering backing device {0}'.format(dev)):
return False
elif not _wait(lambda: _sysfs_attr(_bcpath(dev)) is not False,
'error', 'Backing device {0} did not register'.format(dev)):
return False
elif attach:
return attach_(dev)
return True
def cache_make(dev, reserved=None, force=False, block_size=None, bucket_size=None, attach=True):
'''
Create BCache cache on a block device.
If blkdiscard is available the entire device will be properly cleared in advance.
CLI example:
.. code-block:: bash
salt '*' bcache.cache_make sdb reserved=10% block_size=4096
:param reserved: if dev is a full device, create a partition table with this size empty.
.. note::
this increases the amount of reserved space available to SSD garbage collectors,
potentially (vastly) increasing performance
:param block_size: Block size of the cache; defaults to devices' logical block size
:param force: Overwrite existing BCache sets
:param attach: Attach all existing backend devices immediately
'''
# TODO: multiple devs == md jbod
# pylint: disable=too-many-return-statements
# ---------------- Preflight checks ----------------
cache = uuid()
if cache:
if not force:
log.error('BCache cache %s is already on the system', cache)
return False
cache = _bdev()
dev = _devbase(dev)
udev = __salt__['udev.env'](dev)
if ('ID_FS_TYPE' in udev or (udev.get('DEVTYPE', None) != 'partition' and 'ID_PART_TABLE_TYPE' in udev)) \
and not force:
log.error('%s already contains data, wipe first or force', dev)
return False
elif reserved is not None and udev.get('DEVTYPE', None) != 'disk':
log.error('Need a partitionable blockdev for reserved to work')
return False
_, block, bucket = _sizes(dev)
if bucket_size is None:
bucket_size = bucket
# TODO: bucket from _sizes() makes no sense
bucket_size = False
if block_size is None:
block_size = block
# ---------------- Still here, start doing destructive stuff ----------------
if cache:
if not stop():
return False
# Wipe the current cache device as well,
# forever ruining any chance of it accidentally popping up again
elif not _wipe(cache):
return False
# Can't do enough wiping
if not _wipe(dev):
return False
if reserved:
cmd = 'parted -m -s -a optimal -- ' \
'/dev/{0} mklabel gpt mkpart bcache-reserved 1M {1} mkpart bcache {1} 100%'.format(dev, reserved)
# if wipe was incomplete & part layout remains the same,
# this is one condition set where udev would make it accidentally popup again
if not _run_all(cmd, 'error', 'Error creating bcache partitions on {0}: %s'.format(dev)):
return False
dev = '{0}2'.format(dev)
# ---------------- Finally, create a cache ----------------
cmd = 'make-bcache --cache /dev/{0} --block {1} --wipe-bcache'.format(dev, block_size)
# Actually bucket_size should always have a value, but for testing 0 is possible as well
if bucket_size:
cmd += ' --bucket {0}'.format(bucket_size)
if not _run_all(cmd, 'error', 'Error creating cache {0}: %s'.format(dev)):
return False
elif not _wait(lambda: uuid() is not False,
'error', 'Cache {0} seemingly created OK, but FS did not activate'.format(dev)):
return False
if attach:
return _alltrue(attach_())
else:
return True
def config_(dev=None, **kwargs):
'''
Show or update config of a bcache device.
If no device is given, operate on the cache set itself.
CLI example:
.. code-block:: bash
salt '*' bcache.config
salt '*' bcache.config bcache1
salt '*' bcache.config errors=panic journal_delay_ms=150
salt '*' bcache.config bcache1 cache_mode=writeback writeback_percent=15
:return: config or True/False
'''
if dev is None:
spath = _fspath()
else:
spath = _bcpath(dev)
# filter out 'hidden' kwargs added by our favourite orchestration system
updates = dict([(key, val) for key, val in kwargs.items() if not key.startswith('__')])
if updates:
endres = 0
for key, val in updates.items():
endres += _sysfs_attr([spath, key], val,
'warn', 'Failed to update {0} with {1}'.format(os.path.join(spath, key), val))
return endres > 0
else:
result = {}
data = _sysfs_parse(spath, config=True, internals=True, options=True)
for key in ('other_ro', 'inter_ro'):
if key in data:
del data[key]
for key in data:
result.update(data[key])
return result
def status(stats=False, config=False, internals=False, superblock=False, alldevs=False):
'''
Show the full status of the BCache system and optionally all it's involved devices
CLI example:
.. code-block:: bash
salt '*' bcache.status
salt '*' bcache.status stats=True
salt '*' bcache.status internals=True alldevs=True
:param stats: include statistics
:param config: include settings
:param internals: include internals
:param superblock: include superblock
'''
bdevs = []
for _, links, _ in salt.utils.path.os_walk('/sys/block/'):
for block in links:
if 'bcache' in block:
continue
for spath, sdirs, _ in salt.utils.path.os_walk('/sys/block/{0}'.format(block), followlinks=False):
if 'bcache' in sdirs:
bdevs.append(os.path.basename(spath))
statii = {}
for bcache in bdevs:
statii[bcache] = device(bcache, stats, config, internals, superblock)
cuuid = uuid()
cdev = _bdev()
if cdev:
count = 0
for dev in statii:
if dev != cdev:
# it's a backing dev
if statii[dev]['cache'] == cuuid:
count += 1
statii[cdev]['attached_backing_devices'] = count
if not alldevs:
statii = statii[cdev]
return statii
def device(dev, stats=False, config=False, internals=False, superblock=False):
'''
Check the state of a single bcache device
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc stats=True
:param stats: include statistics
:param settings: include all settings
:param internals: include all internals
:param superblock: include superblock info
'''
result = {}
if not _sysfs_attr(_bcpath(dev), None, 'error', '{0} is not a bcache fo any kind'.format(dev)):
return False
elif _bcsys(dev, 'set'):
# ---------------- It's the cache itself ----------------
result['uuid'] = uuid()
base_attr = ['block_size', 'bucket_size', 'cache_available_percent', 'cache_replacement_policy', 'congested']
# ---------------- Parse through both the blockdev & the FS ----------------
result.update(_sysfs_parse(_bcpath(dev), base_attr, stats, config, internals))
result.update(_sysfs_parse(_fspath(), base_attr, stats, config, internals))
result.update(result.pop('base'))
else:
# ---------------- It's a backing device ----------------
back_uuid = uuid(dev)
if back_uuid is not None:
result['cache'] = back_uuid
try:
result['dev'] = os.path.basename(_bcsys(dev, 'dev'))
except Exception:
pass
result['bdev'] = _bdev(dev)
base_attr = ['cache_mode', 'running', 'state', 'writeback_running']
base_path = _bcpath(dev)
result.update(_sysfs_parse(base_path, base_attr, stats, config, internals))
result.update(result.pop('base'))
# ---------------- Modifications ----------------
state = [result['state']]
if result.pop('running'):
state.append('running')
else:
state.append('stopped')
if 'writeback_running' in result:
if result.pop('writeback_running'):
state.append('writeback_running')
else:
state.append('writeback_stopped')
result['state'] = state
# ---------------- Statistics ----------------
if 'stats' in result:
replre = r'(stats|cache)_'
statres = result['stats']
for attr in result['stats']:
if '/' not in attr:
key = re.sub(replre, '', attr)
statres[key] = statres.pop(attr)
else:
stat, key = attr.split('/', 1)
stat = re.sub(replre, '', stat)
key = re.sub(replre, '', key)
if stat not in statres:
statres[stat] = {}
statres[stat][key] = statres.pop(attr)
result['stats'] = statres
# ---------------- Internals ----------------
if internals:
interres = result.pop('inter_ro', {})
interres.update(result.pop('inter_rw', {}))
if interres:
for key in interres:
if key.startswith('internal'):
nkey = re.sub(r'internal[s/]*', '', key)
interres[nkey] = interres.pop(key)
key = nkey
if key.startswith(('btree', 'writeback')):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in interres:
interres[mkey] = {}
interres[mkey][skey] = interres.pop(key)
result['internals'] = interres
# ---------------- Config ----------------
if config:
configres = result['config']
for key in configres:
if key.startswith('writeback'):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in configres:
configres[mkey] = {}
configres[mkey][skey] = configres.pop(key)
result['config'] = configres
# ---------------- Superblock ----------------
if superblock:
result['superblock'] = super_(dev)
return result
def super_(dev):
'''
Read out BCache SuperBlock
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc
'''
dev = _devpath(dev)
ret = {}
res = _run_all('bcache-super-show {0}'.format(dev), 'error', 'Error reading superblock on {0}: %s'.format(dev))
if not res:
return False
for line in res.splitlines(): # pylint: disable=no-member
line = line.strip()
if not line:
continue
key, val = [val.strip() for val in re.split(r'[\s]+', line, maxsplit=1)]
if not (key and val):
continue
mval = None
if ' ' in val:
rval, mval = [val.strip() for val in re.split(r'[\s]+', val, maxsplit=1)]
mval = mval[1:-1]
else:
rval = val
try:
rval = int(rval)
except Exception:
try:
rval = float(rval)
except Exception:
if rval == 'yes':
rval = True
elif rval == 'no':
rval = False
pkey, key = re.split(r'\.', key, maxsplit=1)
if pkey not in ret:
ret[pkey] = {}
if mval is not None:
ret[pkey][key] = (rval, mval)
else:
ret[pkey][key] = rval
return ret
# -------------------------------- HELPER FUNCTIONS --------------------------------
def _devbase(dev):
'''
Basename of just about any dev
'''
dev = os.path.realpath(os.path.expandvars(dev))
dev = os.path.basename(dev)
return dev
def _devpath(dev):
'''
Return /dev name of just about any dev
:return: /dev/devicename
'''
return os.path.join('/dev', _devbase(dev))
def _syspath(dev):
'''
Full SysFS path of a device
'''
dev = _devbase(dev)
dev = re.sub(r'^([vhs][a-z]+)([0-9]+)', r'\1/\1\2', dev)
# name = re.sub(r'^([a-z]+)(?<!(bcache|md|dm))([0-9]+)', r'\1/\1\2', name)
return os.path.join('/sys/block/', dev)
def _bdev(dev=None):
'''
Resolve a bcacheX or cache to a real dev
:return: basename of bcache dev
'''
if dev is None:
dev = _fssys('cache0')
else:
dev = _bcpath(dev)
if not dev:
return False
else:
return _devbase(os.path.dirname(dev))
def _bcpath(dev):
'''
Full SysFS path of a bcache device
'''
return os.path.join(_syspath(dev), 'bcache')
def _fspath():
'''
:return: path of active bcache
'''
cuuid = uuid()
if not cuuid:
return False
else:
return os.path.join('/sys/fs/bcache/', cuuid)
def _fssys(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with bcache SysFS
'''
fspath = _fspath()
if not fspath:
return False
else:
return _sysfs_attr([fspath, name], value, log_lvl, log_msg)
def _sysfs_attr(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper with logging around sysfs.attr
'''
if isinstance(name, six.string_types):
name = [name]
res = __salt__['sysfs.attr'](os.path.join(*name), value)
if not res and log_lvl is not None and log_msg is not None:
log.log(LOG[log_lvl], log_msg)
return res
def _sysfs_parse(path, base_attr=None, stats=False, config=False, internals=False, options=False):
'''
Helper function for parsing BCache's SysFS interface
'''
result = {}
# ---------------- Parse through the interfaces list ----------------
intfs = __salt__['sysfs.interfaces'](path)
# Actions, we ignore
del intfs['w']
# -------- Sorting hat --------
binkeys = []
if internals:
binkeys.extend(['inter_ro', 'inter_rw'])
if config:
binkeys.append('config')
if stats:
binkeys.append('stats')
bintf = {}
for key in binkeys:
bintf[key] = []
for intf in intfs['r']:
if intf.startswith('internal'):
key = 'inter_ro'
elif 'stats' in intf:
key = 'stats'
else:
# What to do with these???
# I'll utilize 'inter_ro' as 'misc' as well
key = 'inter_ro'
if key in bintf:
bintf[key].append(intf)
for intf in intfs['rw']:
if intf.startswith('internal'):
key = 'inter_rw'
else:
key = 'config'
if key in bintf:
bintf[key].append(intf)
if base_attr is not None:
for intf in bintf:
bintf[intf] = [sintf for sintf in bintf[intf] if sintf not in base_attr]
bintf['base'] = base_attr
mods = {
'stats': ['internal/bset_tree_stats', 'writeback_rate_debug', 'metadata_written', 'nbuckets', 'written',
'average_key_size', 'btree_cache_size'],
}
for modt, modlist in mods.items():
found = []
if modt not in bintf:
continue
for mod in modlist:
for intflist in bintf.values():
if mod in intflist:
found.append(mod)
intflist.remove(mod)
bintf[modt] += found
# -------- Fetch SysFS vals --------
bintflist = [intf for iflist in bintf.values() for intf in iflist]
result.update(__salt__['sysfs.read'](bintflist, path))
# -------- Parse through well known string lists --------
for strlist in ('writeback_rate_debug', 'internal/bset_tree_stats', 'priority_stats'):
if strlist in result:
listres = {}
for line in result[strlist].split('\n'):
key, val = line.split(':', 1)
val = val.strip()
try:
val = int(val)
except Exception:
try:
val = float(val)
except Exception:
pass
listres[key.strip()] = val
result[strlist] = listres
# -------- Parse through selection lists --------
if not options:
for sellist in ('cache_mode', 'cache_replacement_policy', 'errors'):
if sellist in result:
result[sellist] = re.search(r'\[(.+)\]', result[sellist]).groups()[0]
# -------- Parse through well known bools --------
for boolkey in ('running', 'writeback_running', 'congested'):
if boolkey in result:
result[boolkey] = bool(result[boolkey])
# -------- Recategorize results --------
bresult = {}
for iftype, intflist in bintf.items():
ifres = {}
for intf in intflist:
if intf in result:
ifres[intf] = result.pop(intf)
if ifres:
bresult[iftype] = ifres
return bresult
def _size_map(size):
'''
Map Bcache's size strings to real bytes
'''
try:
# I know, I know, EAFP.
# But everything else is reason for None
if not isinstance(size, int):
if re.search(r'[Kk]', size):
size = 1024 * float(re.sub(r'[Kk]', '', size))
elif re.search(r'[Mm]', size):
size = 1024**2 * float(re.sub(r'[Mm]', '', size))
size = int(size)
return size
except Exception:
return None
def _sizes(dev):
'''
Return neigh useless sizing info about a blockdev
:return: (total size in blocks, blocksize, maximum discard size in bytes)
'''
dev = _devbase(dev)
# standarization yay
block_sizes = ('hw_sector_size', 'minimum_io_size', 'physical_block_size', 'logical_block_size')
discard_sizes = ('discard_max_bytes', 'discard_max_hw_bytes', )
sysfs = __salt__['sysfs.read'](
('size',
'queue/hw_sector_size', '../queue/hw_sector_size',
'queue/discard_max_bytes', '../queue/discard_max_bytes'),
root=_syspath(dev))
# TODO: makes no sense
# First of all, it has to be a power of 2
# Secondly, this returns 4GiB - 512b on Intel 3500's for some weird reason
# discard_granularity seems in bytes, resolves to 512b ???
# max_hw_sectors_kb???
# There's also discard_max_hw_bytes more recently
# See: https://www.kernel.org/doc/Documentation/block/queue-sysfs.txt
# Also, I cant find any docs yet regarding bucket sizes;
# it's supposed to be discard_max_hw_bytes,
# but no way to figure that one reliably out apparently
discard = sysfs.get('queue/discard_max_bytes', sysfs.get('../queue/discard_max_bytes', None))
block = sysfs.get('queue/hw_sector_size', sysfs.get('../queue/hw_sector_size', None))
return 512*sysfs['size'], block, discard
def _wipe(dev):
'''
REALLY DESTRUCTIVE STUFF RIGHT AHEAD
'''
endres = 0
dev = _devbase(dev)
size, block, discard = _sizes(dev)
if discard is None:
log.error('Unable to read SysFS props for %s', dev)
return None
elif not discard:
log.warning('%s seems unable to discard', dev)
wiper = 'dd'
elif not HAS_BLKDISCARD:
log.warning('blkdiscard binary not available, properly wipe the dev manually for optimal results')
wiper = 'dd'
else:
wiper = 'blkdiscard'
wipe_failmsg = 'Error wiping {0}: %s'.format(dev)
if wiper == 'dd':
blocks = 4
cmd = 'dd if=/dev/zero of=/dev/{0} bs=1M count={1}'.format(dev, blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# Some stuff (<cough>GPT</cough>) writes stuff at the end of a dev as well
cmd += ' seek={0}'.format((size/1024**2) - blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
elif wiper == 'blkdiscard':
cmd = 'blkdiscard /dev/{0}'.format(dev)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# TODO: fix annoying bug failing blkdiscard by trying to discard 1 sector past blkdev
endres = 1
return endres > 0
def _wait(lfunc, log_lvl=None, log_msg=None, tries=10):
'''
Wait for lfunc to be True
:return: True if lfunc succeeded within tries, False if it didn't
'''
i = 0
while i < tries:
time.sleep(1)
if lfunc():
return True
else:
i += 1
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg)
return False
def _run_all(cmd, log_lvl=None, log_msg=None, exitcode=0):
'''
Simple wrapper around cmd.run_all
log_msg can contain {0} for stderr
:return: True or stdout, False if retcode wasn't exitcode
'''
res = __salt__['cmd.run_all'](cmd)
if res['retcode'] == exitcode:
if res['stdout']:
return res['stdout']
else:
return True
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg, res['stderr'])
return False
def _alltrue(resdict):
if resdict is None:
return True
return len([val for val in resdict.values() if val]) > 0
|
saltstack/salt
|
salt/modules/bcache.py
|
_sysfs_attr
|
python
|
def _sysfs_attr(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper with logging around sysfs.attr
'''
if isinstance(name, six.string_types):
name = [name]
res = __salt__['sysfs.attr'](os.path.join(*name), value)
if not res and log_lvl is not None and log_msg is not None:
log.log(LOG[log_lvl], log_msg)
return res
|
Simple wrapper with logging around sysfs.attr
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bcache.py#L704-L713
| null |
# -*- coding: utf-8 -*-
'''
Module for managing BCache sets
BCache is a block-level caching mechanism similar to ZFS L2ARC/ZIL, dm-cache and fscache.
It works by formatting one block device as a cache set, then adding backend devices
(which need to be formatted as such) to the set and activating them.
It's available in Linux mainline kernel since 3.10
https://www.kernel.org/doc/Documentation/bcache.txt
This module needs the bcache userspace tools to function.
.. versionadded: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import time
import re
from salt.ext import six
# Import salt libs
import salt.utils.path
log = logging.getLogger(__name__)
LOG = {
'trace': logging.TRACE,
'debug': logging.DEBUG,
'info': logging.INFO,
'warn': logging.WARNING,
'error': logging.ERROR,
'crit': logging.CRITICAL,
}
__func_alias__ = {
'attach_': 'attach',
'config_': 'config',
'super_': 'super',
}
HAS_BLKDISCARD = salt.utils.path.which('blkdiscard') is not None
def __virtual__():
'''
Only work when make-bcache is installed
'''
return salt.utils.path.which('make-bcache') is not None
def uuid(dev=None):
'''
Return the bcache UUID of a block device.
If no device is given, the Cache UUID is returned.
CLI example:
.. code-block:: bash
salt '*' bcache.uuid
salt '*' bcache.uuid /dev/sda
salt '*' bcache.uuid bcache0
'''
try:
if dev is None:
# take the only directory in /sys/fs/bcache and return it's basename
return list(salt.utils.path.os_walk('/sys/fs/bcache/'))[0][1][0]
else:
# basename of the /sys/block/{dev}/bcache/cache symlink target
return os.path.basename(_bcsys(dev, 'cache'))
except Exception:
return False
def attach_(dev=None):
'''
Attach a backing devices to a cache set
If no dev is given, all backing devices will be attached.
CLI example:
.. code-block:: bash
salt '*' bcache.attach sdc
salt '*' bcache.attach /dev/bcache1
:return: bool or None if nuttin' happened
'''
cache = uuid()
if not cache:
log.error('No cache to attach %s to', dev)
return False
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = attach_(dev)
return res if res else None
bcache = uuid(dev)
if bcache:
if bcache == cache:
log.info('%s is already attached to bcache %s, doing nothing', dev, cache)
return None
elif not detach(dev):
return False
log.debug('Attaching %s to bcache %s', dev, cache)
if not _bcsys(dev, 'attach', cache,
'error', 'Error attaching {0} to bcache {1}'.format(dev, cache)):
return False
return _wait(lambda: uuid(dev) == cache,
'error', '{0} received attach to bcache {1}, but did not comply'.format(dev, cache))
def detach(dev=None):
'''
Detach a backing device(s) from a cache set
If no dev is given, all backing devices will be attached.
Detaching a backing device will flush it's write cache.
This should leave the underlying device in a consistent state, but might take a while.
CLI example:
.. code-block:: bash
salt '*' bcache.detach sdc
salt '*' bcache.detach bcache1
'''
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = detach(dev)
return res if res else None
log.debug('Detaching %s', dev)
if not _bcsys(dev, 'detach', 'goaway', 'error', 'Error detaching {0}'.format(dev)):
return False
return _wait(lambda: uuid(dev) is False, 'error', '{0} received detach, but did not comply'.format(dev), 300)
def start():
'''
Trigger a start of the full bcache system through udev.
CLI example:
.. code-block:: bash
salt '*' bcache.start
'''
if not _run_all('udevadm trigger', 'error', 'Error starting bcache: %s'):
return False
elif not _wait(lambda: uuid() is not False, 'warn', 'Bcache system started, but no active cache set found.'):
return False
return True
def stop(dev=None):
'''
Stop a bcache device
If no device is given, all backing devices will be detached from the cache, which will subsequently be stopped.
.. warning::
'Stop' on an individual backing device means hard-stop;
no attempt at flushing will be done and the bcache device will seemingly 'disappear' from the device lists
CLI example:
.. code-block:: bash
salt '*' bcache.stop
'''
if dev is not None:
log.warning('Stopping %s, device will only reappear after reregistering!', dev)
if not _bcsys(dev, 'stop', 'goaway', 'error', 'Error stopping {0}'.format(dev)):
return False
return _wait(lambda: _sysfs_attr(_bcpath(dev)) is False, 'error', 'Device {0} did not stop'.format(dev), 300)
else:
cache = uuid()
if not cache:
log.warning('bcache already stopped?')
return None
if not _alltrue(detach()):
return False
elif not _fssys('stop', 'goaway', 'error', 'Error stopping cache'):
return False
return _wait(lambda: uuid() is False, 'error', 'Cache did not stop', 300)
def back_make(dev, cache_mode='writeback', force=False, attach=True, bucket_size=None):
'''
Create a backing device for attachment to a set.
Because the block size must be the same, a cache set already needs to exist.
CLI example:
.. code-block:: bash
salt '*' bcache.back_make sdc cache_mode=writeback attach=True
:param cache_mode: writethrough, writeback, writearound or none.
:param force: Overwrite existing bcaches
:param attach: Immediately attach the backing device to the set
:param bucket_size: Size of a bucket (see kernel doc)
'''
# pylint: disable=too-many-return-statements
cache = uuid()
if not cache:
log.error('No bcache set found')
return False
elif _sysfs_attr(_bcpath(dev)):
if not force:
log.error('%s already contains a bcache. Wipe it manually or use force', dev)
return False
elif uuid(dev) and not detach(dev):
return False
elif not stop(dev):
return False
dev = _devpath(dev)
block_size = _size_map(_fssys('block_size'))
# You might want to override, we pick the cache set's as sane default
if bucket_size is None:
bucket_size = _size_map(_fssys('bucket_size'))
cmd = 'make-bcache --block {0} --bucket {1} --{2} --bdev {3}'.format(block_size, bucket_size, cache_mode, dev)
if force:
cmd += ' --wipe-bcache'
if not _run_all(cmd, 'error', 'Error creating backing device {0}: %s'.format(dev)):
return False
elif not _sysfs_attr('fs/bcache/register', _devpath(dev),
'error', 'Error registering backing device {0}'.format(dev)):
return False
elif not _wait(lambda: _sysfs_attr(_bcpath(dev)) is not False,
'error', 'Backing device {0} did not register'.format(dev)):
return False
elif attach:
return attach_(dev)
return True
def cache_make(dev, reserved=None, force=False, block_size=None, bucket_size=None, attach=True):
'''
Create BCache cache on a block device.
If blkdiscard is available the entire device will be properly cleared in advance.
CLI example:
.. code-block:: bash
salt '*' bcache.cache_make sdb reserved=10% block_size=4096
:param reserved: if dev is a full device, create a partition table with this size empty.
.. note::
this increases the amount of reserved space available to SSD garbage collectors,
potentially (vastly) increasing performance
:param block_size: Block size of the cache; defaults to devices' logical block size
:param force: Overwrite existing BCache sets
:param attach: Attach all existing backend devices immediately
'''
# TODO: multiple devs == md jbod
# pylint: disable=too-many-return-statements
# ---------------- Preflight checks ----------------
cache = uuid()
if cache:
if not force:
log.error('BCache cache %s is already on the system', cache)
return False
cache = _bdev()
dev = _devbase(dev)
udev = __salt__['udev.env'](dev)
if ('ID_FS_TYPE' in udev or (udev.get('DEVTYPE', None) != 'partition' and 'ID_PART_TABLE_TYPE' in udev)) \
and not force:
log.error('%s already contains data, wipe first or force', dev)
return False
elif reserved is not None and udev.get('DEVTYPE', None) != 'disk':
log.error('Need a partitionable blockdev for reserved to work')
return False
_, block, bucket = _sizes(dev)
if bucket_size is None:
bucket_size = bucket
# TODO: bucket from _sizes() makes no sense
bucket_size = False
if block_size is None:
block_size = block
# ---------------- Still here, start doing destructive stuff ----------------
if cache:
if not stop():
return False
# Wipe the current cache device as well,
# forever ruining any chance of it accidentally popping up again
elif not _wipe(cache):
return False
# Can't do enough wiping
if not _wipe(dev):
return False
if reserved:
cmd = 'parted -m -s -a optimal -- ' \
'/dev/{0} mklabel gpt mkpart bcache-reserved 1M {1} mkpart bcache {1} 100%'.format(dev, reserved)
# if wipe was incomplete & part layout remains the same,
# this is one condition set where udev would make it accidentally popup again
if not _run_all(cmd, 'error', 'Error creating bcache partitions on {0}: %s'.format(dev)):
return False
dev = '{0}2'.format(dev)
# ---------------- Finally, create a cache ----------------
cmd = 'make-bcache --cache /dev/{0} --block {1} --wipe-bcache'.format(dev, block_size)
# Actually bucket_size should always have a value, but for testing 0 is possible as well
if bucket_size:
cmd += ' --bucket {0}'.format(bucket_size)
if not _run_all(cmd, 'error', 'Error creating cache {0}: %s'.format(dev)):
return False
elif not _wait(lambda: uuid() is not False,
'error', 'Cache {0} seemingly created OK, but FS did not activate'.format(dev)):
return False
if attach:
return _alltrue(attach_())
else:
return True
def config_(dev=None, **kwargs):
'''
Show or update config of a bcache device.
If no device is given, operate on the cache set itself.
CLI example:
.. code-block:: bash
salt '*' bcache.config
salt '*' bcache.config bcache1
salt '*' bcache.config errors=panic journal_delay_ms=150
salt '*' bcache.config bcache1 cache_mode=writeback writeback_percent=15
:return: config or True/False
'''
if dev is None:
spath = _fspath()
else:
spath = _bcpath(dev)
# filter out 'hidden' kwargs added by our favourite orchestration system
updates = dict([(key, val) for key, val in kwargs.items() if not key.startswith('__')])
if updates:
endres = 0
for key, val in updates.items():
endres += _sysfs_attr([spath, key], val,
'warn', 'Failed to update {0} with {1}'.format(os.path.join(spath, key), val))
return endres > 0
else:
result = {}
data = _sysfs_parse(spath, config=True, internals=True, options=True)
for key in ('other_ro', 'inter_ro'):
if key in data:
del data[key]
for key in data:
result.update(data[key])
return result
def status(stats=False, config=False, internals=False, superblock=False, alldevs=False):
'''
Show the full status of the BCache system and optionally all it's involved devices
CLI example:
.. code-block:: bash
salt '*' bcache.status
salt '*' bcache.status stats=True
salt '*' bcache.status internals=True alldevs=True
:param stats: include statistics
:param config: include settings
:param internals: include internals
:param superblock: include superblock
'''
bdevs = []
for _, links, _ in salt.utils.path.os_walk('/sys/block/'):
for block in links:
if 'bcache' in block:
continue
for spath, sdirs, _ in salt.utils.path.os_walk('/sys/block/{0}'.format(block), followlinks=False):
if 'bcache' in sdirs:
bdevs.append(os.path.basename(spath))
statii = {}
for bcache in bdevs:
statii[bcache] = device(bcache, stats, config, internals, superblock)
cuuid = uuid()
cdev = _bdev()
if cdev:
count = 0
for dev in statii:
if dev != cdev:
# it's a backing dev
if statii[dev]['cache'] == cuuid:
count += 1
statii[cdev]['attached_backing_devices'] = count
if not alldevs:
statii = statii[cdev]
return statii
def device(dev, stats=False, config=False, internals=False, superblock=False):
'''
Check the state of a single bcache device
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc stats=True
:param stats: include statistics
:param settings: include all settings
:param internals: include all internals
:param superblock: include superblock info
'''
result = {}
if not _sysfs_attr(_bcpath(dev), None, 'error', '{0} is not a bcache fo any kind'.format(dev)):
return False
elif _bcsys(dev, 'set'):
# ---------------- It's the cache itself ----------------
result['uuid'] = uuid()
base_attr = ['block_size', 'bucket_size', 'cache_available_percent', 'cache_replacement_policy', 'congested']
# ---------------- Parse through both the blockdev & the FS ----------------
result.update(_sysfs_parse(_bcpath(dev), base_attr, stats, config, internals))
result.update(_sysfs_parse(_fspath(), base_attr, stats, config, internals))
result.update(result.pop('base'))
else:
# ---------------- It's a backing device ----------------
back_uuid = uuid(dev)
if back_uuid is not None:
result['cache'] = back_uuid
try:
result['dev'] = os.path.basename(_bcsys(dev, 'dev'))
except Exception:
pass
result['bdev'] = _bdev(dev)
base_attr = ['cache_mode', 'running', 'state', 'writeback_running']
base_path = _bcpath(dev)
result.update(_sysfs_parse(base_path, base_attr, stats, config, internals))
result.update(result.pop('base'))
# ---------------- Modifications ----------------
state = [result['state']]
if result.pop('running'):
state.append('running')
else:
state.append('stopped')
if 'writeback_running' in result:
if result.pop('writeback_running'):
state.append('writeback_running')
else:
state.append('writeback_stopped')
result['state'] = state
# ---------------- Statistics ----------------
if 'stats' in result:
replre = r'(stats|cache)_'
statres = result['stats']
for attr in result['stats']:
if '/' not in attr:
key = re.sub(replre, '', attr)
statres[key] = statres.pop(attr)
else:
stat, key = attr.split('/', 1)
stat = re.sub(replre, '', stat)
key = re.sub(replre, '', key)
if stat not in statres:
statres[stat] = {}
statres[stat][key] = statres.pop(attr)
result['stats'] = statres
# ---------------- Internals ----------------
if internals:
interres = result.pop('inter_ro', {})
interres.update(result.pop('inter_rw', {}))
if interres:
for key in interres:
if key.startswith('internal'):
nkey = re.sub(r'internal[s/]*', '', key)
interres[nkey] = interres.pop(key)
key = nkey
if key.startswith(('btree', 'writeback')):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in interres:
interres[mkey] = {}
interres[mkey][skey] = interres.pop(key)
result['internals'] = interres
# ---------------- Config ----------------
if config:
configres = result['config']
for key in configres:
if key.startswith('writeback'):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in configres:
configres[mkey] = {}
configres[mkey][skey] = configres.pop(key)
result['config'] = configres
# ---------------- Superblock ----------------
if superblock:
result['superblock'] = super_(dev)
return result
def super_(dev):
'''
Read out BCache SuperBlock
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc
'''
dev = _devpath(dev)
ret = {}
res = _run_all('bcache-super-show {0}'.format(dev), 'error', 'Error reading superblock on {0}: %s'.format(dev))
if not res:
return False
for line in res.splitlines(): # pylint: disable=no-member
line = line.strip()
if not line:
continue
key, val = [val.strip() for val in re.split(r'[\s]+', line, maxsplit=1)]
if not (key and val):
continue
mval = None
if ' ' in val:
rval, mval = [val.strip() for val in re.split(r'[\s]+', val, maxsplit=1)]
mval = mval[1:-1]
else:
rval = val
try:
rval = int(rval)
except Exception:
try:
rval = float(rval)
except Exception:
if rval == 'yes':
rval = True
elif rval == 'no':
rval = False
pkey, key = re.split(r'\.', key, maxsplit=1)
if pkey not in ret:
ret[pkey] = {}
if mval is not None:
ret[pkey][key] = (rval, mval)
else:
ret[pkey][key] = rval
return ret
# -------------------------------- HELPER FUNCTIONS --------------------------------
def _devbase(dev):
'''
Basename of just about any dev
'''
dev = os.path.realpath(os.path.expandvars(dev))
dev = os.path.basename(dev)
return dev
def _devpath(dev):
'''
Return /dev name of just about any dev
:return: /dev/devicename
'''
return os.path.join('/dev', _devbase(dev))
def _syspath(dev):
'''
Full SysFS path of a device
'''
dev = _devbase(dev)
dev = re.sub(r'^([vhs][a-z]+)([0-9]+)', r'\1/\1\2', dev)
# name = re.sub(r'^([a-z]+)(?<!(bcache|md|dm))([0-9]+)', r'\1/\1\2', name)
return os.path.join('/sys/block/', dev)
def _bdev(dev=None):
'''
Resolve a bcacheX or cache to a real dev
:return: basename of bcache dev
'''
if dev is None:
dev = _fssys('cache0')
else:
dev = _bcpath(dev)
if not dev:
return False
else:
return _devbase(os.path.dirname(dev))
def _bcpath(dev):
'''
Full SysFS path of a bcache device
'''
return os.path.join(_syspath(dev), 'bcache')
def _fspath():
'''
:return: path of active bcache
'''
cuuid = uuid()
if not cuuid:
return False
else:
return os.path.join('/sys/fs/bcache/', cuuid)
def _fssys(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with bcache SysFS
'''
fspath = _fspath()
if not fspath:
return False
else:
return _sysfs_attr([fspath, name], value, log_lvl, log_msg)
def _bcsys(dev, name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with backing devs SysFS
'''
return _sysfs_attr([_bcpath(dev), name], value, log_lvl, log_msg)
def _sysfs_parse(path, base_attr=None, stats=False, config=False, internals=False, options=False):
'''
Helper function for parsing BCache's SysFS interface
'''
result = {}
# ---------------- Parse through the interfaces list ----------------
intfs = __salt__['sysfs.interfaces'](path)
# Actions, we ignore
del intfs['w']
# -------- Sorting hat --------
binkeys = []
if internals:
binkeys.extend(['inter_ro', 'inter_rw'])
if config:
binkeys.append('config')
if stats:
binkeys.append('stats')
bintf = {}
for key in binkeys:
bintf[key] = []
for intf in intfs['r']:
if intf.startswith('internal'):
key = 'inter_ro'
elif 'stats' in intf:
key = 'stats'
else:
# What to do with these???
# I'll utilize 'inter_ro' as 'misc' as well
key = 'inter_ro'
if key in bintf:
bintf[key].append(intf)
for intf in intfs['rw']:
if intf.startswith('internal'):
key = 'inter_rw'
else:
key = 'config'
if key in bintf:
bintf[key].append(intf)
if base_attr is not None:
for intf in bintf:
bintf[intf] = [sintf for sintf in bintf[intf] if sintf not in base_attr]
bintf['base'] = base_attr
mods = {
'stats': ['internal/bset_tree_stats', 'writeback_rate_debug', 'metadata_written', 'nbuckets', 'written',
'average_key_size', 'btree_cache_size'],
}
for modt, modlist in mods.items():
found = []
if modt not in bintf:
continue
for mod in modlist:
for intflist in bintf.values():
if mod in intflist:
found.append(mod)
intflist.remove(mod)
bintf[modt] += found
# -------- Fetch SysFS vals --------
bintflist = [intf for iflist in bintf.values() for intf in iflist]
result.update(__salt__['sysfs.read'](bintflist, path))
# -------- Parse through well known string lists --------
for strlist in ('writeback_rate_debug', 'internal/bset_tree_stats', 'priority_stats'):
if strlist in result:
listres = {}
for line in result[strlist].split('\n'):
key, val = line.split(':', 1)
val = val.strip()
try:
val = int(val)
except Exception:
try:
val = float(val)
except Exception:
pass
listres[key.strip()] = val
result[strlist] = listres
# -------- Parse through selection lists --------
if not options:
for sellist in ('cache_mode', 'cache_replacement_policy', 'errors'):
if sellist in result:
result[sellist] = re.search(r'\[(.+)\]', result[sellist]).groups()[0]
# -------- Parse through well known bools --------
for boolkey in ('running', 'writeback_running', 'congested'):
if boolkey in result:
result[boolkey] = bool(result[boolkey])
# -------- Recategorize results --------
bresult = {}
for iftype, intflist in bintf.items():
ifres = {}
for intf in intflist:
if intf in result:
ifres[intf] = result.pop(intf)
if ifres:
bresult[iftype] = ifres
return bresult
def _size_map(size):
'''
Map Bcache's size strings to real bytes
'''
try:
# I know, I know, EAFP.
# But everything else is reason for None
if not isinstance(size, int):
if re.search(r'[Kk]', size):
size = 1024 * float(re.sub(r'[Kk]', '', size))
elif re.search(r'[Mm]', size):
size = 1024**2 * float(re.sub(r'[Mm]', '', size))
size = int(size)
return size
except Exception:
return None
def _sizes(dev):
'''
Return neigh useless sizing info about a blockdev
:return: (total size in blocks, blocksize, maximum discard size in bytes)
'''
dev = _devbase(dev)
# standarization yay
block_sizes = ('hw_sector_size', 'minimum_io_size', 'physical_block_size', 'logical_block_size')
discard_sizes = ('discard_max_bytes', 'discard_max_hw_bytes', )
sysfs = __salt__['sysfs.read'](
('size',
'queue/hw_sector_size', '../queue/hw_sector_size',
'queue/discard_max_bytes', '../queue/discard_max_bytes'),
root=_syspath(dev))
# TODO: makes no sense
# First of all, it has to be a power of 2
# Secondly, this returns 4GiB - 512b on Intel 3500's for some weird reason
# discard_granularity seems in bytes, resolves to 512b ???
# max_hw_sectors_kb???
# There's also discard_max_hw_bytes more recently
# See: https://www.kernel.org/doc/Documentation/block/queue-sysfs.txt
# Also, I cant find any docs yet regarding bucket sizes;
# it's supposed to be discard_max_hw_bytes,
# but no way to figure that one reliably out apparently
discard = sysfs.get('queue/discard_max_bytes', sysfs.get('../queue/discard_max_bytes', None))
block = sysfs.get('queue/hw_sector_size', sysfs.get('../queue/hw_sector_size', None))
return 512*sysfs['size'], block, discard
def _wipe(dev):
'''
REALLY DESTRUCTIVE STUFF RIGHT AHEAD
'''
endres = 0
dev = _devbase(dev)
size, block, discard = _sizes(dev)
if discard is None:
log.error('Unable to read SysFS props for %s', dev)
return None
elif not discard:
log.warning('%s seems unable to discard', dev)
wiper = 'dd'
elif not HAS_BLKDISCARD:
log.warning('blkdiscard binary not available, properly wipe the dev manually for optimal results')
wiper = 'dd'
else:
wiper = 'blkdiscard'
wipe_failmsg = 'Error wiping {0}: %s'.format(dev)
if wiper == 'dd':
blocks = 4
cmd = 'dd if=/dev/zero of=/dev/{0} bs=1M count={1}'.format(dev, blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# Some stuff (<cough>GPT</cough>) writes stuff at the end of a dev as well
cmd += ' seek={0}'.format((size/1024**2) - blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
elif wiper == 'blkdiscard':
cmd = 'blkdiscard /dev/{0}'.format(dev)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# TODO: fix annoying bug failing blkdiscard by trying to discard 1 sector past blkdev
endres = 1
return endres > 0
def _wait(lfunc, log_lvl=None, log_msg=None, tries=10):
'''
Wait for lfunc to be True
:return: True if lfunc succeeded within tries, False if it didn't
'''
i = 0
while i < tries:
time.sleep(1)
if lfunc():
return True
else:
i += 1
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg)
return False
def _run_all(cmd, log_lvl=None, log_msg=None, exitcode=0):
'''
Simple wrapper around cmd.run_all
log_msg can contain {0} for stderr
:return: True or stdout, False if retcode wasn't exitcode
'''
res = __salt__['cmd.run_all'](cmd)
if res['retcode'] == exitcode:
if res['stdout']:
return res['stdout']
else:
return True
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg, res['stderr'])
return False
def _alltrue(resdict):
if resdict is None:
return True
return len([val for val in resdict.values() if val]) > 0
|
saltstack/salt
|
salt/modules/bcache.py
|
_sysfs_parse
|
python
|
def _sysfs_parse(path, base_attr=None, stats=False, config=False, internals=False, options=False):
'''
Helper function for parsing BCache's SysFS interface
'''
result = {}
# ---------------- Parse through the interfaces list ----------------
intfs = __salt__['sysfs.interfaces'](path)
# Actions, we ignore
del intfs['w']
# -------- Sorting hat --------
binkeys = []
if internals:
binkeys.extend(['inter_ro', 'inter_rw'])
if config:
binkeys.append('config')
if stats:
binkeys.append('stats')
bintf = {}
for key in binkeys:
bintf[key] = []
for intf in intfs['r']:
if intf.startswith('internal'):
key = 'inter_ro'
elif 'stats' in intf:
key = 'stats'
else:
# What to do with these???
# I'll utilize 'inter_ro' as 'misc' as well
key = 'inter_ro'
if key in bintf:
bintf[key].append(intf)
for intf in intfs['rw']:
if intf.startswith('internal'):
key = 'inter_rw'
else:
key = 'config'
if key in bintf:
bintf[key].append(intf)
if base_attr is not None:
for intf in bintf:
bintf[intf] = [sintf for sintf in bintf[intf] if sintf not in base_attr]
bintf['base'] = base_attr
mods = {
'stats': ['internal/bset_tree_stats', 'writeback_rate_debug', 'metadata_written', 'nbuckets', 'written',
'average_key_size', 'btree_cache_size'],
}
for modt, modlist in mods.items():
found = []
if modt not in bintf:
continue
for mod in modlist:
for intflist in bintf.values():
if mod in intflist:
found.append(mod)
intflist.remove(mod)
bintf[modt] += found
# -------- Fetch SysFS vals --------
bintflist = [intf for iflist in bintf.values() for intf in iflist]
result.update(__salt__['sysfs.read'](bintflist, path))
# -------- Parse through well known string lists --------
for strlist in ('writeback_rate_debug', 'internal/bset_tree_stats', 'priority_stats'):
if strlist in result:
listres = {}
for line in result[strlist].split('\n'):
key, val = line.split(':', 1)
val = val.strip()
try:
val = int(val)
except Exception:
try:
val = float(val)
except Exception:
pass
listres[key.strip()] = val
result[strlist] = listres
# -------- Parse through selection lists --------
if not options:
for sellist in ('cache_mode', 'cache_replacement_policy', 'errors'):
if sellist in result:
result[sellist] = re.search(r'\[(.+)\]', result[sellist]).groups()[0]
# -------- Parse through well known bools --------
for boolkey in ('running', 'writeback_running', 'congested'):
if boolkey in result:
result[boolkey] = bool(result[boolkey])
# -------- Recategorize results --------
bresult = {}
for iftype, intflist in bintf.items():
ifres = {}
for intf in intflist:
if intf in result:
ifres[intf] = result.pop(intf)
if ifres:
bresult[iftype] = ifres
return bresult
|
Helper function for parsing BCache's SysFS interface
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bcache.py#L716-L826
| null |
# -*- coding: utf-8 -*-
'''
Module for managing BCache sets
BCache is a block-level caching mechanism similar to ZFS L2ARC/ZIL, dm-cache and fscache.
It works by formatting one block device as a cache set, then adding backend devices
(which need to be formatted as such) to the set and activating them.
It's available in Linux mainline kernel since 3.10
https://www.kernel.org/doc/Documentation/bcache.txt
This module needs the bcache userspace tools to function.
.. versionadded: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import time
import re
from salt.ext import six
# Import salt libs
import salt.utils.path
log = logging.getLogger(__name__)
LOG = {
'trace': logging.TRACE,
'debug': logging.DEBUG,
'info': logging.INFO,
'warn': logging.WARNING,
'error': logging.ERROR,
'crit': logging.CRITICAL,
}
__func_alias__ = {
'attach_': 'attach',
'config_': 'config',
'super_': 'super',
}
HAS_BLKDISCARD = salt.utils.path.which('blkdiscard') is not None
def __virtual__():
'''
Only work when make-bcache is installed
'''
return salt.utils.path.which('make-bcache') is not None
def uuid(dev=None):
'''
Return the bcache UUID of a block device.
If no device is given, the Cache UUID is returned.
CLI example:
.. code-block:: bash
salt '*' bcache.uuid
salt '*' bcache.uuid /dev/sda
salt '*' bcache.uuid bcache0
'''
try:
if dev is None:
# take the only directory in /sys/fs/bcache and return it's basename
return list(salt.utils.path.os_walk('/sys/fs/bcache/'))[0][1][0]
else:
# basename of the /sys/block/{dev}/bcache/cache symlink target
return os.path.basename(_bcsys(dev, 'cache'))
except Exception:
return False
def attach_(dev=None):
'''
Attach a backing devices to a cache set
If no dev is given, all backing devices will be attached.
CLI example:
.. code-block:: bash
salt '*' bcache.attach sdc
salt '*' bcache.attach /dev/bcache1
:return: bool or None if nuttin' happened
'''
cache = uuid()
if not cache:
log.error('No cache to attach %s to', dev)
return False
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = attach_(dev)
return res if res else None
bcache = uuid(dev)
if bcache:
if bcache == cache:
log.info('%s is already attached to bcache %s, doing nothing', dev, cache)
return None
elif not detach(dev):
return False
log.debug('Attaching %s to bcache %s', dev, cache)
if not _bcsys(dev, 'attach', cache,
'error', 'Error attaching {0} to bcache {1}'.format(dev, cache)):
return False
return _wait(lambda: uuid(dev) == cache,
'error', '{0} received attach to bcache {1}, but did not comply'.format(dev, cache))
def detach(dev=None):
'''
Detach a backing device(s) from a cache set
If no dev is given, all backing devices will be attached.
Detaching a backing device will flush it's write cache.
This should leave the underlying device in a consistent state, but might take a while.
CLI example:
.. code-block:: bash
salt '*' bcache.detach sdc
salt '*' bcache.detach bcache1
'''
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = detach(dev)
return res if res else None
log.debug('Detaching %s', dev)
if not _bcsys(dev, 'detach', 'goaway', 'error', 'Error detaching {0}'.format(dev)):
return False
return _wait(lambda: uuid(dev) is False, 'error', '{0} received detach, but did not comply'.format(dev), 300)
def start():
'''
Trigger a start of the full bcache system through udev.
CLI example:
.. code-block:: bash
salt '*' bcache.start
'''
if not _run_all('udevadm trigger', 'error', 'Error starting bcache: %s'):
return False
elif not _wait(lambda: uuid() is not False, 'warn', 'Bcache system started, but no active cache set found.'):
return False
return True
def stop(dev=None):
'''
Stop a bcache device
If no device is given, all backing devices will be detached from the cache, which will subsequently be stopped.
.. warning::
'Stop' on an individual backing device means hard-stop;
no attempt at flushing will be done and the bcache device will seemingly 'disappear' from the device lists
CLI example:
.. code-block:: bash
salt '*' bcache.stop
'''
if dev is not None:
log.warning('Stopping %s, device will only reappear after reregistering!', dev)
if not _bcsys(dev, 'stop', 'goaway', 'error', 'Error stopping {0}'.format(dev)):
return False
return _wait(lambda: _sysfs_attr(_bcpath(dev)) is False, 'error', 'Device {0} did not stop'.format(dev), 300)
else:
cache = uuid()
if not cache:
log.warning('bcache already stopped?')
return None
if not _alltrue(detach()):
return False
elif not _fssys('stop', 'goaway', 'error', 'Error stopping cache'):
return False
return _wait(lambda: uuid() is False, 'error', 'Cache did not stop', 300)
def back_make(dev, cache_mode='writeback', force=False, attach=True, bucket_size=None):
'''
Create a backing device for attachment to a set.
Because the block size must be the same, a cache set already needs to exist.
CLI example:
.. code-block:: bash
salt '*' bcache.back_make sdc cache_mode=writeback attach=True
:param cache_mode: writethrough, writeback, writearound or none.
:param force: Overwrite existing bcaches
:param attach: Immediately attach the backing device to the set
:param bucket_size: Size of a bucket (see kernel doc)
'''
# pylint: disable=too-many-return-statements
cache = uuid()
if not cache:
log.error('No bcache set found')
return False
elif _sysfs_attr(_bcpath(dev)):
if not force:
log.error('%s already contains a bcache. Wipe it manually or use force', dev)
return False
elif uuid(dev) and not detach(dev):
return False
elif not stop(dev):
return False
dev = _devpath(dev)
block_size = _size_map(_fssys('block_size'))
# You might want to override, we pick the cache set's as sane default
if bucket_size is None:
bucket_size = _size_map(_fssys('bucket_size'))
cmd = 'make-bcache --block {0} --bucket {1} --{2} --bdev {3}'.format(block_size, bucket_size, cache_mode, dev)
if force:
cmd += ' --wipe-bcache'
if not _run_all(cmd, 'error', 'Error creating backing device {0}: %s'.format(dev)):
return False
elif not _sysfs_attr('fs/bcache/register', _devpath(dev),
'error', 'Error registering backing device {0}'.format(dev)):
return False
elif not _wait(lambda: _sysfs_attr(_bcpath(dev)) is not False,
'error', 'Backing device {0} did not register'.format(dev)):
return False
elif attach:
return attach_(dev)
return True
def cache_make(dev, reserved=None, force=False, block_size=None, bucket_size=None, attach=True):
'''
Create BCache cache on a block device.
If blkdiscard is available the entire device will be properly cleared in advance.
CLI example:
.. code-block:: bash
salt '*' bcache.cache_make sdb reserved=10% block_size=4096
:param reserved: if dev is a full device, create a partition table with this size empty.
.. note::
this increases the amount of reserved space available to SSD garbage collectors,
potentially (vastly) increasing performance
:param block_size: Block size of the cache; defaults to devices' logical block size
:param force: Overwrite existing BCache sets
:param attach: Attach all existing backend devices immediately
'''
# TODO: multiple devs == md jbod
# pylint: disable=too-many-return-statements
# ---------------- Preflight checks ----------------
cache = uuid()
if cache:
if not force:
log.error('BCache cache %s is already on the system', cache)
return False
cache = _bdev()
dev = _devbase(dev)
udev = __salt__['udev.env'](dev)
if ('ID_FS_TYPE' in udev or (udev.get('DEVTYPE', None) != 'partition' and 'ID_PART_TABLE_TYPE' in udev)) \
and not force:
log.error('%s already contains data, wipe first or force', dev)
return False
elif reserved is not None and udev.get('DEVTYPE', None) != 'disk':
log.error('Need a partitionable blockdev for reserved to work')
return False
_, block, bucket = _sizes(dev)
if bucket_size is None:
bucket_size = bucket
# TODO: bucket from _sizes() makes no sense
bucket_size = False
if block_size is None:
block_size = block
# ---------------- Still here, start doing destructive stuff ----------------
if cache:
if not stop():
return False
# Wipe the current cache device as well,
# forever ruining any chance of it accidentally popping up again
elif not _wipe(cache):
return False
# Can't do enough wiping
if not _wipe(dev):
return False
if reserved:
cmd = 'parted -m -s -a optimal -- ' \
'/dev/{0} mklabel gpt mkpart bcache-reserved 1M {1} mkpart bcache {1} 100%'.format(dev, reserved)
# if wipe was incomplete & part layout remains the same,
# this is one condition set where udev would make it accidentally popup again
if not _run_all(cmd, 'error', 'Error creating bcache partitions on {0}: %s'.format(dev)):
return False
dev = '{0}2'.format(dev)
# ---------------- Finally, create a cache ----------------
cmd = 'make-bcache --cache /dev/{0} --block {1} --wipe-bcache'.format(dev, block_size)
# Actually bucket_size should always have a value, but for testing 0 is possible as well
if bucket_size:
cmd += ' --bucket {0}'.format(bucket_size)
if not _run_all(cmd, 'error', 'Error creating cache {0}: %s'.format(dev)):
return False
elif not _wait(lambda: uuid() is not False,
'error', 'Cache {0} seemingly created OK, but FS did not activate'.format(dev)):
return False
if attach:
return _alltrue(attach_())
else:
return True
def config_(dev=None, **kwargs):
'''
Show or update config of a bcache device.
If no device is given, operate on the cache set itself.
CLI example:
.. code-block:: bash
salt '*' bcache.config
salt '*' bcache.config bcache1
salt '*' bcache.config errors=panic journal_delay_ms=150
salt '*' bcache.config bcache1 cache_mode=writeback writeback_percent=15
:return: config or True/False
'''
if dev is None:
spath = _fspath()
else:
spath = _bcpath(dev)
# filter out 'hidden' kwargs added by our favourite orchestration system
updates = dict([(key, val) for key, val in kwargs.items() if not key.startswith('__')])
if updates:
endres = 0
for key, val in updates.items():
endres += _sysfs_attr([spath, key], val,
'warn', 'Failed to update {0} with {1}'.format(os.path.join(spath, key), val))
return endres > 0
else:
result = {}
data = _sysfs_parse(spath, config=True, internals=True, options=True)
for key in ('other_ro', 'inter_ro'):
if key in data:
del data[key]
for key in data:
result.update(data[key])
return result
def status(stats=False, config=False, internals=False, superblock=False, alldevs=False):
'''
Show the full status of the BCache system and optionally all it's involved devices
CLI example:
.. code-block:: bash
salt '*' bcache.status
salt '*' bcache.status stats=True
salt '*' bcache.status internals=True alldevs=True
:param stats: include statistics
:param config: include settings
:param internals: include internals
:param superblock: include superblock
'''
bdevs = []
for _, links, _ in salt.utils.path.os_walk('/sys/block/'):
for block in links:
if 'bcache' in block:
continue
for spath, sdirs, _ in salt.utils.path.os_walk('/sys/block/{0}'.format(block), followlinks=False):
if 'bcache' in sdirs:
bdevs.append(os.path.basename(spath))
statii = {}
for bcache in bdevs:
statii[bcache] = device(bcache, stats, config, internals, superblock)
cuuid = uuid()
cdev = _bdev()
if cdev:
count = 0
for dev in statii:
if dev != cdev:
# it's a backing dev
if statii[dev]['cache'] == cuuid:
count += 1
statii[cdev]['attached_backing_devices'] = count
if not alldevs:
statii = statii[cdev]
return statii
def device(dev, stats=False, config=False, internals=False, superblock=False):
'''
Check the state of a single bcache device
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc stats=True
:param stats: include statistics
:param settings: include all settings
:param internals: include all internals
:param superblock: include superblock info
'''
result = {}
if not _sysfs_attr(_bcpath(dev), None, 'error', '{0} is not a bcache fo any kind'.format(dev)):
return False
elif _bcsys(dev, 'set'):
# ---------------- It's the cache itself ----------------
result['uuid'] = uuid()
base_attr = ['block_size', 'bucket_size', 'cache_available_percent', 'cache_replacement_policy', 'congested']
# ---------------- Parse through both the blockdev & the FS ----------------
result.update(_sysfs_parse(_bcpath(dev), base_attr, stats, config, internals))
result.update(_sysfs_parse(_fspath(), base_attr, stats, config, internals))
result.update(result.pop('base'))
else:
# ---------------- It's a backing device ----------------
back_uuid = uuid(dev)
if back_uuid is not None:
result['cache'] = back_uuid
try:
result['dev'] = os.path.basename(_bcsys(dev, 'dev'))
except Exception:
pass
result['bdev'] = _bdev(dev)
base_attr = ['cache_mode', 'running', 'state', 'writeback_running']
base_path = _bcpath(dev)
result.update(_sysfs_parse(base_path, base_attr, stats, config, internals))
result.update(result.pop('base'))
# ---------------- Modifications ----------------
state = [result['state']]
if result.pop('running'):
state.append('running')
else:
state.append('stopped')
if 'writeback_running' in result:
if result.pop('writeback_running'):
state.append('writeback_running')
else:
state.append('writeback_stopped')
result['state'] = state
# ---------------- Statistics ----------------
if 'stats' in result:
replre = r'(stats|cache)_'
statres = result['stats']
for attr in result['stats']:
if '/' not in attr:
key = re.sub(replre, '', attr)
statres[key] = statres.pop(attr)
else:
stat, key = attr.split('/', 1)
stat = re.sub(replre, '', stat)
key = re.sub(replre, '', key)
if stat not in statres:
statres[stat] = {}
statres[stat][key] = statres.pop(attr)
result['stats'] = statres
# ---------------- Internals ----------------
if internals:
interres = result.pop('inter_ro', {})
interres.update(result.pop('inter_rw', {}))
if interres:
for key in interres:
if key.startswith('internal'):
nkey = re.sub(r'internal[s/]*', '', key)
interres[nkey] = interres.pop(key)
key = nkey
if key.startswith(('btree', 'writeback')):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in interres:
interres[mkey] = {}
interres[mkey][skey] = interres.pop(key)
result['internals'] = interres
# ---------------- Config ----------------
if config:
configres = result['config']
for key in configres:
if key.startswith('writeback'):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in configres:
configres[mkey] = {}
configres[mkey][skey] = configres.pop(key)
result['config'] = configres
# ---------------- Superblock ----------------
if superblock:
result['superblock'] = super_(dev)
return result
def super_(dev):
'''
Read out BCache SuperBlock
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc
'''
dev = _devpath(dev)
ret = {}
res = _run_all('bcache-super-show {0}'.format(dev), 'error', 'Error reading superblock on {0}: %s'.format(dev))
if not res:
return False
for line in res.splitlines(): # pylint: disable=no-member
line = line.strip()
if not line:
continue
key, val = [val.strip() for val in re.split(r'[\s]+', line, maxsplit=1)]
if not (key and val):
continue
mval = None
if ' ' in val:
rval, mval = [val.strip() for val in re.split(r'[\s]+', val, maxsplit=1)]
mval = mval[1:-1]
else:
rval = val
try:
rval = int(rval)
except Exception:
try:
rval = float(rval)
except Exception:
if rval == 'yes':
rval = True
elif rval == 'no':
rval = False
pkey, key = re.split(r'\.', key, maxsplit=1)
if pkey not in ret:
ret[pkey] = {}
if mval is not None:
ret[pkey][key] = (rval, mval)
else:
ret[pkey][key] = rval
return ret
# -------------------------------- HELPER FUNCTIONS --------------------------------
def _devbase(dev):
'''
Basename of just about any dev
'''
dev = os.path.realpath(os.path.expandvars(dev))
dev = os.path.basename(dev)
return dev
def _devpath(dev):
'''
Return /dev name of just about any dev
:return: /dev/devicename
'''
return os.path.join('/dev', _devbase(dev))
def _syspath(dev):
'''
Full SysFS path of a device
'''
dev = _devbase(dev)
dev = re.sub(r'^([vhs][a-z]+)([0-9]+)', r'\1/\1\2', dev)
# name = re.sub(r'^([a-z]+)(?<!(bcache|md|dm))([0-9]+)', r'\1/\1\2', name)
return os.path.join('/sys/block/', dev)
def _bdev(dev=None):
'''
Resolve a bcacheX or cache to a real dev
:return: basename of bcache dev
'''
if dev is None:
dev = _fssys('cache0')
else:
dev = _bcpath(dev)
if not dev:
return False
else:
return _devbase(os.path.dirname(dev))
def _bcpath(dev):
'''
Full SysFS path of a bcache device
'''
return os.path.join(_syspath(dev), 'bcache')
def _fspath():
'''
:return: path of active bcache
'''
cuuid = uuid()
if not cuuid:
return False
else:
return os.path.join('/sys/fs/bcache/', cuuid)
def _fssys(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with bcache SysFS
'''
fspath = _fspath()
if not fspath:
return False
else:
return _sysfs_attr([fspath, name], value, log_lvl, log_msg)
def _bcsys(dev, name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with backing devs SysFS
'''
return _sysfs_attr([_bcpath(dev), name], value, log_lvl, log_msg)
def _sysfs_attr(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper with logging around sysfs.attr
'''
if isinstance(name, six.string_types):
name = [name]
res = __salt__['sysfs.attr'](os.path.join(*name), value)
if not res and log_lvl is not None and log_msg is not None:
log.log(LOG[log_lvl], log_msg)
return res
def _size_map(size):
'''
Map Bcache's size strings to real bytes
'''
try:
# I know, I know, EAFP.
# But everything else is reason for None
if not isinstance(size, int):
if re.search(r'[Kk]', size):
size = 1024 * float(re.sub(r'[Kk]', '', size))
elif re.search(r'[Mm]', size):
size = 1024**2 * float(re.sub(r'[Mm]', '', size))
size = int(size)
return size
except Exception:
return None
def _sizes(dev):
'''
Return neigh useless sizing info about a blockdev
:return: (total size in blocks, blocksize, maximum discard size in bytes)
'''
dev = _devbase(dev)
# standarization yay
block_sizes = ('hw_sector_size', 'minimum_io_size', 'physical_block_size', 'logical_block_size')
discard_sizes = ('discard_max_bytes', 'discard_max_hw_bytes', )
sysfs = __salt__['sysfs.read'](
('size',
'queue/hw_sector_size', '../queue/hw_sector_size',
'queue/discard_max_bytes', '../queue/discard_max_bytes'),
root=_syspath(dev))
# TODO: makes no sense
# First of all, it has to be a power of 2
# Secondly, this returns 4GiB - 512b on Intel 3500's for some weird reason
# discard_granularity seems in bytes, resolves to 512b ???
# max_hw_sectors_kb???
# There's also discard_max_hw_bytes more recently
# See: https://www.kernel.org/doc/Documentation/block/queue-sysfs.txt
# Also, I cant find any docs yet regarding bucket sizes;
# it's supposed to be discard_max_hw_bytes,
# but no way to figure that one reliably out apparently
discard = sysfs.get('queue/discard_max_bytes', sysfs.get('../queue/discard_max_bytes', None))
block = sysfs.get('queue/hw_sector_size', sysfs.get('../queue/hw_sector_size', None))
return 512*sysfs['size'], block, discard
def _wipe(dev):
'''
REALLY DESTRUCTIVE STUFF RIGHT AHEAD
'''
endres = 0
dev = _devbase(dev)
size, block, discard = _sizes(dev)
if discard is None:
log.error('Unable to read SysFS props for %s', dev)
return None
elif not discard:
log.warning('%s seems unable to discard', dev)
wiper = 'dd'
elif not HAS_BLKDISCARD:
log.warning('blkdiscard binary not available, properly wipe the dev manually for optimal results')
wiper = 'dd'
else:
wiper = 'blkdiscard'
wipe_failmsg = 'Error wiping {0}: %s'.format(dev)
if wiper == 'dd':
blocks = 4
cmd = 'dd if=/dev/zero of=/dev/{0} bs=1M count={1}'.format(dev, blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# Some stuff (<cough>GPT</cough>) writes stuff at the end of a dev as well
cmd += ' seek={0}'.format((size/1024**2) - blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
elif wiper == 'blkdiscard':
cmd = 'blkdiscard /dev/{0}'.format(dev)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# TODO: fix annoying bug failing blkdiscard by trying to discard 1 sector past blkdev
endres = 1
return endres > 0
def _wait(lfunc, log_lvl=None, log_msg=None, tries=10):
'''
Wait for lfunc to be True
:return: True if lfunc succeeded within tries, False if it didn't
'''
i = 0
while i < tries:
time.sleep(1)
if lfunc():
return True
else:
i += 1
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg)
return False
def _run_all(cmd, log_lvl=None, log_msg=None, exitcode=0):
'''
Simple wrapper around cmd.run_all
log_msg can contain {0} for stderr
:return: True or stdout, False if retcode wasn't exitcode
'''
res = __salt__['cmd.run_all'](cmd)
if res['retcode'] == exitcode:
if res['stdout']:
return res['stdout']
else:
return True
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg, res['stderr'])
return False
def _alltrue(resdict):
if resdict is None:
return True
return len([val for val in resdict.values() if val]) > 0
|
saltstack/salt
|
salt/modules/bcache.py
|
_size_map
|
python
|
def _size_map(size):
'''
Map Bcache's size strings to real bytes
'''
try:
# I know, I know, EAFP.
# But everything else is reason for None
if not isinstance(size, int):
if re.search(r'[Kk]', size):
size = 1024 * float(re.sub(r'[Kk]', '', size))
elif re.search(r'[Mm]', size):
size = 1024**2 * float(re.sub(r'[Mm]', '', size))
size = int(size)
return size
except Exception:
return None
|
Map Bcache's size strings to real bytes
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bcache.py#L829-L844
| null |
# -*- coding: utf-8 -*-
'''
Module for managing BCache sets
BCache is a block-level caching mechanism similar to ZFS L2ARC/ZIL, dm-cache and fscache.
It works by formatting one block device as a cache set, then adding backend devices
(which need to be formatted as such) to the set and activating them.
It's available in Linux mainline kernel since 3.10
https://www.kernel.org/doc/Documentation/bcache.txt
This module needs the bcache userspace tools to function.
.. versionadded: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import time
import re
from salt.ext import six
# Import salt libs
import salt.utils.path
log = logging.getLogger(__name__)
LOG = {
'trace': logging.TRACE,
'debug': logging.DEBUG,
'info': logging.INFO,
'warn': logging.WARNING,
'error': logging.ERROR,
'crit': logging.CRITICAL,
}
__func_alias__ = {
'attach_': 'attach',
'config_': 'config',
'super_': 'super',
}
HAS_BLKDISCARD = salt.utils.path.which('blkdiscard') is not None
def __virtual__():
'''
Only work when make-bcache is installed
'''
return salt.utils.path.which('make-bcache') is not None
def uuid(dev=None):
'''
Return the bcache UUID of a block device.
If no device is given, the Cache UUID is returned.
CLI example:
.. code-block:: bash
salt '*' bcache.uuid
salt '*' bcache.uuid /dev/sda
salt '*' bcache.uuid bcache0
'''
try:
if dev is None:
# take the only directory in /sys/fs/bcache and return it's basename
return list(salt.utils.path.os_walk('/sys/fs/bcache/'))[0][1][0]
else:
# basename of the /sys/block/{dev}/bcache/cache symlink target
return os.path.basename(_bcsys(dev, 'cache'))
except Exception:
return False
def attach_(dev=None):
'''
Attach a backing devices to a cache set
If no dev is given, all backing devices will be attached.
CLI example:
.. code-block:: bash
salt '*' bcache.attach sdc
salt '*' bcache.attach /dev/bcache1
:return: bool or None if nuttin' happened
'''
cache = uuid()
if not cache:
log.error('No cache to attach %s to', dev)
return False
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = attach_(dev)
return res if res else None
bcache = uuid(dev)
if bcache:
if bcache == cache:
log.info('%s is already attached to bcache %s, doing nothing', dev, cache)
return None
elif not detach(dev):
return False
log.debug('Attaching %s to bcache %s', dev, cache)
if not _bcsys(dev, 'attach', cache,
'error', 'Error attaching {0} to bcache {1}'.format(dev, cache)):
return False
return _wait(lambda: uuid(dev) == cache,
'error', '{0} received attach to bcache {1}, but did not comply'.format(dev, cache))
def detach(dev=None):
'''
Detach a backing device(s) from a cache set
If no dev is given, all backing devices will be attached.
Detaching a backing device will flush it's write cache.
This should leave the underlying device in a consistent state, but might take a while.
CLI example:
.. code-block:: bash
salt '*' bcache.detach sdc
salt '*' bcache.detach bcache1
'''
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = detach(dev)
return res if res else None
log.debug('Detaching %s', dev)
if not _bcsys(dev, 'detach', 'goaway', 'error', 'Error detaching {0}'.format(dev)):
return False
return _wait(lambda: uuid(dev) is False, 'error', '{0} received detach, but did not comply'.format(dev), 300)
def start():
'''
Trigger a start of the full bcache system through udev.
CLI example:
.. code-block:: bash
salt '*' bcache.start
'''
if not _run_all('udevadm trigger', 'error', 'Error starting bcache: %s'):
return False
elif not _wait(lambda: uuid() is not False, 'warn', 'Bcache system started, but no active cache set found.'):
return False
return True
def stop(dev=None):
'''
Stop a bcache device
If no device is given, all backing devices will be detached from the cache, which will subsequently be stopped.
.. warning::
'Stop' on an individual backing device means hard-stop;
no attempt at flushing will be done and the bcache device will seemingly 'disappear' from the device lists
CLI example:
.. code-block:: bash
salt '*' bcache.stop
'''
if dev is not None:
log.warning('Stopping %s, device will only reappear after reregistering!', dev)
if not _bcsys(dev, 'stop', 'goaway', 'error', 'Error stopping {0}'.format(dev)):
return False
return _wait(lambda: _sysfs_attr(_bcpath(dev)) is False, 'error', 'Device {0} did not stop'.format(dev), 300)
else:
cache = uuid()
if not cache:
log.warning('bcache already stopped?')
return None
if not _alltrue(detach()):
return False
elif not _fssys('stop', 'goaway', 'error', 'Error stopping cache'):
return False
return _wait(lambda: uuid() is False, 'error', 'Cache did not stop', 300)
def back_make(dev, cache_mode='writeback', force=False, attach=True, bucket_size=None):
'''
Create a backing device for attachment to a set.
Because the block size must be the same, a cache set already needs to exist.
CLI example:
.. code-block:: bash
salt '*' bcache.back_make sdc cache_mode=writeback attach=True
:param cache_mode: writethrough, writeback, writearound or none.
:param force: Overwrite existing bcaches
:param attach: Immediately attach the backing device to the set
:param bucket_size: Size of a bucket (see kernel doc)
'''
# pylint: disable=too-many-return-statements
cache = uuid()
if not cache:
log.error('No bcache set found')
return False
elif _sysfs_attr(_bcpath(dev)):
if not force:
log.error('%s already contains a bcache. Wipe it manually or use force', dev)
return False
elif uuid(dev) and not detach(dev):
return False
elif not stop(dev):
return False
dev = _devpath(dev)
block_size = _size_map(_fssys('block_size'))
# You might want to override, we pick the cache set's as sane default
if bucket_size is None:
bucket_size = _size_map(_fssys('bucket_size'))
cmd = 'make-bcache --block {0} --bucket {1} --{2} --bdev {3}'.format(block_size, bucket_size, cache_mode, dev)
if force:
cmd += ' --wipe-bcache'
if not _run_all(cmd, 'error', 'Error creating backing device {0}: %s'.format(dev)):
return False
elif not _sysfs_attr('fs/bcache/register', _devpath(dev),
'error', 'Error registering backing device {0}'.format(dev)):
return False
elif not _wait(lambda: _sysfs_attr(_bcpath(dev)) is not False,
'error', 'Backing device {0} did not register'.format(dev)):
return False
elif attach:
return attach_(dev)
return True
def cache_make(dev, reserved=None, force=False, block_size=None, bucket_size=None, attach=True):
'''
Create BCache cache on a block device.
If blkdiscard is available the entire device will be properly cleared in advance.
CLI example:
.. code-block:: bash
salt '*' bcache.cache_make sdb reserved=10% block_size=4096
:param reserved: if dev is a full device, create a partition table with this size empty.
.. note::
this increases the amount of reserved space available to SSD garbage collectors,
potentially (vastly) increasing performance
:param block_size: Block size of the cache; defaults to devices' logical block size
:param force: Overwrite existing BCache sets
:param attach: Attach all existing backend devices immediately
'''
# TODO: multiple devs == md jbod
# pylint: disable=too-many-return-statements
# ---------------- Preflight checks ----------------
cache = uuid()
if cache:
if not force:
log.error('BCache cache %s is already on the system', cache)
return False
cache = _bdev()
dev = _devbase(dev)
udev = __salt__['udev.env'](dev)
if ('ID_FS_TYPE' in udev or (udev.get('DEVTYPE', None) != 'partition' and 'ID_PART_TABLE_TYPE' in udev)) \
and not force:
log.error('%s already contains data, wipe first or force', dev)
return False
elif reserved is not None and udev.get('DEVTYPE', None) != 'disk':
log.error('Need a partitionable blockdev for reserved to work')
return False
_, block, bucket = _sizes(dev)
if bucket_size is None:
bucket_size = bucket
# TODO: bucket from _sizes() makes no sense
bucket_size = False
if block_size is None:
block_size = block
# ---------------- Still here, start doing destructive stuff ----------------
if cache:
if not stop():
return False
# Wipe the current cache device as well,
# forever ruining any chance of it accidentally popping up again
elif not _wipe(cache):
return False
# Can't do enough wiping
if not _wipe(dev):
return False
if reserved:
cmd = 'parted -m -s -a optimal -- ' \
'/dev/{0} mklabel gpt mkpart bcache-reserved 1M {1} mkpart bcache {1} 100%'.format(dev, reserved)
# if wipe was incomplete & part layout remains the same,
# this is one condition set where udev would make it accidentally popup again
if not _run_all(cmd, 'error', 'Error creating bcache partitions on {0}: %s'.format(dev)):
return False
dev = '{0}2'.format(dev)
# ---------------- Finally, create a cache ----------------
cmd = 'make-bcache --cache /dev/{0} --block {1} --wipe-bcache'.format(dev, block_size)
# Actually bucket_size should always have a value, but for testing 0 is possible as well
if bucket_size:
cmd += ' --bucket {0}'.format(bucket_size)
if not _run_all(cmd, 'error', 'Error creating cache {0}: %s'.format(dev)):
return False
elif not _wait(lambda: uuid() is not False,
'error', 'Cache {0} seemingly created OK, but FS did not activate'.format(dev)):
return False
if attach:
return _alltrue(attach_())
else:
return True
def config_(dev=None, **kwargs):
'''
Show or update config of a bcache device.
If no device is given, operate on the cache set itself.
CLI example:
.. code-block:: bash
salt '*' bcache.config
salt '*' bcache.config bcache1
salt '*' bcache.config errors=panic journal_delay_ms=150
salt '*' bcache.config bcache1 cache_mode=writeback writeback_percent=15
:return: config or True/False
'''
if dev is None:
spath = _fspath()
else:
spath = _bcpath(dev)
# filter out 'hidden' kwargs added by our favourite orchestration system
updates = dict([(key, val) for key, val in kwargs.items() if not key.startswith('__')])
if updates:
endres = 0
for key, val in updates.items():
endres += _sysfs_attr([spath, key], val,
'warn', 'Failed to update {0} with {1}'.format(os.path.join(spath, key), val))
return endres > 0
else:
result = {}
data = _sysfs_parse(spath, config=True, internals=True, options=True)
for key in ('other_ro', 'inter_ro'):
if key in data:
del data[key]
for key in data:
result.update(data[key])
return result
def status(stats=False, config=False, internals=False, superblock=False, alldevs=False):
'''
Show the full status of the BCache system and optionally all it's involved devices
CLI example:
.. code-block:: bash
salt '*' bcache.status
salt '*' bcache.status stats=True
salt '*' bcache.status internals=True alldevs=True
:param stats: include statistics
:param config: include settings
:param internals: include internals
:param superblock: include superblock
'''
bdevs = []
for _, links, _ in salt.utils.path.os_walk('/sys/block/'):
for block in links:
if 'bcache' in block:
continue
for spath, sdirs, _ in salt.utils.path.os_walk('/sys/block/{0}'.format(block), followlinks=False):
if 'bcache' in sdirs:
bdevs.append(os.path.basename(spath))
statii = {}
for bcache in bdevs:
statii[bcache] = device(bcache, stats, config, internals, superblock)
cuuid = uuid()
cdev = _bdev()
if cdev:
count = 0
for dev in statii:
if dev != cdev:
# it's a backing dev
if statii[dev]['cache'] == cuuid:
count += 1
statii[cdev]['attached_backing_devices'] = count
if not alldevs:
statii = statii[cdev]
return statii
def device(dev, stats=False, config=False, internals=False, superblock=False):
'''
Check the state of a single bcache device
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc stats=True
:param stats: include statistics
:param settings: include all settings
:param internals: include all internals
:param superblock: include superblock info
'''
result = {}
if not _sysfs_attr(_bcpath(dev), None, 'error', '{0} is not a bcache fo any kind'.format(dev)):
return False
elif _bcsys(dev, 'set'):
# ---------------- It's the cache itself ----------------
result['uuid'] = uuid()
base_attr = ['block_size', 'bucket_size', 'cache_available_percent', 'cache_replacement_policy', 'congested']
# ---------------- Parse through both the blockdev & the FS ----------------
result.update(_sysfs_parse(_bcpath(dev), base_attr, stats, config, internals))
result.update(_sysfs_parse(_fspath(), base_attr, stats, config, internals))
result.update(result.pop('base'))
else:
# ---------------- It's a backing device ----------------
back_uuid = uuid(dev)
if back_uuid is not None:
result['cache'] = back_uuid
try:
result['dev'] = os.path.basename(_bcsys(dev, 'dev'))
except Exception:
pass
result['bdev'] = _bdev(dev)
base_attr = ['cache_mode', 'running', 'state', 'writeback_running']
base_path = _bcpath(dev)
result.update(_sysfs_parse(base_path, base_attr, stats, config, internals))
result.update(result.pop('base'))
# ---------------- Modifications ----------------
state = [result['state']]
if result.pop('running'):
state.append('running')
else:
state.append('stopped')
if 'writeback_running' in result:
if result.pop('writeback_running'):
state.append('writeback_running')
else:
state.append('writeback_stopped')
result['state'] = state
# ---------------- Statistics ----------------
if 'stats' in result:
replre = r'(stats|cache)_'
statres = result['stats']
for attr in result['stats']:
if '/' not in attr:
key = re.sub(replre, '', attr)
statres[key] = statres.pop(attr)
else:
stat, key = attr.split('/', 1)
stat = re.sub(replre, '', stat)
key = re.sub(replre, '', key)
if stat not in statres:
statres[stat] = {}
statres[stat][key] = statres.pop(attr)
result['stats'] = statres
# ---------------- Internals ----------------
if internals:
interres = result.pop('inter_ro', {})
interres.update(result.pop('inter_rw', {}))
if interres:
for key in interres:
if key.startswith('internal'):
nkey = re.sub(r'internal[s/]*', '', key)
interres[nkey] = interres.pop(key)
key = nkey
if key.startswith(('btree', 'writeback')):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in interres:
interres[mkey] = {}
interres[mkey][skey] = interres.pop(key)
result['internals'] = interres
# ---------------- Config ----------------
if config:
configres = result['config']
for key in configres:
if key.startswith('writeback'):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in configres:
configres[mkey] = {}
configres[mkey][skey] = configres.pop(key)
result['config'] = configres
# ---------------- Superblock ----------------
if superblock:
result['superblock'] = super_(dev)
return result
def super_(dev):
'''
Read out BCache SuperBlock
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc
'''
dev = _devpath(dev)
ret = {}
res = _run_all('bcache-super-show {0}'.format(dev), 'error', 'Error reading superblock on {0}: %s'.format(dev))
if not res:
return False
for line in res.splitlines(): # pylint: disable=no-member
line = line.strip()
if not line:
continue
key, val = [val.strip() for val in re.split(r'[\s]+', line, maxsplit=1)]
if not (key and val):
continue
mval = None
if ' ' in val:
rval, mval = [val.strip() for val in re.split(r'[\s]+', val, maxsplit=1)]
mval = mval[1:-1]
else:
rval = val
try:
rval = int(rval)
except Exception:
try:
rval = float(rval)
except Exception:
if rval == 'yes':
rval = True
elif rval == 'no':
rval = False
pkey, key = re.split(r'\.', key, maxsplit=1)
if pkey not in ret:
ret[pkey] = {}
if mval is not None:
ret[pkey][key] = (rval, mval)
else:
ret[pkey][key] = rval
return ret
# -------------------------------- HELPER FUNCTIONS --------------------------------
def _devbase(dev):
'''
Basename of just about any dev
'''
dev = os.path.realpath(os.path.expandvars(dev))
dev = os.path.basename(dev)
return dev
def _devpath(dev):
'''
Return /dev name of just about any dev
:return: /dev/devicename
'''
return os.path.join('/dev', _devbase(dev))
def _syspath(dev):
'''
Full SysFS path of a device
'''
dev = _devbase(dev)
dev = re.sub(r'^([vhs][a-z]+)([0-9]+)', r'\1/\1\2', dev)
# name = re.sub(r'^([a-z]+)(?<!(bcache|md|dm))([0-9]+)', r'\1/\1\2', name)
return os.path.join('/sys/block/', dev)
def _bdev(dev=None):
'''
Resolve a bcacheX or cache to a real dev
:return: basename of bcache dev
'''
if dev is None:
dev = _fssys('cache0')
else:
dev = _bcpath(dev)
if not dev:
return False
else:
return _devbase(os.path.dirname(dev))
def _bcpath(dev):
'''
Full SysFS path of a bcache device
'''
return os.path.join(_syspath(dev), 'bcache')
def _fspath():
'''
:return: path of active bcache
'''
cuuid = uuid()
if not cuuid:
return False
else:
return os.path.join('/sys/fs/bcache/', cuuid)
def _fssys(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with bcache SysFS
'''
fspath = _fspath()
if not fspath:
return False
else:
return _sysfs_attr([fspath, name], value, log_lvl, log_msg)
def _bcsys(dev, name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with backing devs SysFS
'''
return _sysfs_attr([_bcpath(dev), name], value, log_lvl, log_msg)
def _sysfs_attr(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper with logging around sysfs.attr
'''
if isinstance(name, six.string_types):
name = [name]
res = __salt__['sysfs.attr'](os.path.join(*name), value)
if not res and log_lvl is not None and log_msg is not None:
log.log(LOG[log_lvl], log_msg)
return res
def _sysfs_parse(path, base_attr=None, stats=False, config=False, internals=False, options=False):
'''
Helper function for parsing BCache's SysFS interface
'''
result = {}
# ---------------- Parse through the interfaces list ----------------
intfs = __salt__['sysfs.interfaces'](path)
# Actions, we ignore
del intfs['w']
# -------- Sorting hat --------
binkeys = []
if internals:
binkeys.extend(['inter_ro', 'inter_rw'])
if config:
binkeys.append('config')
if stats:
binkeys.append('stats')
bintf = {}
for key in binkeys:
bintf[key] = []
for intf in intfs['r']:
if intf.startswith('internal'):
key = 'inter_ro'
elif 'stats' in intf:
key = 'stats'
else:
# What to do with these???
# I'll utilize 'inter_ro' as 'misc' as well
key = 'inter_ro'
if key in bintf:
bintf[key].append(intf)
for intf in intfs['rw']:
if intf.startswith('internal'):
key = 'inter_rw'
else:
key = 'config'
if key in bintf:
bintf[key].append(intf)
if base_attr is not None:
for intf in bintf:
bintf[intf] = [sintf for sintf in bintf[intf] if sintf not in base_attr]
bintf['base'] = base_attr
mods = {
'stats': ['internal/bset_tree_stats', 'writeback_rate_debug', 'metadata_written', 'nbuckets', 'written',
'average_key_size', 'btree_cache_size'],
}
for modt, modlist in mods.items():
found = []
if modt not in bintf:
continue
for mod in modlist:
for intflist in bintf.values():
if mod in intflist:
found.append(mod)
intflist.remove(mod)
bintf[modt] += found
# -------- Fetch SysFS vals --------
bintflist = [intf for iflist in bintf.values() for intf in iflist]
result.update(__salt__['sysfs.read'](bintflist, path))
# -------- Parse through well known string lists --------
for strlist in ('writeback_rate_debug', 'internal/bset_tree_stats', 'priority_stats'):
if strlist in result:
listres = {}
for line in result[strlist].split('\n'):
key, val = line.split(':', 1)
val = val.strip()
try:
val = int(val)
except Exception:
try:
val = float(val)
except Exception:
pass
listres[key.strip()] = val
result[strlist] = listres
# -------- Parse through selection lists --------
if not options:
for sellist in ('cache_mode', 'cache_replacement_policy', 'errors'):
if sellist in result:
result[sellist] = re.search(r'\[(.+)\]', result[sellist]).groups()[0]
# -------- Parse through well known bools --------
for boolkey in ('running', 'writeback_running', 'congested'):
if boolkey in result:
result[boolkey] = bool(result[boolkey])
# -------- Recategorize results --------
bresult = {}
for iftype, intflist in bintf.items():
ifres = {}
for intf in intflist:
if intf in result:
ifres[intf] = result.pop(intf)
if ifres:
bresult[iftype] = ifres
return bresult
def _sizes(dev):
'''
Return neigh useless sizing info about a blockdev
:return: (total size in blocks, blocksize, maximum discard size in bytes)
'''
dev = _devbase(dev)
# standarization yay
block_sizes = ('hw_sector_size', 'minimum_io_size', 'physical_block_size', 'logical_block_size')
discard_sizes = ('discard_max_bytes', 'discard_max_hw_bytes', )
sysfs = __salt__['sysfs.read'](
('size',
'queue/hw_sector_size', '../queue/hw_sector_size',
'queue/discard_max_bytes', '../queue/discard_max_bytes'),
root=_syspath(dev))
# TODO: makes no sense
# First of all, it has to be a power of 2
# Secondly, this returns 4GiB - 512b on Intel 3500's for some weird reason
# discard_granularity seems in bytes, resolves to 512b ???
# max_hw_sectors_kb???
# There's also discard_max_hw_bytes more recently
# See: https://www.kernel.org/doc/Documentation/block/queue-sysfs.txt
# Also, I cant find any docs yet regarding bucket sizes;
# it's supposed to be discard_max_hw_bytes,
# but no way to figure that one reliably out apparently
discard = sysfs.get('queue/discard_max_bytes', sysfs.get('../queue/discard_max_bytes', None))
block = sysfs.get('queue/hw_sector_size', sysfs.get('../queue/hw_sector_size', None))
return 512*sysfs['size'], block, discard
def _wipe(dev):
'''
REALLY DESTRUCTIVE STUFF RIGHT AHEAD
'''
endres = 0
dev = _devbase(dev)
size, block, discard = _sizes(dev)
if discard is None:
log.error('Unable to read SysFS props for %s', dev)
return None
elif not discard:
log.warning('%s seems unable to discard', dev)
wiper = 'dd'
elif not HAS_BLKDISCARD:
log.warning('blkdiscard binary not available, properly wipe the dev manually for optimal results')
wiper = 'dd'
else:
wiper = 'blkdiscard'
wipe_failmsg = 'Error wiping {0}: %s'.format(dev)
if wiper == 'dd':
blocks = 4
cmd = 'dd if=/dev/zero of=/dev/{0} bs=1M count={1}'.format(dev, blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# Some stuff (<cough>GPT</cough>) writes stuff at the end of a dev as well
cmd += ' seek={0}'.format((size/1024**2) - blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
elif wiper == 'blkdiscard':
cmd = 'blkdiscard /dev/{0}'.format(dev)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# TODO: fix annoying bug failing blkdiscard by trying to discard 1 sector past blkdev
endres = 1
return endres > 0
def _wait(lfunc, log_lvl=None, log_msg=None, tries=10):
'''
Wait for lfunc to be True
:return: True if lfunc succeeded within tries, False if it didn't
'''
i = 0
while i < tries:
time.sleep(1)
if lfunc():
return True
else:
i += 1
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg)
return False
def _run_all(cmd, log_lvl=None, log_msg=None, exitcode=0):
'''
Simple wrapper around cmd.run_all
log_msg can contain {0} for stderr
:return: True or stdout, False if retcode wasn't exitcode
'''
res = __salt__['cmd.run_all'](cmd)
if res['retcode'] == exitcode:
if res['stdout']:
return res['stdout']
else:
return True
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg, res['stderr'])
return False
def _alltrue(resdict):
if resdict is None:
return True
return len([val for val in resdict.values() if val]) > 0
|
saltstack/salt
|
salt/modules/bcache.py
|
_sizes
|
python
|
def _sizes(dev):
'''
Return neigh useless sizing info about a blockdev
:return: (total size in blocks, blocksize, maximum discard size in bytes)
'''
dev = _devbase(dev)
# standarization yay
block_sizes = ('hw_sector_size', 'minimum_io_size', 'physical_block_size', 'logical_block_size')
discard_sizes = ('discard_max_bytes', 'discard_max_hw_bytes', )
sysfs = __salt__['sysfs.read'](
('size',
'queue/hw_sector_size', '../queue/hw_sector_size',
'queue/discard_max_bytes', '../queue/discard_max_bytes'),
root=_syspath(dev))
# TODO: makes no sense
# First of all, it has to be a power of 2
# Secondly, this returns 4GiB - 512b on Intel 3500's for some weird reason
# discard_granularity seems in bytes, resolves to 512b ???
# max_hw_sectors_kb???
# There's also discard_max_hw_bytes more recently
# See: https://www.kernel.org/doc/Documentation/block/queue-sysfs.txt
# Also, I cant find any docs yet regarding bucket sizes;
# it's supposed to be discard_max_hw_bytes,
# but no way to figure that one reliably out apparently
discard = sysfs.get('queue/discard_max_bytes', sysfs.get('../queue/discard_max_bytes', None))
block = sysfs.get('queue/hw_sector_size', sysfs.get('../queue/hw_sector_size', None))
return 512*sysfs['size'], block, discard
|
Return neigh useless sizing info about a blockdev
:return: (total size in blocks, blocksize, maximum discard size in bytes)
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bcache.py#L847-L878
|
[
"def _devbase(dev):\n '''\n Basename of just about any dev\n '''\n dev = os.path.realpath(os.path.expandvars(dev))\n dev = os.path.basename(dev)\n return dev\n",
"def _syspath(dev):\n '''\n Full SysFS path of a device\n '''\n dev = _devbase(dev)\n dev = re.sub(r'^([vhs][a-z]+)([0-9]+)', r'\\1/\\1\\2', dev)\n\n # name = re.sub(r'^([a-z]+)(?<!(bcache|md|dm))([0-9]+)', r'\\1/\\1\\2', name)\n return os.path.join('/sys/block/', dev)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for managing BCache sets
BCache is a block-level caching mechanism similar to ZFS L2ARC/ZIL, dm-cache and fscache.
It works by formatting one block device as a cache set, then adding backend devices
(which need to be formatted as such) to the set and activating them.
It's available in Linux mainline kernel since 3.10
https://www.kernel.org/doc/Documentation/bcache.txt
This module needs the bcache userspace tools to function.
.. versionadded: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import time
import re
from salt.ext import six
# Import salt libs
import salt.utils.path
log = logging.getLogger(__name__)
LOG = {
'trace': logging.TRACE,
'debug': logging.DEBUG,
'info': logging.INFO,
'warn': logging.WARNING,
'error': logging.ERROR,
'crit': logging.CRITICAL,
}
__func_alias__ = {
'attach_': 'attach',
'config_': 'config',
'super_': 'super',
}
HAS_BLKDISCARD = salt.utils.path.which('blkdiscard') is not None
def __virtual__():
'''
Only work when make-bcache is installed
'''
return salt.utils.path.which('make-bcache') is not None
def uuid(dev=None):
'''
Return the bcache UUID of a block device.
If no device is given, the Cache UUID is returned.
CLI example:
.. code-block:: bash
salt '*' bcache.uuid
salt '*' bcache.uuid /dev/sda
salt '*' bcache.uuid bcache0
'''
try:
if dev is None:
# take the only directory in /sys/fs/bcache and return it's basename
return list(salt.utils.path.os_walk('/sys/fs/bcache/'))[0][1][0]
else:
# basename of the /sys/block/{dev}/bcache/cache symlink target
return os.path.basename(_bcsys(dev, 'cache'))
except Exception:
return False
def attach_(dev=None):
'''
Attach a backing devices to a cache set
If no dev is given, all backing devices will be attached.
CLI example:
.. code-block:: bash
salt '*' bcache.attach sdc
salt '*' bcache.attach /dev/bcache1
:return: bool or None if nuttin' happened
'''
cache = uuid()
if not cache:
log.error('No cache to attach %s to', dev)
return False
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = attach_(dev)
return res if res else None
bcache = uuid(dev)
if bcache:
if bcache == cache:
log.info('%s is already attached to bcache %s, doing nothing', dev, cache)
return None
elif not detach(dev):
return False
log.debug('Attaching %s to bcache %s', dev, cache)
if not _bcsys(dev, 'attach', cache,
'error', 'Error attaching {0} to bcache {1}'.format(dev, cache)):
return False
return _wait(lambda: uuid(dev) == cache,
'error', '{0} received attach to bcache {1}, but did not comply'.format(dev, cache))
def detach(dev=None):
'''
Detach a backing device(s) from a cache set
If no dev is given, all backing devices will be attached.
Detaching a backing device will flush it's write cache.
This should leave the underlying device in a consistent state, but might take a while.
CLI example:
.. code-block:: bash
salt '*' bcache.detach sdc
salt '*' bcache.detach bcache1
'''
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = detach(dev)
return res if res else None
log.debug('Detaching %s', dev)
if not _bcsys(dev, 'detach', 'goaway', 'error', 'Error detaching {0}'.format(dev)):
return False
return _wait(lambda: uuid(dev) is False, 'error', '{0} received detach, but did not comply'.format(dev), 300)
def start():
'''
Trigger a start of the full bcache system through udev.
CLI example:
.. code-block:: bash
salt '*' bcache.start
'''
if not _run_all('udevadm trigger', 'error', 'Error starting bcache: %s'):
return False
elif not _wait(lambda: uuid() is not False, 'warn', 'Bcache system started, but no active cache set found.'):
return False
return True
def stop(dev=None):
'''
Stop a bcache device
If no device is given, all backing devices will be detached from the cache, which will subsequently be stopped.
.. warning::
'Stop' on an individual backing device means hard-stop;
no attempt at flushing will be done and the bcache device will seemingly 'disappear' from the device lists
CLI example:
.. code-block:: bash
salt '*' bcache.stop
'''
if dev is not None:
log.warning('Stopping %s, device will only reappear after reregistering!', dev)
if not _bcsys(dev, 'stop', 'goaway', 'error', 'Error stopping {0}'.format(dev)):
return False
return _wait(lambda: _sysfs_attr(_bcpath(dev)) is False, 'error', 'Device {0} did not stop'.format(dev), 300)
else:
cache = uuid()
if not cache:
log.warning('bcache already stopped?')
return None
if not _alltrue(detach()):
return False
elif not _fssys('stop', 'goaway', 'error', 'Error stopping cache'):
return False
return _wait(lambda: uuid() is False, 'error', 'Cache did not stop', 300)
def back_make(dev, cache_mode='writeback', force=False, attach=True, bucket_size=None):
'''
Create a backing device for attachment to a set.
Because the block size must be the same, a cache set already needs to exist.
CLI example:
.. code-block:: bash
salt '*' bcache.back_make sdc cache_mode=writeback attach=True
:param cache_mode: writethrough, writeback, writearound or none.
:param force: Overwrite existing bcaches
:param attach: Immediately attach the backing device to the set
:param bucket_size: Size of a bucket (see kernel doc)
'''
# pylint: disable=too-many-return-statements
cache = uuid()
if not cache:
log.error('No bcache set found')
return False
elif _sysfs_attr(_bcpath(dev)):
if not force:
log.error('%s already contains a bcache. Wipe it manually or use force', dev)
return False
elif uuid(dev) and not detach(dev):
return False
elif not stop(dev):
return False
dev = _devpath(dev)
block_size = _size_map(_fssys('block_size'))
# You might want to override, we pick the cache set's as sane default
if bucket_size is None:
bucket_size = _size_map(_fssys('bucket_size'))
cmd = 'make-bcache --block {0} --bucket {1} --{2} --bdev {3}'.format(block_size, bucket_size, cache_mode, dev)
if force:
cmd += ' --wipe-bcache'
if not _run_all(cmd, 'error', 'Error creating backing device {0}: %s'.format(dev)):
return False
elif not _sysfs_attr('fs/bcache/register', _devpath(dev),
'error', 'Error registering backing device {0}'.format(dev)):
return False
elif not _wait(lambda: _sysfs_attr(_bcpath(dev)) is not False,
'error', 'Backing device {0} did not register'.format(dev)):
return False
elif attach:
return attach_(dev)
return True
def cache_make(dev, reserved=None, force=False, block_size=None, bucket_size=None, attach=True):
'''
Create BCache cache on a block device.
If blkdiscard is available the entire device will be properly cleared in advance.
CLI example:
.. code-block:: bash
salt '*' bcache.cache_make sdb reserved=10% block_size=4096
:param reserved: if dev is a full device, create a partition table with this size empty.
.. note::
this increases the amount of reserved space available to SSD garbage collectors,
potentially (vastly) increasing performance
:param block_size: Block size of the cache; defaults to devices' logical block size
:param force: Overwrite existing BCache sets
:param attach: Attach all existing backend devices immediately
'''
# TODO: multiple devs == md jbod
# pylint: disable=too-many-return-statements
# ---------------- Preflight checks ----------------
cache = uuid()
if cache:
if not force:
log.error('BCache cache %s is already on the system', cache)
return False
cache = _bdev()
dev = _devbase(dev)
udev = __salt__['udev.env'](dev)
if ('ID_FS_TYPE' in udev or (udev.get('DEVTYPE', None) != 'partition' and 'ID_PART_TABLE_TYPE' in udev)) \
and not force:
log.error('%s already contains data, wipe first or force', dev)
return False
elif reserved is not None and udev.get('DEVTYPE', None) != 'disk':
log.error('Need a partitionable blockdev for reserved to work')
return False
_, block, bucket = _sizes(dev)
if bucket_size is None:
bucket_size = bucket
# TODO: bucket from _sizes() makes no sense
bucket_size = False
if block_size is None:
block_size = block
# ---------------- Still here, start doing destructive stuff ----------------
if cache:
if not stop():
return False
# Wipe the current cache device as well,
# forever ruining any chance of it accidentally popping up again
elif not _wipe(cache):
return False
# Can't do enough wiping
if not _wipe(dev):
return False
if reserved:
cmd = 'parted -m -s -a optimal -- ' \
'/dev/{0} mklabel gpt mkpart bcache-reserved 1M {1} mkpart bcache {1} 100%'.format(dev, reserved)
# if wipe was incomplete & part layout remains the same,
# this is one condition set where udev would make it accidentally popup again
if not _run_all(cmd, 'error', 'Error creating bcache partitions on {0}: %s'.format(dev)):
return False
dev = '{0}2'.format(dev)
# ---------------- Finally, create a cache ----------------
cmd = 'make-bcache --cache /dev/{0} --block {1} --wipe-bcache'.format(dev, block_size)
# Actually bucket_size should always have a value, but for testing 0 is possible as well
if bucket_size:
cmd += ' --bucket {0}'.format(bucket_size)
if not _run_all(cmd, 'error', 'Error creating cache {0}: %s'.format(dev)):
return False
elif not _wait(lambda: uuid() is not False,
'error', 'Cache {0} seemingly created OK, but FS did not activate'.format(dev)):
return False
if attach:
return _alltrue(attach_())
else:
return True
def config_(dev=None, **kwargs):
'''
Show or update config of a bcache device.
If no device is given, operate on the cache set itself.
CLI example:
.. code-block:: bash
salt '*' bcache.config
salt '*' bcache.config bcache1
salt '*' bcache.config errors=panic journal_delay_ms=150
salt '*' bcache.config bcache1 cache_mode=writeback writeback_percent=15
:return: config or True/False
'''
if dev is None:
spath = _fspath()
else:
spath = _bcpath(dev)
# filter out 'hidden' kwargs added by our favourite orchestration system
updates = dict([(key, val) for key, val in kwargs.items() if not key.startswith('__')])
if updates:
endres = 0
for key, val in updates.items():
endres += _sysfs_attr([spath, key], val,
'warn', 'Failed to update {0} with {1}'.format(os.path.join(spath, key), val))
return endres > 0
else:
result = {}
data = _sysfs_parse(spath, config=True, internals=True, options=True)
for key in ('other_ro', 'inter_ro'):
if key in data:
del data[key]
for key in data:
result.update(data[key])
return result
def status(stats=False, config=False, internals=False, superblock=False, alldevs=False):
'''
Show the full status of the BCache system and optionally all it's involved devices
CLI example:
.. code-block:: bash
salt '*' bcache.status
salt '*' bcache.status stats=True
salt '*' bcache.status internals=True alldevs=True
:param stats: include statistics
:param config: include settings
:param internals: include internals
:param superblock: include superblock
'''
bdevs = []
for _, links, _ in salt.utils.path.os_walk('/sys/block/'):
for block in links:
if 'bcache' in block:
continue
for spath, sdirs, _ in salt.utils.path.os_walk('/sys/block/{0}'.format(block), followlinks=False):
if 'bcache' in sdirs:
bdevs.append(os.path.basename(spath))
statii = {}
for bcache in bdevs:
statii[bcache] = device(bcache, stats, config, internals, superblock)
cuuid = uuid()
cdev = _bdev()
if cdev:
count = 0
for dev in statii:
if dev != cdev:
# it's a backing dev
if statii[dev]['cache'] == cuuid:
count += 1
statii[cdev]['attached_backing_devices'] = count
if not alldevs:
statii = statii[cdev]
return statii
def device(dev, stats=False, config=False, internals=False, superblock=False):
'''
Check the state of a single bcache device
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc stats=True
:param stats: include statistics
:param settings: include all settings
:param internals: include all internals
:param superblock: include superblock info
'''
result = {}
if not _sysfs_attr(_bcpath(dev), None, 'error', '{0} is not a bcache fo any kind'.format(dev)):
return False
elif _bcsys(dev, 'set'):
# ---------------- It's the cache itself ----------------
result['uuid'] = uuid()
base_attr = ['block_size', 'bucket_size', 'cache_available_percent', 'cache_replacement_policy', 'congested']
# ---------------- Parse through both the blockdev & the FS ----------------
result.update(_sysfs_parse(_bcpath(dev), base_attr, stats, config, internals))
result.update(_sysfs_parse(_fspath(), base_attr, stats, config, internals))
result.update(result.pop('base'))
else:
# ---------------- It's a backing device ----------------
back_uuid = uuid(dev)
if back_uuid is not None:
result['cache'] = back_uuid
try:
result['dev'] = os.path.basename(_bcsys(dev, 'dev'))
except Exception:
pass
result['bdev'] = _bdev(dev)
base_attr = ['cache_mode', 'running', 'state', 'writeback_running']
base_path = _bcpath(dev)
result.update(_sysfs_parse(base_path, base_attr, stats, config, internals))
result.update(result.pop('base'))
# ---------------- Modifications ----------------
state = [result['state']]
if result.pop('running'):
state.append('running')
else:
state.append('stopped')
if 'writeback_running' in result:
if result.pop('writeback_running'):
state.append('writeback_running')
else:
state.append('writeback_stopped')
result['state'] = state
# ---------------- Statistics ----------------
if 'stats' in result:
replre = r'(stats|cache)_'
statres = result['stats']
for attr in result['stats']:
if '/' not in attr:
key = re.sub(replre, '', attr)
statres[key] = statres.pop(attr)
else:
stat, key = attr.split('/', 1)
stat = re.sub(replre, '', stat)
key = re.sub(replre, '', key)
if stat not in statres:
statres[stat] = {}
statres[stat][key] = statres.pop(attr)
result['stats'] = statres
# ---------------- Internals ----------------
if internals:
interres = result.pop('inter_ro', {})
interres.update(result.pop('inter_rw', {}))
if interres:
for key in interres:
if key.startswith('internal'):
nkey = re.sub(r'internal[s/]*', '', key)
interres[nkey] = interres.pop(key)
key = nkey
if key.startswith(('btree', 'writeback')):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in interres:
interres[mkey] = {}
interres[mkey][skey] = interres.pop(key)
result['internals'] = interres
# ---------------- Config ----------------
if config:
configres = result['config']
for key in configres:
if key.startswith('writeback'):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in configres:
configres[mkey] = {}
configres[mkey][skey] = configres.pop(key)
result['config'] = configres
# ---------------- Superblock ----------------
if superblock:
result['superblock'] = super_(dev)
return result
def super_(dev):
'''
Read out BCache SuperBlock
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc
'''
dev = _devpath(dev)
ret = {}
res = _run_all('bcache-super-show {0}'.format(dev), 'error', 'Error reading superblock on {0}: %s'.format(dev))
if not res:
return False
for line in res.splitlines(): # pylint: disable=no-member
line = line.strip()
if not line:
continue
key, val = [val.strip() for val in re.split(r'[\s]+', line, maxsplit=1)]
if not (key and val):
continue
mval = None
if ' ' in val:
rval, mval = [val.strip() for val in re.split(r'[\s]+', val, maxsplit=1)]
mval = mval[1:-1]
else:
rval = val
try:
rval = int(rval)
except Exception:
try:
rval = float(rval)
except Exception:
if rval == 'yes':
rval = True
elif rval == 'no':
rval = False
pkey, key = re.split(r'\.', key, maxsplit=1)
if pkey not in ret:
ret[pkey] = {}
if mval is not None:
ret[pkey][key] = (rval, mval)
else:
ret[pkey][key] = rval
return ret
# -------------------------------- HELPER FUNCTIONS --------------------------------
def _devbase(dev):
'''
Basename of just about any dev
'''
dev = os.path.realpath(os.path.expandvars(dev))
dev = os.path.basename(dev)
return dev
def _devpath(dev):
'''
Return /dev name of just about any dev
:return: /dev/devicename
'''
return os.path.join('/dev', _devbase(dev))
def _syspath(dev):
'''
Full SysFS path of a device
'''
dev = _devbase(dev)
dev = re.sub(r'^([vhs][a-z]+)([0-9]+)', r'\1/\1\2', dev)
# name = re.sub(r'^([a-z]+)(?<!(bcache|md|dm))([0-9]+)', r'\1/\1\2', name)
return os.path.join('/sys/block/', dev)
def _bdev(dev=None):
'''
Resolve a bcacheX or cache to a real dev
:return: basename of bcache dev
'''
if dev is None:
dev = _fssys('cache0')
else:
dev = _bcpath(dev)
if not dev:
return False
else:
return _devbase(os.path.dirname(dev))
def _bcpath(dev):
'''
Full SysFS path of a bcache device
'''
return os.path.join(_syspath(dev), 'bcache')
def _fspath():
'''
:return: path of active bcache
'''
cuuid = uuid()
if not cuuid:
return False
else:
return os.path.join('/sys/fs/bcache/', cuuid)
def _fssys(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with bcache SysFS
'''
fspath = _fspath()
if not fspath:
return False
else:
return _sysfs_attr([fspath, name], value, log_lvl, log_msg)
def _bcsys(dev, name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with backing devs SysFS
'''
return _sysfs_attr([_bcpath(dev), name], value, log_lvl, log_msg)
def _sysfs_attr(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper with logging around sysfs.attr
'''
if isinstance(name, six.string_types):
name = [name]
res = __salt__['sysfs.attr'](os.path.join(*name), value)
if not res and log_lvl is not None and log_msg is not None:
log.log(LOG[log_lvl], log_msg)
return res
def _sysfs_parse(path, base_attr=None, stats=False, config=False, internals=False, options=False):
'''
Helper function for parsing BCache's SysFS interface
'''
result = {}
# ---------------- Parse through the interfaces list ----------------
intfs = __salt__['sysfs.interfaces'](path)
# Actions, we ignore
del intfs['w']
# -------- Sorting hat --------
binkeys = []
if internals:
binkeys.extend(['inter_ro', 'inter_rw'])
if config:
binkeys.append('config')
if stats:
binkeys.append('stats')
bintf = {}
for key in binkeys:
bintf[key] = []
for intf in intfs['r']:
if intf.startswith('internal'):
key = 'inter_ro'
elif 'stats' in intf:
key = 'stats'
else:
# What to do with these???
# I'll utilize 'inter_ro' as 'misc' as well
key = 'inter_ro'
if key in bintf:
bintf[key].append(intf)
for intf in intfs['rw']:
if intf.startswith('internal'):
key = 'inter_rw'
else:
key = 'config'
if key in bintf:
bintf[key].append(intf)
if base_attr is not None:
for intf in bintf:
bintf[intf] = [sintf for sintf in bintf[intf] if sintf not in base_attr]
bintf['base'] = base_attr
mods = {
'stats': ['internal/bset_tree_stats', 'writeback_rate_debug', 'metadata_written', 'nbuckets', 'written',
'average_key_size', 'btree_cache_size'],
}
for modt, modlist in mods.items():
found = []
if modt not in bintf:
continue
for mod in modlist:
for intflist in bintf.values():
if mod in intflist:
found.append(mod)
intflist.remove(mod)
bintf[modt] += found
# -------- Fetch SysFS vals --------
bintflist = [intf for iflist in bintf.values() for intf in iflist]
result.update(__salt__['sysfs.read'](bintflist, path))
# -------- Parse through well known string lists --------
for strlist in ('writeback_rate_debug', 'internal/bset_tree_stats', 'priority_stats'):
if strlist in result:
listres = {}
for line in result[strlist].split('\n'):
key, val = line.split(':', 1)
val = val.strip()
try:
val = int(val)
except Exception:
try:
val = float(val)
except Exception:
pass
listres[key.strip()] = val
result[strlist] = listres
# -------- Parse through selection lists --------
if not options:
for sellist in ('cache_mode', 'cache_replacement_policy', 'errors'):
if sellist in result:
result[sellist] = re.search(r'\[(.+)\]', result[sellist]).groups()[0]
# -------- Parse through well known bools --------
for boolkey in ('running', 'writeback_running', 'congested'):
if boolkey in result:
result[boolkey] = bool(result[boolkey])
# -------- Recategorize results --------
bresult = {}
for iftype, intflist in bintf.items():
ifres = {}
for intf in intflist:
if intf in result:
ifres[intf] = result.pop(intf)
if ifres:
bresult[iftype] = ifres
return bresult
def _size_map(size):
'''
Map Bcache's size strings to real bytes
'''
try:
# I know, I know, EAFP.
# But everything else is reason for None
if not isinstance(size, int):
if re.search(r'[Kk]', size):
size = 1024 * float(re.sub(r'[Kk]', '', size))
elif re.search(r'[Mm]', size):
size = 1024**2 * float(re.sub(r'[Mm]', '', size))
size = int(size)
return size
except Exception:
return None
def _wipe(dev):
'''
REALLY DESTRUCTIVE STUFF RIGHT AHEAD
'''
endres = 0
dev = _devbase(dev)
size, block, discard = _sizes(dev)
if discard is None:
log.error('Unable to read SysFS props for %s', dev)
return None
elif not discard:
log.warning('%s seems unable to discard', dev)
wiper = 'dd'
elif not HAS_BLKDISCARD:
log.warning('blkdiscard binary not available, properly wipe the dev manually for optimal results')
wiper = 'dd'
else:
wiper = 'blkdiscard'
wipe_failmsg = 'Error wiping {0}: %s'.format(dev)
if wiper == 'dd':
blocks = 4
cmd = 'dd if=/dev/zero of=/dev/{0} bs=1M count={1}'.format(dev, blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# Some stuff (<cough>GPT</cough>) writes stuff at the end of a dev as well
cmd += ' seek={0}'.format((size/1024**2) - blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
elif wiper == 'blkdiscard':
cmd = 'blkdiscard /dev/{0}'.format(dev)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# TODO: fix annoying bug failing blkdiscard by trying to discard 1 sector past blkdev
endres = 1
return endres > 0
def _wait(lfunc, log_lvl=None, log_msg=None, tries=10):
'''
Wait for lfunc to be True
:return: True if lfunc succeeded within tries, False if it didn't
'''
i = 0
while i < tries:
time.sleep(1)
if lfunc():
return True
else:
i += 1
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg)
return False
def _run_all(cmd, log_lvl=None, log_msg=None, exitcode=0):
'''
Simple wrapper around cmd.run_all
log_msg can contain {0} for stderr
:return: True or stdout, False if retcode wasn't exitcode
'''
res = __salt__['cmd.run_all'](cmd)
if res['retcode'] == exitcode:
if res['stdout']:
return res['stdout']
else:
return True
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg, res['stderr'])
return False
def _alltrue(resdict):
if resdict is None:
return True
return len([val for val in resdict.values() if val]) > 0
|
saltstack/salt
|
salt/modules/bcache.py
|
_wipe
|
python
|
def _wipe(dev):
'''
REALLY DESTRUCTIVE STUFF RIGHT AHEAD
'''
endres = 0
dev = _devbase(dev)
size, block, discard = _sizes(dev)
if discard is None:
log.error('Unable to read SysFS props for %s', dev)
return None
elif not discard:
log.warning('%s seems unable to discard', dev)
wiper = 'dd'
elif not HAS_BLKDISCARD:
log.warning('blkdiscard binary not available, properly wipe the dev manually for optimal results')
wiper = 'dd'
else:
wiper = 'blkdiscard'
wipe_failmsg = 'Error wiping {0}: %s'.format(dev)
if wiper == 'dd':
blocks = 4
cmd = 'dd if=/dev/zero of=/dev/{0} bs=1M count={1}'.format(dev, blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# Some stuff (<cough>GPT</cough>) writes stuff at the end of a dev as well
cmd += ' seek={0}'.format((size/1024**2) - blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
elif wiper == 'blkdiscard':
cmd = 'blkdiscard /dev/{0}'.format(dev)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# TODO: fix annoying bug failing blkdiscard by trying to discard 1 sector past blkdev
endres = 1
return endres > 0
|
REALLY DESTRUCTIVE STUFF RIGHT AHEAD
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bcache.py#L881-L918
|
[
"def _sizes(dev):\n '''\n Return neigh useless sizing info about a blockdev\n :return: (total size in blocks, blocksize, maximum discard size in bytes)\n '''\n dev = _devbase(dev)\n\n # standarization yay\n block_sizes = ('hw_sector_size', 'minimum_io_size', 'physical_block_size', 'logical_block_size')\n discard_sizes = ('discard_max_bytes', 'discard_max_hw_bytes', )\n\n sysfs = __salt__['sysfs.read'](\n ('size',\n 'queue/hw_sector_size', '../queue/hw_sector_size',\n 'queue/discard_max_bytes', '../queue/discard_max_bytes'),\n root=_syspath(dev))\n\n # TODO: makes no sense\n # First of all, it has to be a power of 2\n # Secondly, this returns 4GiB - 512b on Intel 3500's for some weird reason\n # discard_granularity seems in bytes, resolves to 512b ???\n # max_hw_sectors_kb???\n # There's also discard_max_hw_bytes more recently\n # See: https://www.kernel.org/doc/Documentation/block/queue-sysfs.txt\n # Also, I cant find any docs yet regarding bucket sizes;\n # it's supposed to be discard_max_hw_bytes,\n # but no way to figure that one reliably out apparently\n\n discard = sysfs.get('queue/discard_max_bytes', sysfs.get('../queue/discard_max_bytes', None))\n block = sysfs.get('queue/hw_sector_size', sysfs.get('../queue/hw_sector_size', None))\n\n return 512*sysfs['size'], block, discard\n",
"def _run_all(cmd, log_lvl=None, log_msg=None, exitcode=0):\n '''\n Simple wrapper around cmd.run_all\n log_msg can contain {0} for stderr\n :return: True or stdout, False if retcode wasn't exitcode\n '''\n res = __salt__['cmd.run_all'](cmd)\n if res['retcode'] == exitcode:\n if res['stdout']:\n return res['stdout']\n else:\n return True\n\n if log_lvl is not None:\n log.log(LOG[log_lvl], log_msg, res['stderr'])\n return False\n",
"def _devbase(dev):\n '''\n Basename of just about any dev\n '''\n dev = os.path.realpath(os.path.expandvars(dev))\n dev = os.path.basename(dev)\n return dev\n"
] |
# -*- coding: utf-8 -*-
'''
Module for managing BCache sets
BCache is a block-level caching mechanism similar to ZFS L2ARC/ZIL, dm-cache and fscache.
It works by formatting one block device as a cache set, then adding backend devices
(which need to be formatted as such) to the set and activating them.
It's available in Linux mainline kernel since 3.10
https://www.kernel.org/doc/Documentation/bcache.txt
This module needs the bcache userspace tools to function.
.. versionadded: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import time
import re
from salt.ext import six
# Import salt libs
import salt.utils.path
log = logging.getLogger(__name__)
LOG = {
'trace': logging.TRACE,
'debug': logging.DEBUG,
'info': logging.INFO,
'warn': logging.WARNING,
'error': logging.ERROR,
'crit': logging.CRITICAL,
}
__func_alias__ = {
'attach_': 'attach',
'config_': 'config',
'super_': 'super',
}
HAS_BLKDISCARD = salt.utils.path.which('blkdiscard') is not None
def __virtual__():
'''
Only work when make-bcache is installed
'''
return salt.utils.path.which('make-bcache') is not None
def uuid(dev=None):
'''
Return the bcache UUID of a block device.
If no device is given, the Cache UUID is returned.
CLI example:
.. code-block:: bash
salt '*' bcache.uuid
salt '*' bcache.uuid /dev/sda
salt '*' bcache.uuid bcache0
'''
try:
if dev is None:
# take the only directory in /sys/fs/bcache and return it's basename
return list(salt.utils.path.os_walk('/sys/fs/bcache/'))[0][1][0]
else:
# basename of the /sys/block/{dev}/bcache/cache symlink target
return os.path.basename(_bcsys(dev, 'cache'))
except Exception:
return False
def attach_(dev=None):
'''
Attach a backing devices to a cache set
If no dev is given, all backing devices will be attached.
CLI example:
.. code-block:: bash
salt '*' bcache.attach sdc
salt '*' bcache.attach /dev/bcache1
:return: bool or None if nuttin' happened
'''
cache = uuid()
if not cache:
log.error('No cache to attach %s to', dev)
return False
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = attach_(dev)
return res if res else None
bcache = uuid(dev)
if bcache:
if bcache == cache:
log.info('%s is already attached to bcache %s, doing nothing', dev, cache)
return None
elif not detach(dev):
return False
log.debug('Attaching %s to bcache %s', dev, cache)
if not _bcsys(dev, 'attach', cache,
'error', 'Error attaching {0} to bcache {1}'.format(dev, cache)):
return False
return _wait(lambda: uuid(dev) == cache,
'error', '{0} received attach to bcache {1}, but did not comply'.format(dev, cache))
def detach(dev=None):
'''
Detach a backing device(s) from a cache set
If no dev is given, all backing devices will be attached.
Detaching a backing device will flush it's write cache.
This should leave the underlying device in a consistent state, but might take a while.
CLI example:
.. code-block:: bash
salt '*' bcache.detach sdc
salt '*' bcache.detach bcache1
'''
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = detach(dev)
return res if res else None
log.debug('Detaching %s', dev)
if not _bcsys(dev, 'detach', 'goaway', 'error', 'Error detaching {0}'.format(dev)):
return False
return _wait(lambda: uuid(dev) is False, 'error', '{0} received detach, but did not comply'.format(dev), 300)
def start():
'''
Trigger a start of the full bcache system through udev.
CLI example:
.. code-block:: bash
salt '*' bcache.start
'''
if not _run_all('udevadm trigger', 'error', 'Error starting bcache: %s'):
return False
elif not _wait(lambda: uuid() is not False, 'warn', 'Bcache system started, but no active cache set found.'):
return False
return True
def stop(dev=None):
'''
Stop a bcache device
If no device is given, all backing devices will be detached from the cache, which will subsequently be stopped.
.. warning::
'Stop' on an individual backing device means hard-stop;
no attempt at flushing will be done and the bcache device will seemingly 'disappear' from the device lists
CLI example:
.. code-block:: bash
salt '*' bcache.stop
'''
if dev is not None:
log.warning('Stopping %s, device will only reappear after reregistering!', dev)
if not _bcsys(dev, 'stop', 'goaway', 'error', 'Error stopping {0}'.format(dev)):
return False
return _wait(lambda: _sysfs_attr(_bcpath(dev)) is False, 'error', 'Device {0} did not stop'.format(dev), 300)
else:
cache = uuid()
if not cache:
log.warning('bcache already stopped?')
return None
if not _alltrue(detach()):
return False
elif not _fssys('stop', 'goaway', 'error', 'Error stopping cache'):
return False
return _wait(lambda: uuid() is False, 'error', 'Cache did not stop', 300)
def back_make(dev, cache_mode='writeback', force=False, attach=True, bucket_size=None):
'''
Create a backing device for attachment to a set.
Because the block size must be the same, a cache set already needs to exist.
CLI example:
.. code-block:: bash
salt '*' bcache.back_make sdc cache_mode=writeback attach=True
:param cache_mode: writethrough, writeback, writearound or none.
:param force: Overwrite existing bcaches
:param attach: Immediately attach the backing device to the set
:param bucket_size: Size of a bucket (see kernel doc)
'''
# pylint: disable=too-many-return-statements
cache = uuid()
if not cache:
log.error('No bcache set found')
return False
elif _sysfs_attr(_bcpath(dev)):
if not force:
log.error('%s already contains a bcache. Wipe it manually or use force', dev)
return False
elif uuid(dev) and not detach(dev):
return False
elif not stop(dev):
return False
dev = _devpath(dev)
block_size = _size_map(_fssys('block_size'))
# You might want to override, we pick the cache set's as sane default
if bucket_size is None:
bucket_size = _size_map(_fssys('bucket_size'))
cmd = 'make-bcache --block {0} --bucket {1} --{2} --bdev {3}'.format(block_size, bucket_size, cache_mode, dev)
if force:
cmd += ' --wipe-bcache'
if not _run_all(cmd, 'error', 'Error creating backing device {0}: %s'.format(dev)):
return False
elif not _sysfs_attr('fs/bcache/register', _devpath(dev),
'error', 'Error registering backing device {0}'.format(dev)):
return False
elif not _wait(lambda: _sysfs_attr(_bcpath(dev)) is not False,
'error', 'Backing device {0} did not register'.format(dev)):
return False
elif attach:
return attach_(dev)
return True
def cache_make(dev, reserved=None, force=False, block_size=None, bucket_size=None, attach=True):
'''
Create BCache cache on a block device.
If blkdiscard is available the entire device will be properly cleared in advance.
CLI example:
.. code-block:: bash
salt '*' bcache.cache_make sdb reserved=10% block_size=4096
:param reserved: if dev is a full device, create a partition table with this size empty.
.. note::
this increases the amount of reserved space available to SSD garbage collectors,
potentially (vastly) increasing performance
:param block_size: Block size of the cache; defaults to devices' logical block size
:param force: Overwrite existing BCache sets
:param attach: Attach all existing backend devices immediately
'''
# TODO: multiple devs == md jbod
# pylint: disable=too-many-return-statements
# ---------------- Preflight checks ----------------
cache = uuid()
if cache:
if not force:
log.error('BCache cache %s is already on the system', cache)
return False
cache = _bdev()
dev = _devbase(dev)
udev = __salt__['udev.env'](dev)
if ('ID_FS_TYPE' in udev or (udev.get('DEVTYPE', None) != 'partition' and 'ID_PART_TABLE_TYPE' in udev)) \
and not force:
log.error('%s already contains data, wipe first or force', dev)
return False
elif reserved is not None and udev.get('DEVTYPE', None) != 'disk':
log.error('Need a partitionable blockdev for reserved to work')
return False
_, block, bucket = _sizes(dev)
if bucket_size is None:
bucket_size = bucket
# TODO: bucket from _sizes() makes no sense
bucket_size = False
if block_size is None:
block_size = block
# ---------------- Still here, start doing destructive stuff ----------------
if cache:
if not stop():
return False
# Wipe the current cache device as well,
# forever ruining any chance of it accidentally popping up again
elif not _wipe(cache):
return False
# Can't do enough wiping
if not _wipe(dev):
return False
if reserved:
cmd = 'parted -m -s -a optimal -- ' \
'/dev/{0} mklabel gpt mkpart bcache-reserved 1M {1} mkpart bcache {1} 100%'.format(dev, reserved)
# if wipe was incomplete & part layout remains the same,
# this is one condition set where udev would make it accidentally popup again
if not _run_all(cmd, 'error', 'Error creating bcache partitions on {0}: %s'.format(dev)):
return False
dev = '{0}2'.format(dev)
# ---------------- Finally, create a cache ----------------
cmd = 'make-bcache --cache /dev/{0} --block {1} --wipe-bcache'.format(dev, block_size)
# Actually bucket_size should always have a value, but for testing 0 is possible as well
if bucket_size:
cmd += ' --bucket {0}'.format(bucket_size)
if not _run_all(cmd, 'error', 'Error creating cache {0}: %s'.format(dev)):
return False
elif not _wait(lambda: uuid() is not False,
'error', 'Cache {0} seemingly created OK, but FS did not activate'.format(dev)):
return False
if attach:
return _alltrue(attach_())
else:
return True
def config_(dev=None, **kwargs):
'''
Show or update config of a bcache device.
If no device is given, operate on the cache set itself.
CLI example:
.. code-block:: bash
salt '*' bcache.config
salt '*' bcache.config bcache1
salt '*' bcache.config errors=panic journal_delay_ms=150
salt '*' bcache.config bcache1 cache_mode=writeback writeback_percent=15
:return: config or True/False
'''
if dev is None:
spath = _fspath()
else:
spath = _bcpath(dev)
# filter out 'hidden' kwargs added by our favourite orchestration system
updates = dict([(key, val) for key, val in kwargs.items() if not key.startswith('__')])
if updates:
endres = 0
for key, val in updates.items():
endres += _sysfs_attr([spath, key], val,
'warn', 'Failed to update {0} with {1}'.format(os.path.join(spath, key), val))
return endres > 0
else:
result = {}
data = _sysfs_parse(spath, config=True, internals=True, options=True)
for key in ('other_ro', 'inter_ro'):
if key in data:
del data[key]
for key in data:
result.update(data[key])
return result
def status(stats=False, config=False, internals=False, superblock=False, alldevs=False):
'''
Show the full status of the BCache system and optionally all it's involved devices
CLI example:
.. code-block:: bash
salt '*' bcache.status
salt '*' bcache.status stats=True
salt '*' bcache.status internals=True alldevs=True
:param stats: include statistics
:param config: include settings
:param internals: include internals
:param superblock: include superblock
'''
bdevs = []
for _, links, _ in salt.utils.path.os_walk('/sys/block/'):
for block in links:
if 'bcache' in block:
continue
for spath, sdirs, _ in salt.utils.path.os_walk('/sys/block/{0}'.format(block), followlinks=False):
if 'bcache' in sdirs:
bdevs.append(os.path.basename(spath))
statii = {}
for bcache in bdevs:
statii[bcache] = device(bcache, stats, config, internals, superblock)
cuuid = uuid()
cdev = _bdev()
if cdev:
count = 0
for dev in statii:
if dev != cdev:
# it's a backing dev
if statii[dev]['cache'] == cuuid:
count += 1
statii[cdev]['attached_backing_devices'] = count
if not alldevs:
statii = statii[cdev]
return statii
def device(dev, stats=False, config=False, internals=False, superblock=False):
'''
Check the state of a single bcache device
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc stats=True
:param stats: include statistics
:param settings: include all settings
:param internals: include all internals
:param superblock: include superblock info
'''
result = {}
if not _sysfs_attr(_bcpath(dev), None, 'error', '{0} is not a bcache fo any kind'.format(dev)):
return False
elif _bcsys(dev, 'set'):
# ---------------- It's the cache itself ----------------
result['uuid'] = uuid()
base_attr = ['block_size', 'bucket_size', 'cache_available_percent', 'cache_replacement_policy', 'congested']
# ---------------- Parse through both the blockdev & the FS ----------------
result.update(_sysfs_parse(_bcpath(dev), base_attr, stats, config, internals))
result.update(_sysfs_parse(_fspath(), base_attr, stats, config, internals))
result.update(result.pop('base'))
else:
# ---------------- It's a backing device ----------------
back_uuid = uuid(dev)
if back_uuid is not None:
result['cache'] = back_uuid
try:
result['dev'] = os.path.basename(_bcsys(dev, 'dev'))
except Exception:
pass
result['bdev'] = _bdev(dev)
base_attr = ['cache_mode', 'running', 'state', 'writeback_running']
base_path = _bcpath(dev)
result.update(_sysfs_parse(base_path, base_attr, stats, config, internals))
result.update(result.pop('base'))
# ---------------- Modifications ----------------
state = [result['state']]
if result.pop('running'):
state.append('running')
else:
state.append('stopped')
if 'writeback_running' in result:
if result.pop('writeback_running'):
state.append('writeback_running')
else:
state.append('writeback_stopped')
result['state'] = state
# ---------------- Statistics ----------------
if 'stats' in result:
replre = r'(stats|cache)_'
statres = result['stats']
for attr in result['stats']:
if '/' not in attr:
key = re.sub(replre, '', attr)
statres[key] = statres.pop(attr)
else:
stat, key = attr.split('/', 1)
stat = re.sub(replre, '', stat)
key = re.sub(replre, '', key)
if stat not in statres:
statres[stat] = {}
statres[stat][key] = statres.pop(attr)
result['stats'] = statres
# ---------------- Internals ----------------
if internals:
interres = result.pop('inter_ro', {})
interres.update(result.pop('inter_rw', {}))
if interres:
for key in interres:
if key.startswith('internal'):
nkey = re.sub(r'internal[s/]*', '', key)
interres[nkey] = interres.pop(key)
key = nkey
if key.startswith(('btree', 'writeback')):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in interres:
interres[mkey] = {}
interres[mkey][skey] = interres.pop(key)
result['internals'] = interres
# ---------------- Config ----------------
if config:
configres = result['config']
for key in configres:
if key.startswith('writeback'):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in configres:
configres[mkey] = {}
configres[mkey][skey] = configres.pop(key)
result['config'] = configres
# ---------------- Superblock ----------------
if superblock:
result['superblock'] = super_(dev)
return result
def super_(dev):
'''
Read out BCache SuperBlock
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc
'''
dev = _devpath(dev)
ret = {}
res = _run_all('bcache-super-show {0}'.format(dev), 'error', 'Error reading superblock on {0}: %s'.format(dev))
if not res:
return False
for line in res.splitlines(): # pylint: disable=no-member
line = line.strip()
if not line:
continue
key, val = [val.strip() for val in re.split(r'[\s]+', line, maxsplit=1)]
if not (key and val):
continue
mval = None
if ' ' in val:
rval, mval = [val.strip() for val in re.split(r'[\s]+', val, maxsplit=1)]
mval = mval[1:-1]
else:
rval = val
try:
rval = int(rval)
except Exception:
try:
rval = float(rval)
except Exception:
if rval == 'yes':
rval = True
elif rval == 'no':
rval = False
pkey, key = re.split(r'\.', key, maxsplit=1)
if pkey not in ret:
ret[pkey] = {}
if mval is not None:
ret[pkey][key] = (rval, mval)
else:
ret[pkey][key] = rval
return ret
# -------------------------------- HELPER FUNCTIONS --------------------------------
def _devbase(dev):
'''
Basename of just about any dev
'''
dev = os.path.realpath(os.path.expandvars(dev))
dev = os.path.basename(dev)
return dev
def _devpath(dev):
'''
Return /dev name of just about any dev
:return: /dev/devicename
'''
return os.path.join('/dev', _devbase(dev))
def _syspath(dev):
'''
Full SysFS path of a device
'''
dev = _devbase(dev)
dev = re.sub(r'^([vhs][a-z]+)([0-9]+)', r'\1/\1\2', dev)
# name = re.sub(r'^([a-z]+)(?<!(bcache|md|dm))([0-9]+)', r'\1/\1\2', name)
return os.path.join('/sys/block/', dev)
def _bdev(dev=None):
'''
Resolve a bcacheX or cache to a real dev
:return: basename of bcache dev
'''
if dev is None:
dev = _fssys('cache0')
else:
dev = _bcpath(dev)
if not dev:
return False
else:
return _devbase(os.path.dirname(dev))
def _bcpath(dev):
'''
Full SysFS path of a bcache device
'''
return os.path.join(_syspath(dev), 'bcache')
def _fspath():
'''
:return: path of active bcache
'''
cuuid = uuid()
if not cuuid:
return False
else:
return os.path.join('/sys/fs/bcache/', cuuid)
def _fssys(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with bcache SysFS
'''
fspath = _fspath()
if not fspath:
return False
else:
return _sysfs_attr([fspath, name], value, log_lvl, log_msg)
def _bcsys(dev, name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with backing devs SysFS
'''
return _sysfs_attr([_bcpath(dev), name], value, log_lvl, log_msg)
def _sysfs_attr(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper with logging around sysfs.attr
'''
if isinstance(name, six.string_types):
name = [name]
res = __salt__['sysfs.attr'](os.path.join(*name), value)
if not res and log_lvl is not None and log_msg is not None:
log.log(LOG[log_lvl], log_msg)
return res
def _sysfs_parse(path, base_attr=None, stats=False, config=False, internals=False, options=False):
'''
Helper function for parsing BCache's SysFS interface
'''
result = {}
# ---------------- Parse through the interfaces list ----------------
intfs = __salt__['sysfs.interfaces'](path)
# Actions, we ignore
del intfs['w']
# -------- Sorting hat --------
binkeys = []
if internals:
binkeys.extend(['inter_ro', 'inter_rw'])
if config:
binkeys.append('config')
if stats:
binkeys.append('stats')
bintf = {}
for key in binkeys:
bintf[key] = []
for intf in intfs['r']:
if intf.startswith('internal'):
key = 'inter_ro'
elif 'stats' in intf:
key = 'stats'
else:
# What to do with these???
# I'll utilize 'inter_ro' as 'misc' as well
key = 'inter_ro'
if key in bintf:
bintf[key].append(intf)
for intf in intfs['rw']:
if intf.startswith('internal'):
key = 'inter_rw'
else:
key = 'config'
if key in bintf:
bintf[key].append(intf)
if base_attr is not None:
for intf in bintf:
bintf[intf] = [sintf for sintf in bintf[intf] if sintf not in base_attr]
bintf['base'] = base_attr
mods = {
'stats': ['internal/bset_tree_stats', 'writeback_rate_debug', 'metadata_written', 'nbuckets', 'written',
'average_key_size', 'btree_cache_size'],
}
for modt, modlist in mods.items():
found = []
if modt not in bintf:
continue
for mod in modlist:
for intflist in bintf.values():
if mod in intflist:
found.append(mod)
intflist.remove(mod)
bintf[modt] += found
# -------- Fetch SysFS vals --------
bintflist = [intf for iflist in bintf.values() for intf in iflist]
result.update(__salt__['sysfs.read'](bintflist, path))
# -------- Parse through well known string lists --------
for strlist in ('writeback_rate_debug', 'internal/bset_tree_stats', 'priority_stats'):
if strlist in result:
listres = {}
for line in result[strlist].split('\n'):
key, val = line.split(':', 1)
val = val.strip()
try:
val = int(val)
except Exception:
try:
val = float(val)
except Exception:
pass
listres[key.strip()] = val
result[strlist] = listres
# -------- Parse through selection lists --------
if not options:
for sellist in ('cache_mode', 'cache_replacement_policy', 'errors'):
if sellist in result:
result[sellist] = re.search(r'\[(.+)\]', result[sellist]).groups()[0]
# -------- Parse through well known bools --------
for boolkey in ('running', 'writeback_running', 'congested'):
if boolkey in result:
result[boolkey] = bool(result[boolkey])
# -------- Recategorize results --------
bresult = {}
for iftype, intflist in bintf.items():
ifres = {}
for intf in intflist:
if intf in result:
ifres[intf] = result.pop(intf)
if ifres:
bresult[iftype] = ifres
return bresult
def _size_map(size):
'''
Map Bcache's size strings to real bytes
'''
try:
# I know, I know, EAFP.
# But everything else is reason for None
if not isinstance(size, int):
if re.search(r'[Kk]', size):
size = 1024 * float(re.sub(r'[Kk]', '', size))
elif re.search(r'[Mm]', size):
size = 1024**2 * float(re.sub(r'[Mm]', '', size))
size = int(size)
return size
except Exception:
return None
def _sizes(dev):
'''
Return neigh useless sizing info about a blockdev
:return: (total size in blocks, blocksize, maximum discard size in bytes)
'''
dev = _devbase(dev)
# standarization yay
block_sizes = ('hw_sector_size', 'minimum_io_size', 'physical_block_size', 'logical_block_size')
discard_sizes = ('discard_max_bytes', 'discard_max_hw_bytes', )
sysfs = __salt__['sysfs.read'](
('size',
'queue/hw_sector_size', '../queue/hw_sector_size',
'queue/discard_max_bytes', '../queue/discard_max_bytes'),
root=_syspath(dev))
# TODO: makes no sense
# First of all, it has to be a power of 2
# Secondly, this returns 4GiB - 512b on Intel 3500's for some weird reason
# discard_granularity seems in bytes, resolves to 512b ???
# max_hw_sectors_kb???
# There's also discard_max_hw_bytes more recently
# See: https://www.kernel.org/doc/Documentation/block/queue-sysfs.txt
# Also, I cant find any docs yet regarding bucket sizes;
# it's supposed to be discard_max_hw_bytes,
# but no way to figure that one reliably out apparently
discard = sysfs.get('queue/discard_max_bytes', sysfs.get('../queue/discard_max_bytes', None))
block = sysfs.get('queue/hw_sector_size', sysfs.get('../queue/hw_sector_size', None))
return 512*sysfs['size'], block, discard
def _wait(lfunc, log_lvl=None, log_msg=None, tries=10):
'''
Wait for lfunc to be True
:return: True if lfunc succeeded within tries, False if it didn't
'''
i = 0
while i < tries:
time.sleep(1)
if lfunc():
return True
else:
i += 1
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg)
return False
def _run_all(cmd, log_lvl=None, log_msg=None, exitcode=0):
'''
Simple wrapper around cmd.run_all
log_msg can contain {0} for stderr
:return: True or stdout, False if retcode wasn't exitcode
'''
res = __salt__['cmd.run_all'](cmd)
if res['retcode'] == exitcode:
if res['stdout']:
return res['stdout']
else:
return True
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg, res['stderr'])
return False
def _alltrue(resdict):
if resdict is None:
return True
return len([val for val in resdict.values() if val]) > 0
|
saltstack/salt
|
salt/modules/bcache.py
|
_wait
|
python
|
def _wait(lfunc, log_lvl=None, log_msg=None, tries=10):
'''
Wait for lfunc to be True
:return: True if lfunc succeeded within tries, False if it didn't
'''
i = 0
while i < tries:
time.sleep(1)
if lfunc():
return True
else:
i += 1
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg)
return False
|
Wait for lfunc to be True
:return: True if lfunc succeeded within tries, False if it didn't
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bcache.py#L921-L936
|
[
"return _wait(lambda: uuid(dev) == cache,\n",
"return _wait(lambda: uuid(dev) is False, 'error', '{0} received detach, but did not comply'.format(dev), 300)\n",
"elif not _wait(lambda: uuid() is not False, 'warn', 'Bcache system started, but no active cache set found.'):\n",
"elif not _wait(lambda: _sysfs_attr(_bcpath(dev)) is not False,\n",
"elif not _wait(lambda: uuid() is not False,\n"
] |
# -*- coding: utf-8 -*-
'''
Module for managing BCache sets
BCache is a block-level caching mechanism similar to ZFS L2ARC/ZIL, dm-cache and fscache.
It works by formatting one block device as a cache set, then adding backend devices
(which need to be formatted as such) to the set and activating them.
It's available in Linux mainline kernel since 3.10
https://www.kernel.org/doc/Documentation/bcache.txt
This module needs the bcache userspace tools to function.
.. versionadded: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import time
import re
from salt.ext import six
# Import salt libs
import salt.utils.path
log = logging.getLogger(__name__)
LOG = {
'trace': logging.TRACE,
'debug': logging.DEBUG,
'info': logging.INFO,
'warn': logging.WARNING,
'error': logging.ERROR,
'crit': logging.CRITICAL,
}
__func_alias__ = {
'attach_': 'attach',
'config_': 'config',
'super_': 'super',
}
HAS_BLKDISCARD = salt.utils.path.which('blkdiscard') is not None
def __virtual__():
'''
Only work when make-bcache is installed
'''
return salt.utils.path.which('make-bcache') is not None
def uuid(dev=None):
'''
Return the bcache UUID of a block device.
If no device is given, the Cache UUID is returned.
CLI example:
.. code-block:: bash
salt '*' bcache.uuid
salt '*' bcache.uuid /dev/sda
salt '*' bcache.uuid bcache0
'''
try:
if dev is None:
# take the only directory in /sys/fs/bcache and return it's basename
return list(salt.utils.path.os_walk('/sys/fs/bcache/'))[0][1][0]
else:
# basename of the /sys/block/{dev}/bcache/cache symlink target
return os.path.basename(_bcsys(dev, 'cache'))
except Exception:
return False
def attach_(dev=None):
'''
Attach a backing devices to a cache set
If no dev is given, all backing devices will be attached.
CLI example:
.. code-block:: bash
salt '*' bcache.attach sdc
salt '*' bcache.attach /dev/bcache1
:return: bool or None if nuttin' happened
'''
cache = uuid()
if not cache:
log.error('No cache to attach %s to', dev)
return False
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = attach_(dev)
return res if res else None
bcache = uuid(dev)
if bcache:
if bcache == cache:
log.info('%s is already attached to bcache %s, doing nothing', dev, cache)
return None
elif not detach(dev):
return False
log.debug('Attaching %s to bcache %s', dev, cache)
if not _bcsys(dev, 'attach', cache,
'error', 'Error attaching {0} to bcache {1}'.format(dev, cache)):
return False
return _wait(lambda: uuid(dev) == cache,
'error', '{0} received attach to bcache {1}, but did not comply'.format(dev, cache))
def detach(dev=None):
'''
Detach a backing device(s) from a cache set
If no dev is given, all backing devices will be attached.
Detaching a backing device will flush it's write cache.
This should leave the underlying device in a consistent state, but might take a while.
CLI example:
.. code-block:: bash
salt '*' bcache.detach sdc
salt '*' bcache.detach bcache1
'''
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = detach(dev)
return res if res else None
log.debug('Detaching %s', dev)
if not _bcsys(dev, 'detach', 'goaway', 'error', 'Error detaching {0}'.format(dev)):
return False
return _wait(lambda: uuid(dev) is False, 'error', '{0} received detach, but did not comply'.format(dev), 300)
def start():
'''
Trigger a start of the full bcache system through udev.
CLI example:
.. code-block:: bash
salt '*' bcache.start
'''
if not _run_all('udevadm trigger', 'error', 'Error starting bcache: %s'):
return False
elif not _wait(lambda: uuid() is not False, 'warn', 'Bcache system started, but no active cache set found.'):
return False
return True
def stop(dev=None):
'''
Stop a bcache device
If no device is given, all backing devices will be detached from the cache, which will subsequently be stopped.
.. warning::
'Stop' on an individual backing device means hard-stop;
no attempt at flushing will be done and the bcache device will seemingly 'disappear' from the device lists
CLI example:
.. code-block:: bash
salt '*' bcache.stop
'''
if dev is not None:
log.warning('Stopping %s, device will only reappear after reregistering!', dev)
if not _bcsys(dev, 'stop', 'goaway', 'error', 'Error stopping {0}'.format(dev)):
return False
return _wait(lambda: _sysfs_attr(_bcpath(dev)) is False, 'error', 'Device {0} did not stop'.format(dev), 300)
else:
cache = uuid()
if not cache:
log.warning('bcache already stopped?')
return None
if not _alltrue(detach()):
return False
elif not _fssys('stop', 'goaway', 'error', 'Error stopping cache'):
return False
return _wait(lambda: uuid() is False, 'error', 'Cache did not stop', 300)
def back_make(dev, cache_mode='writeback', force=False, attach=True, bucket_size=None):
'''
Create a backing device for attachment to a set.
Because the block size must be the same, a cache set already needs to exist.
CLI example:
.. code-block:: bash
salt '*' bcache.back_make sdc cache_mode=writeback attach=True
:param cache_mode: writethrough, writeback, writearound or none.
:param force: Overwrite existing bcaches
:param attach: Immediately attach the backing device to the set
:param bucket_size: Size of a bucket (see kernel doc)
'''
# pylint: disable=too-many-return-statements
cache = uuid()
if not cache:
log.error('No bcache set found')
return False
elif _sysfs_attr(_bcpath(dev)):
if not force:
log.error('%s already contains a bcache. Wipe it manually or use force', dev)
return False
elif uuid(dev) and not detach(dev):
return False
elif not stop(dev):
return False
dev = _devpath(dev)
block_size = _size_map(_fssys('block_size'))
# You might want to override, we pick the cache set's as sane default
if bucket_size is None:
bucket_size = _size_map(_fssys('bucket_size'))
cmd = 'make-bcache --block {0} --bucket {1} --{2} --bdev {3}'.format(block_size, bucket_size, cache_mode, dev)
if force:
cmd += ' --wipe-bcache'
if not _run_all(cmd, 'error', 'Error creating backing device {0}: %s'.format(dev)):
return False
elif not _sysfs_attr('fs/bcache/register', _devpath(dev),
'error', 'Error registering backing device {0}'.format(dev)):
return False
elif not _wait(lambda: _sysfs_attr(_bcpath(dev)) is not False,
'error', 'Backing device {0} did not register'.format(dev)):
return False
elif attach:
return attach_(dev)
return True
def cache_make(dev, reserved=None, force=False, block_size=None, bucket_size=None, attach=True):
'''
Create BCache cache on a block device.
If blkdiscard is available the entire device will be properly cleared in advance.
CLI example:
.. code-block:: bash
salt '*' bcache.cache_make sdb reserved=10% block_size=4096
:param reserved: if dev is a full device, create a partition table with this size empty.
.. note::
this increases the amount of reserved space available to SSD garbage collectors,
potentially (vastly) increasing performance
:param block_size: Block size of the cache; defaults to devices' logical block size
:param force: Overwrite existing BCache sets
:param attach: Attach all existing backend devices immediately
'''
# TODO: multiple devs == md jbod
# pylint: disable=too-many-return-statements
# ---------------- Preflight checks ----------------
cache = uuid()
if cache:
if not force:
log.error('BCache cache %s is already on the system', cache)
return False
cache = _bdev()
dev = _devbase(dev)
udev = __salt__['udev.env'](dev)
if ('ID_FS_TYPE' in udev or (udev.get('DEVTYPE', None) != 'partition' and 'ID_PART_TABLE_TYPE' in udev)) \
and not force:
log.error('%s already contains data, wipe first or force', dev)
return False
elif reserved is not None and udev.get('DEVTYPE', None) != 'disk':
log.error('Need a partitionable blockdev for reserved to work')
return False
_, block, bucket = _sizes(dev)
if bucket_size is None:
bucket_size = bucket
# TODO: bucket from _sizes() makes no sense
bucket_size = False
if block_size is None:
block_size = block
# ---------------- Still here, start doing destructive stuff ----------------
if cache:
if not stop():
return False
# Wipe the current cache device as well,
# forever ruining any chance of it accidentally popping up again
elif not _wipe(cache):
return False
# Can't do enough wiping
if not _wipe(dev):
return False
if reserved:
cmd = 'parted -m -s -a optimal -- ' \
'/dev/{0} mklabel gpt mkpart bcache-reserved 1M {1} mkpart bcache {1} 100%'.format(dev, reserved)
# if wipe was incomplete & part layout remains the same,
# this is one condition set where udev would make it accidentally popup again
if not _run_all(cmd, 'error', 'Error creating bcache partitions on {0}: %s'.format(dev)):
return False
dev = '{0}2'.format(dev)
# ---------------- Finally, create a cache ----------------
cmd = 'make-bcache --cache /dev/{0} --block {1} --wipe-bcache'.format(dev, block_size)
# Actually bucket_size should always have a value, but for testing 0 is possible as well
if bucket_size:
cmd += ' --bucket {0}'.format(bucket_size)
if not _run_all(cmd, 'error', 'Error creating cache {0}: %s'.format(dev)):
return False
elif not _wait(lambda: uuid() is not False,
'error', 'Cache {0} seemingly created OK, but FS did not activate'.format(dev)):
return False
if attach:
return _alltrue(attach_())
else:
return True
def config_(dev=None, **kwargs):
'''
Show or update config of a bcache device.
If no device is given, operate on the cache set itself.
CLI example:
.. code-block:: bash
salt '*' bcache.config
salt '*' bcache.config bcache1
salt '*' bcache.config errors=panic journal_delay_ms=150
salt '*' bcache.config bcache1 cache_mode=writeback writeback_percent=15
:return: config or True/False
'''
if dev is None:
spath = _fspath()
else:
spath = _bcpath(dev)
# filter out 'hidden' kwargs added by our favourite orchestration system
updates = dict([(key, val) for key, val in kwargs.items() if not key.startswith('__')])
if updates:
endres = 0
for key, val in updates.items():
endres += _sysfs_attr([spath, key], val,
'warn', 'Failed to update {0} with {1}'.format(os.path.join(spath, key), val))
return endres > 0
else:
result = {}
data = _sysfs_parse(spath, config=True, internals=True, options=True)
for key in ('other_ro', 'inter_ro'):
if key in data:
del data[key]
for key in data:
result.update(data[key])
return result
def status(stats=False, config=False, internals=False, superblock=False, alldevs=False):
'''
Show the full status of the BCache system and optionally all it's involved devices
CLI example:
.. code-block:: bash
salt '*' bcache.status
salt '*' bcache.status stats=True
salt '*' bcache.status internals=True alldevs=True
:param stats: include statistics
:param config: include settings
:param internals: include internals
:param superblock: include superblock
'''
bdevs = []
for _, links, _ in salt.utils.path.os_walk('/sys/block/'):
for block in links:
if 'bcache' in block:
continue
for spath, sdirs, _ in salt.utils.path.os_walk('/sys/block/{0}'.format(block), followlinks=False):
if 'bcache' in sdirs:
bdevs.append(os.path.basename(spath))
statii = {}
for bcache in bdevs:
statii[bcache] = device(bcache, stats, config, internals, superblock)
cuuid = uuid()
cdev = _bdev()
if cdev:
count = 0
for dev in statii:
if dev != cdev:
# it's a backing dev
if statii[dev]['cache'] == cuuid:
count += 1
statii[cdev]['attached_backing_devices'] = count
if not alldevs:
statii = statii[cdev]
return statii
def device(dev, stats=False, config=False, internals=False, superblock=False):
'''
Check the state of a single bcache device
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc stats=True
:param stats: include statistics
:param settings: include all settings
:param internals: include all internals
:param superblock: include superblock info
'''
result = {}
if not _sysfs_attr(_bcpath(dev), None, 'error', '{0} is not a bcache fo any kind'.format(dev)):
return False
elif _bcsys(dev, 'set'):
# ---------------- It's the cache itself ----------------
result['uuid'] = uuid()
base_attr = ['block_size', 'bucket_size', 'cache_available_percent', 'cache_replacement_policy', 'congested']
# ---------------- Parse through both the blockdev & the FS ----------------
result.update(_sysfs_parse(_bcpath(dev), base_attr, stats, config, internals))
result.update(_sysfs_parse(_fspath(), base_attr, stats, config, internals))
result.update(result.pop('base'))
else:
# ---------------- It's a backing device ----------------
back_uuid = uuid(dev)
if back_uuid is not None:
result['cache'] = back_uuid
try:
result['dev'] = os.path.basename(_bcsys(dev, 'dev'))
except Exception:
pass
result['bdev'] = _bdev(dev)
base_attr = ['cache_mode', 'running', 'state', 'writeback_running']
base_path = _bcpath(dev)
result.update(_sysfs_parse(base_path, base_attr, stats, config, internals))
result.update(result.pop('base'))
# ---------------- Modifications ----------------
state = [result['state']]
if result.pop('running'):
state.append('running')
else:
state.append('stopped')
if 'writeback_running' in result:
if result.pop('writeback_running'):
state.append('writeback_running')
else:
state.append('writeback_stopped')
result['state'] = state
# ---------------- Statistics ----------------
if 'stats' in result:
replre = r'(stats|cache)_'
statres = result['stats']
for attr in result['stats']:
if '/' not in attr:
key = re.sub(replre, '', attr)
statres[key] = statres.pop(attr)
else:
stat, key = attr.split('/', 1)
stat = re.sub(replre, '', stat)
key = re.sub(replre, '', key)
if stat not in statres:
statres[stat] = {}
statres[stat][key] = statres.pop(attr)
result['stats'] = statres
# ---------------- Internals ----------------
if internals:
interres = result.pop('inter_ro', {})
interres.update(result.pop('inter_rw', {}))
if interres:
for key in interres:
if key.startswith('internal'):
nkey = re.sub(r'internal[s/]*', '', key)
interres[nkey] = interres.pop(key)
key = nkey
if key.startswith(('btree', 'writeback')):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in interres:
interres[mkey] = {}
interres[mkey][skey] = interres.pop(key)
result['internals'] = interres
# ---------------- Config ----------------
if config:
configres = result['config']
for key in configres:
if key.startswith('writeback'):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in configres:
configres[mkey] = {}
configres[mkey][skey] = configres.pop(key)
result['config'] = configres
# ---------------- Superblock ----------------
if superblock:
result['superblock'] = super_(dev)
return result
def super_(dev):
'''
Read out BCache SuperBlock
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc
'''
dev = _devpath(dev)
ret = {}
res = _run_all('bcache-super-show {0}'.format(dev), 'error', 'Error reading superblock on {0}: %s'.format(dev))
if not res:
return False
for line in res.splitlines(): # pylint: disable=no-member
line = line.strip()
if not line:
continue
key, val = [val.strip() for val in re.split(r'[\s]+', line, maxsplit=1)]
if not (key and val):
continue
mval = None
if ' ' in val:
rval, mval = [val.strip() for val in re.split(r'[\s]+', val, maxsplit=1)]
mval = mval[1:-1]
else:
rval = val
try:
rval = int(rval)
except Exception:
try:
rval = float(rval)
except Exception:
if rval == 'yes':
rval = True
elif rval == 'no':
rval = False
pkey, key = re.split(r'\.', key, maxsplit=1)
if pkey not in ret:
ret[pkey] = {}
if mval is not None:
ret[pkey][key] = (rval, mval)
else:
ret[pkey][key] = rval
return ret
# -------------------------------- HELPER FUNCTIONS --------------------------------
def _devbase(dev):
'''
Basename of just about any dev
'''
dev = os.path.realpath(os.path.expandvars(dev))
dev = os.path.basename(dev)
return dev
def _devpath(dev):
'''
Return /dev name of just about any dev
:return: /dev/devicename
'''
return os.path.join('/dev', _devbase(dev))
def _syspath(dev):
'''
Full SysFS path of a device
'''
dev = _devbase(dev)
dev = re.sub(r'^([vhs][a-z]+)([0-9]+)', r'\1/\1\2', dev)
# name = re.sub(r'^([a-z]+)(?<!(bcache|md|dm))([0-9]+)', r'\1/\1\2', name)
return os.path.join('/sys/block/', dev)
def _bdev(dev=None):
'''
Resolve a bcacheX or cache to a real dev
:return: basename of bcache dev
'''
if dev is None:
dev = _fssys('cache0')
else:
dev = _bcpath(dev)
if not dev:
return False
else:
return _devbase(os.path.dirname(dev))
def _bcpath(dev):
'''
Full SysFS path of a bcache device
'''
return os.path.join(_syspath(dev), 'bcache')
def _fspath():
'''
:return: path of active bcache
'''
cuuid = uuid()
if not cuuid:
return False
else:
return os.path.join('/sys/fs/bcache/', cuuid)
def _fssys(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with bcache SysFS
'''
fspath = _fspath()
if not fspath:
return False
else:
return _sysfs_attr([fspath, name], value, log_lvl, log_msg)
def _bcsys(dev, name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with backing devs SysFS
'''
return _sysfs_attr([_bcpath(dev), name], value, log_lvl, log_msg)
def _sysfs_attr(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper with logging around sysfs.attr
'''
if isinstance(name, six.string_types):
name = [name]
res = __salt__['sysfs.attr'](os.path.join(*name), value)
if not res and log_lvl is not None and log_msg is not None:
log.log(LOG[log_lvl], log_msg)
return res
def _sysfs_parse(path, base_attr=None, stats=False, config=False, internals=False, options=False):
'''
Helper function for parsing BCache's SysFS interface
'''
result = {}
# ---------------- Parse through the interfaces list ----------------
intfs = __salt__['sysfs.interfaces'](path)
# Actions, we ignore
del intfs['w']
# -------- Sorting hat --------
binkeys = []
if internals:
binkeys.extend(['inter_ro', 'inter_rw'])
if config:
binkeys.append('config')
if stats:
binkeys.append('stats')
bintf = {}
for key in binkeys:
bintf[key] = []
for intf in intfs['r']:
if intf.startswith('internal'):
key = 'inter_ro'
elif 'stats' in intf:
key = 'stats'
else:
# What to do with these???
# I'll utilize 'inter_ro' as 'misc' as well
key = 'inter_ro'
if key in bintf:
bintf[key].append(intf)
for intf in intfs['rw']:
if intf.startswith('internal'):
key = 'inter_rw'
else:
key = 'config'
if key in bintf:
bintf[key].append(intf)
if base_attr is not None:
for intf in bintf:
bintf[intf] = [sintf for sintf in bintf[intf] if sintf not in base_attr]
bintf['base'] = base_attr
mods = {
'stats': ['internal/bset_tree_stats', 'writeback_rate_debug', 'metadata_written', 'nbuckets', 'written',
'average_key_size', 'btree_cache_size'],
}
for modt, modlist in mods.items():
found = []
if modt not in bintf:
continue
for mod in modlist:
for intflist in bintf.values():
if mod in intflist:
found.append(mod)
intflist.remove(mod)
bintf[modt] += found
# -------- Fetch SysFS vals --------
bintflist = [intf for iflist in bintf.values() for intf in iflist]
result.update(__salt__['sysfs.read'](bintflist, path))
# -------- Parse through well known string lists --------
for strlist in ('writeback_rate_debug', 'internal/bset_tree_stats', 'priority_stats'):
if strlist in result:
listres = {}
for line in result[strlist].split('\n'):
key, val = line.split(':', 1)
val = val.strip()
try:
val = int(val)
except Exception:
try:
val = float(val)
except Exception:
pass
listres[key.strip()] = val
result[strlist] = listres
# -------- Parse through selection lists --------
if not options:
for sellist in ('cache_mode', 'cache_replacement_policy', 'errors'):
if sellist in result:
result[sellist] = re.search(r'\[(.+)\]', result[sellist]).groups()[0]
# -------- Parse through well known bools --------
for boolkey in ('running', 'writeback_running', 'congested'):
if boolkey in result:
result[boolkey] = bool(result[boolkey])
# -------- Recategorize results --------
bresult = {}
for iftype, intflist in bintf.items():
ifres = {}
for intf in intflist:
if intf in result:
ifres[intf] = result.pop(intf)
if ifres:
bresult[iftype] = ifres
return bresult
def _size_map(size):
'''
Map Bcache's size strings to real bytes
'''
try:
# I know, I know, EAFP.
# But everything else is reason for None
if not isinstance(size, int):
if re.search(r'[Kk]', size):
size = 1024 * float(re.sub(r'[Kk]', '', size))
elif re.search(r'[Mm]', size):
size = 1024**2 * float(re.sub(r'[Mm]', '', size))
size = int(size)
return size
except Exception:
return None
def _sizes(dev):
'''
Return neigh useless sizing info about a blockdev
:return: (total size in blocks, blocksize, maximum discard size in bytes)
'''
dev = _devbase(dev)
# standarization yay
block_sizes = ('hw_sector_size', 'minimum_io_size', 'physical_block_size', 'logical_block_size')
discard_sizes = ('discard_max_bytes', 'discard_max_hw_bytes', )
sysfs = __salt__['sysfs.read'](
('size',
'queue/hw_sector_size', '../queue/hw_sector_size',
'queue/discard_max_bytes', '../queue/discard_max_bytes'),
root=_syspath(dev))
# TODO: makes no sense
# First of all, it has to be a power of 2
# Secondly, this returns 4GiB - 512b on Intel 3500's for some weird reason
# discard_granularity seems in bytes, resolves to 512b ???
# max_hw_sectors_kb???
# There's also discard_max_hw_bytes more recently
# See: https://www.kernel.org/doc/Documentation/block/queue-sysfs.txt
# Also, I cant find any docs yet regarding bucket sizes;
# it's supposed to be discard_max_hw_bytes,
# but no way to figure that one reliably out apparently
discard = sysfs.get('queue/discard_max_bytes', sysfs.get('../queue/discard_max_bytes', None))
block = sysfs.get('queue/hw_sector_size', sysfs.get('../queue/hw_sector_size', None))
return 512*sysfs['size'], block, discard
def _wipe(dev):
'''
REALLY DESTRUCTIVE STUFF RIGHT AHEAD
'''
endres = 0
dev = _devbase(dev)
size, block, discard = _sizes(dev)
if discard is None:
log.error('Unable to read SysFS props for %s', dev)
return None
elif not discard:
log.warning('%s seems unable to discard', dev)
wiper = 'dd'
elif not HAS_BLKDISCARD:
log.warning('blkdiscard binary not available, properly wipe the dev manually for optimal results')
wiper = 'dd'
else:
wiper = 'blkdiscard'
wipe_failmsg = 'Error wiping {0}: %s'.format(dev)
if wiper == 'dd':
blocks = 4
cmd = 'dd if=/dev/zero of=/dev/{0} bs=1M count={1}'.format(dev, blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# Some stuff (<cough>GPT</cough>) writes stuff at the end of a dev as well
cmd += ' seek={0}'.format((size/1024**2) - blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
elif wiper == 'blkdiscard':
cmd = 'blkdiscard /dev/{0}'.format(dev)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# TODO: fix annoying bug failing blkdiscard by trying to discard 1 sector past blkdev
endres = 1
return endres > 0
def _run_all(cmd, log_lvl=None, log_msg=None, exitcode=0):
'''
Simple wrapper around cmd.run_all
log_msg can contain {0} for stderr
:return: True or stdout, False if retcode wasn't exitcode
'''
res = __salt__['cmd.run_all'](cmd)
if res['retcode'] == exitcode:
if res['stdout']:
return res['stdout']
else:
return True
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg, res['stderr'])
return False
def _alltrue(resdict):
if resdict is None:
return True
return len([val for val in resdict.values() if val]) > 0
|
saltstack/salt
|
salt/modules/bcache.py
|
_run_all
|
python
|
def _run_all(cmd, log_lvl=None, log_msg=None, exitcode=0):
'''
Simple wrapper around cmd.run_all
log_msg can contain {0} for stderr
:return: True or stdout, False if retcode wasn't exitcode
'''
res = __salt__['cmd.run_all'](cmd)
if res['retcode'] == exitcode:
if res['stdout']:
return res['stdout']
else:
return True
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg, res['stderr'])
return False
|
Simple wrapper around cmd.run_all
log_msg can contain {0} for stderr
:return: True or stdout, False if retcode wasn't exitcode
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bcache.py#L939-L954
| null |
# -*- coding: utf-8 -*-
'''
Module for managing BCache sets
BCache is a block-level caching mechanism similar to ZFS L2ARC/ZIL, dm-cache and fscache.
It works by formatting one block device as a cache set, then adding backend devices
(which need to be formatted as such) to the set and activating them.
It's available in Linux mainline kernel since 3.10
https://www.kernel.org/doc/Documentation/bcache.txt
This module needs the bcache userspace tools to function.
.. versionadded: 2016.3.0
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import time
import re
from salt.ext import six
# Import salt libs
import salt.utils.path
log = logging.getLogger(__name__)
LOG = {
'trace': logging.TRACE,
'debug': logging.DEBUG,
'info': logging.INFO,
'warn': logging.WARNING,
'error': logging.ERROR,
'crit': logging.CRITICAL,
}
__func_alias__ = {
'attach_': 'attach',
'config_': 'config',
'super_': 'super',
}
HAS_BLKDISCARD = salt.utils.path.which('blkdiscard') is not None
def __virtual__():
'''
Only work when make-bcache is installed
'''
return salt.utils.path.which('make-bcache') is not None
def uuid(dev=None):
'''
Return the bcache UUID of a block device.
If no device is given, the Cache UUID is returned.
CLI example:
.. code-block:: bash
salt '*' bcache.uuid
salt '*' bcache.uuid /dev/sda
salt '*' bcache.uuid bcache0
'''
try:
if dev is None:
# take the only directory in /sys/fs/bcache and return it's basename
return list(salt.utils.path.os_walk('/sys/fs/bcache/'))[0][1][0]
else:
# basename of the /sys/block/{dev}/bcache/cache symlink target
return os.path.basename(_bcsys(dev, 'cache'))
except Exception:
return False
def attach_(dev=None):
'''
Attach a backing devices to a cache set
If no dev is given, all backing devices will be attached.
CLI example:
.. code-block:: bash
salt '*' bcache.attach sdc
salt '*' bcache.attach /dev/bcache1
:return: bool or None if nuttin' happened
'''
cache = uuid()
if not cache:
log.error('No cache to attach %s to', dev)
return False
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = attach_(dev)
return res if res else None
bcache = uuid(dev)
if bcache:
if bcache == cache:
log.info('%s is already attached to bcache %s, doing nothing', dev, cache)
return None
elif not detach(dev):
return False
log.debug('Attaching %s to bcache %s', dev, cache)
if not _bcsys(dev, 'attach', cache,
'error', 'Error attaching {0} to bcache {1}'.format(dev, cache)):
return False
return _wait(lambda: uuid(dev) == cache,
'error', '{0} received attach to bcache {1}, but did not comply'.format(dev, cache))
def detach(dev=None):
'''
Detach a backing device(s) from a cache set
If no dev is given, all backing devices will be attached.
Detaching a backing device will flush it's write cache.
This should leave the underlying device in a consistent state, but might take a while.
CLI example:
.. code-block:: bash
salt '*' bcache.detach sdc
salt '*' bcache.detach bcache1
'''
if dev is None:
res = {}
for dev, data in status(alldevs=True).items():
if 'cache' in data:
res[dev] = detach(dev)
return res if res else None
log.debug('Detaching %s', dev)
if not _bcsys(dev, 'detach', 'goaway', 'error', 'Error detaching {0}'.format(dev)):
return False
return _wait(lambda: uuid(dev) is False, 'error', '{0} received detach, but did not comply'.format(dev), 300)
def start():
'''
Trigger a start of the full bcache system through udev.
CLI example:
.. code-block:: bash
salt '*' bcache.start
'''
if not _run_all('udevadm trigger', 'error', 'Error starting bcache: %s'):
return False
elif not _wait(lambda: uuid() is not False, 'warn', 'Bcache system started, but no active cache set found.'):
return False
return True
def stop(dev=None):
'''
Stop a bcache device
If no device is given, all backing devices will be detached from the cache, which will subsequently be stopped.
.. warning::
'Stop' on an individual backing device means hard-stop;
no attempt at flushing will be done and the bcache device will seemingly 'disappear' from the device lists
CLI example:
.. code-block:: bash
salt '*' bcache.stop
'''
if dev is not None:
log.warning('Stopping %s, device will only reappear after reregistering!', dev)
if not _bcsys(dev, 'stop', 'goaway', 'error', 'Error stopping {0}'.format(dev)):
return False
return _wait(lambda: _sysfs_attr(_bcpath(dev)) is False, 'error', 'Device {0} did not stop'.format(dev), 300)
else:
cache = uuid()
if not cache:
log.warning('bcache already stopped?')
return None
if not _alltrue(detach()):
return False
elif not _fssys('stop', 'goaway', 'error', 'Error stopping cache'):
return False
return _wait(lambda: uuid() is False, 'error', 'Cache did not stop', 300)
def back_make(dev, cache_mode='writeback', force=False, attach=True, bucket_size=None):
'''
Create a backing device for attachment to a set.
Because the block size must be the same, a cache set already needs to exist.
CLI example:
.. code-block:: bash
salt '*' bcache.back_make sdc cache_mode=writeback attach=True
:param cache_mode: writethrough, writeback, writearound or none.
:param force: Overwrite existing bcaches
:param attach: Immediately attach the backing device to the set
:param bucket_size: Size of a bucket (see kernel doc)
'''
# pylint: disable=too-many-return-statements
cache = uuid()
if not cache:
log.error('No bcache set found')
return False
elif _sysfs_attr(_bcpath(dev)):
if not force:
log.error('%s already contains a bcache. Wipe it manually or use force', dev)
return False
elif uuid(dev) and not detach(dev):
return False
elif not stop(dev):
return False
dev = _devpath(dev)
block_size = _size_map(_fssys('block_size'))
# You might want to override, we pick the cache set's as sane default
if bucket_size is None:
bucket_size = _size_map(_fssys('bucket_size'))
cmd = 'make-bcache --block {0} --bucket {1} --{2} --bdev {3}'.format(block_size, bucket_size, cache_mode, dev)
if force:
cmd += ' --wipe-bcache'
if not _run_all(cmd, 'error', 'Error creating backing device {0}: %s'.format(dev)):
return False
elif not _sysfs_attr('fs/bcache/register', _devpath(dev),
'error', 'Error registering backing device {0}'.format(dev)):
return False
elif not _wait(lambda: _sysfs_attr(_bcpath(dev)) is not False,
'error', 'Backing device {0} did not register'.format(dev)):
return False
elif attach:
return attach_(dev)
return True
def cache_make(dev, reserved=None, force=False, block_size=None, bucket_size=None, attach=True):
'''
Create BCache cache on a block device.
If blkdiscard is available the entire device will be properly cleared in advance.
CLI example:
.. code-block:: bash
salt '*' bcache.cache_make sdb reserved=10% block_size=4096
:param reserved: if dev is a full device, create a partition table with this size empty.
.. note::
this increases the amount of reserved space available to SSD garbage collectors,
potentially (vastly) increasing performance
:param block_size: Block size of the cache; defaults to devices' logical block size
:param force: Overwrite existing BCache sets
:param attach: Attach all existing backend devices immediately
'''
# TODO: multiple devs == md jbod
# pylint: disable=too-many-return-statements
# ---------------- Preflight checks ----------------
cache = uuid()
if cache:
if not force:
log.error('BCache cache %s is already on the system', cache)
return False
cache = _bdev()
dev = _devbase(dev)
udev = __salt__['udev.env'](dev)
if ('ID_FS_TYPE' in udev or (udev.get('DEVTYPE', None) != 'partition' and 'ID_PART_TABLE_TYPE' in udev)) \
and not force:
log.error('%s already contains data, wipe first or force', dev)
return False
elif reserved is not None and udev.get('DEVTYPE', None) != 'disk':
log.error('Need a partitionable blockdev for reserved to work')
return False
_, block, bucket = _sizes(dev)
if bucket_size is None:
bucket_size = bucket
# TODO: bucket from _sizes() makes no sense
bucket_size = False
if block_size is None:
block_size = block
# ---------------- Still here, start doing destructive stuff ----------------
if cache:
if not stop():
return False
# Wipe the current cache device as well,
# forever ruining any chance of it accidentally popping up again
elif not _wipe(cache):
return False
# Can't do enough wiping
if not _wipe(dev):
return False
if reserved:
cmd = 'parted -m -s -a optimal -- ' \
'/dev/{0} mklabel gpt mkpart bcache-reserved 1M {1} mkpart bcache {1} 100%'.format(dev, reserved)
# if wipe was incomplete & part layout remains the same,
# this is one condition set where udev would make it accidentally popup again
if not _run_all(cmd, 'error', 'Error creating bcache partitions on {0}: %s'.format(dev)):
return False
dev = '{0}2'.format(dev)
# ---------------- Finally, create a cache ----------------
cmd = 'make-bcache --cache /dev/{0} --block {1} --wipe-bcache'.format(dev, block_size)
# Actually bucket_size should always have a value, but for testing 0 is possible as well
if bucket_size:
cmd += ' --bucket {0}'.format(bucket_size)
if not _run_all(cmd, 'error', 'Error creating cache {0}: %s'.format(dev)):
return False
elif not _wait(lambda: uuid() is not False,
'error', 'Cache {0} seemingly created OK, but FS did not activate'.format(dev)):
return False
if attach:
return _alltrue(attach_())
else:
return True
def config_(dev=None, **kwargs):
'''
Show or update config of a bcache device.
If no device is given, operate on the cache set itself.
CLI example:
.. code-block:: bash
salt '*' bcache.config
salt '*' bcache.config bcache1
salt '*' bcache.config errors=panic journal_delay_ms=150
salt '*' bcache.config bcache1 cache_mode=writeback writeback_percent=15
:return: config or True/False
'''
if dev is None:
spath = _fspath()
else:
spath = _bcpath(dev)
# filter out 'hidden' kwargs added by our favourite orchestration system
updates = dict([(key, val) for key, val in kwargs.items() if not key.startswith('__')])
if updates:
endres = 0
for key, val in updates.items():
endres += _sysfs_attr([spath, key], val,
'warn', 'Failed to update {0} with {1}'.format(os.path.join(spath, key), val))
return endres > 0
else:
result = {}
data = _sysfs_parse(spath, config=True, internals=True, options=True)
for key in ('other_ro', 'inter_ro'):
if key in data:
del data[key]
for key in data:
result.update(data[key])
return result
def status(stats=False, config=False, internals=False, superblock=False, alldevs=False):
'''
Show the full status of the BCache system and optionally all it's involved devices
CLI example:
.. code-block:: bash
salt '*' bcache.status
salt '*' bcache.status stats=True
salt '*' bcache.status internals=True alldevs=True
:param stats: include statistics
:param config: include settings
:param internals: include internals
:param superblock: include superblock
'''
bdevs = []
for _, links, _ in salt.utils.path.os_walk('/sys/block/'):
for block in links:
if 'bcache' in block:
continue
for spath, sdirs, _ in salt.utils.path.os_walk('/sys/block/{0}'.format(block), followlinks=False):
if 'bcache' in sdirs:
bdevs.append(os.path.basename(spath))
statii = {}
for bcache in bdevs:
statii[bcache] = device(bcache, stats, config, internals, superblock)
cuuid = uuid()
cdev = _bdev()
if cdev:
count = 0
for dev in statii:
if dev != cdev:
# it's a backing dev
if statii[dev]['cache'] == cuuid:
count += 1
statii[cdev]['attached_backing_devices'] = count
if not alldevs:
statii = statii[cdev]
return statii
def device(dev, stats=False, config=False, internals=False, superblock=False):
'''
Check the state of a single bcache device
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc stats=True
:param stats: include statistics
:param settings: include all settings
:param internals: include all internals
:param superblock: include superblock info
'''
result = {}
if not _sysfs_attr(_bcpath(dev), None, 'error', '{0} is not a bcache fo any kind'.format(dev)):
return False
elif _bcsys(dev, 'set'):
# ---------------- It's the cache itself ----------------
result['uuid'] = uuid()
base_attr = ['block_size', 'bucket_size', 'cache_available_percent', 'cache_replacement_policy', 'congested']
# ---------------- Parse through both the blockdev & the FS ----------------
result.update(_sysfs_parse(_bcpath(dev), base_attr, stats, config, internals))
result.update(_sysfs_parse(_fspath(), base_attr, stats, config, internals))
result.update(result.pop('base'))
else:
# ---------------- It's a backing device ----------------
back_uuid = uuid(dev)
if back_uuid is not None:
result['cache'] = back_uuid
try:
result['dev'] = os.path.basename(_bcsys(dev, 'dev'))
except Exception:
pass
result['bdev'] = _bdev(dev)
base_attr = ['cache_mode', 'running', 'state', 'writeback_running']
base_path = _bcpath(dev)
result.update(_sysfs_parse(base_path, base_attr, stats, config, internals))
result.update(result.pop('base'))
# ---------------- Modifications ----------------
state = [result['state']]
if result.pop('running'):
state.append('running')
else:
state.append('stopped')
if 'writeback_running' in result:
if result.pop('writeback_running'):
state.append('writeback_running')
else:
state.append('writeback_stopped')
result['state'] = state
# ---------------- Statistics ----------------
if 'stats' in result:
replre = r'(stats|cache)_'
statres = result['stats']
for attr in result['stats']:
if '/' not in attr:
key = re.sub(replre, '', attr)
statres[key] = statres.pop(attr)
else:
stat, key = attr.split('/', 1)
stat = re.sub(replre, '', stat)
key = re.sub(replre, '', key)
if stat not in statres:
statres[stat] = {}
statres[stat][key] = statres.pop(attr)
result['stats'] = statres
# ---------------- Internals ----------------
if internals:
interres = result.pop('inter_ro', {})
interres.update(result.pop('inter_rw', {}))
if interres:
for key in interres:
if key.startswith('internal'):
nkey = re.sub(r'internal[s/]*', '', key)
interres[nkey] = interres.pop(key)
key = nkey
if key.startswith(('btree', 'writeback')):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in interres:
interres[mkey] = {}
interres[mkey][skey] = interres.pop(key)
result['internals'] = interres
# ---------------- Config ----------------
if config:
configres = result['config']
for key in configres:
if key.startswith('writeback'):
mkey, skey = re.split(r'_', key, maxsplit=1)
if mkey not in configres:
configres[mkey] = {}
configres[mkey][skey] = configres.pop(key)
result['config'] = configres
# ---------------- Superblock ----------------
if superblock:
result['superblock'] = super_(dev)
return result
def super_(dev):
'''
Read out BCache SuperBlock
CLI example:
.. code-block:: bash
salt '*' bcache.device bcache0
salt '*' bcache.device /dev/sdc
'''
dev = _devpath(dev)
ret = {}
res = _run_all('bcache-super-show {0}'.format(dev), 'error', 'Error reading superblock on {0}: %s'.format(dev))
if not res:
return False
for line in res.splitlines(): # pylint: disable=no-member
line = line.strip()
if not line:
continue
key, val = [val.strip() for val in re.split(r'[\s]+', line, maxsplit=1)]
if not (key and val):
continue
mval = None
if ' ' in val:
rval, mval = [val.strip() for val in re.split(r'[\s]+', val, maxsplit=1)]
mval = mval[1:-1]
else:
rval = val
try:
rval = int(rval)
except Exception:
try:
rval = float(rval)
except Exception:
if rval == 'yes':
rval = True
elif rval == 'no':
rval = False
pkey, key = re.split(r'\.', key, maxsplit=1)
if pkey not in ret:
ret[pkey] = {}
if mval is not None:
ret[pkey][key] = (rval, mval)
else:
ret[pkey][key] = rval
return ret
# -------------------------------- HELPER FUNCTIONS --------------------------------
def _devbase(dev):
'''
Basename of just about any dev
'''
dev = os.path.realpath(os.path.expandvars(dev))
dev = os.path.basename(dev)
return dev
def _devpath(dev):
'''
Return /dev name of just about any dev
:return: /dev/devicename
'''
return os.path.join('/dev', _devbase(dev))
def _syspath(dev):
'''
Full SysFS path of a device
'''
dev = _devbase(dev)
dev = re.sub(r'^([vhs][a-z]+)([0-9]+)', r'\1/\1\2', dev)
# name = re.sub(r'^([a-z]+)(?<!(bcache|md|dm))([0-9]+)', r'\1/\1\2', name)
return os.path.join('/sys/block/', dev)
def _bdev(dev=None):
'''
Resolve a bcacheX or cache to a real dev
:return: basename of bcache dev
'''
if dev is None:
dev = _fssys('cache0')
else:
dev = _bcpath(dev)
if not dev:
return False
else:
return _devbase(os.path.dirname(dev))
def _bcpath(dev):
'''
Full SysFS path of a bcache device
'''
return os.path.join(_syspath(dev), 'bcache')
def _fspath():
'''
:return: path of active bcache
'''
cuuid = uuid()
if not cuuid:
return False
else:
return os.path.join('/sys/fs/bcache/', cuuid)
def _fssys(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with bcache SysFS
'''
fspath = _fspath()
if not fspath:
return False
else:
return _sysfs_attr([fspath, name], value, log_lvl, log_msg)
def _bcsys(dev, name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper to interface with backing devs SysFS
'''
return _sysfs_attr([_bcpath(dev), name], value, log_lvl, log_msg)
def _sysfs_attr(name, value=None, log_lvl=None, log_msg=None):
'''
Simple wrapper with logging around sysfs.attr
'''
if isinstance(name, six.string_types):
name = [name]
res = __salt__['sysfs.attr'](os.path.join(*name), value)
if not res and log_lvl is not None and log_msg is not None:
log.log(LOG[log_lvl], log_msg)
return res
def _sysfs_parse(path, base_attr=None, stats=False, config=False, internals=False, options=False):
'''
Helper function for parsing BCache's SysFS interface
'''
result = {}
# ---------------- Parse through the interfaces list ----------------
intfs = __salt__['sysfs.interfaces'](path)
# Actions, we ignore
del intfs['w']
# -------- Sorting hat --------
binkeys = []
if internals:
binkeys.extend(['inter_ro', 'inter_rw'])
if config:
binkeys.append('config')
if stats:
binkeys.append('stats')
bintf = {}
for key in binkeys:
bintf[key] = []
for intf in intfs['r']:
if intf.startswith('internal'):
key = 'inter_ro'
elif 'stats' in intf:
key = 'stats'
else:
# What to do with these???
# I'll utilize 'inter_ro' as 'misc' as well
key = 'inter_ro'
if key in bintf:
bintf[key].append(intf)
for intf in intfs['rw']:
if intf.startswith('internal'):
key = 'inter_rw'
else:
key = 'config'
if key in bintf:
bintf[key].append(intf)
if base_attr is not None:
for intf in bintf:
bintf[intf] = [sintf for sintf in bintf[intf] if sintf not in base_attr]
bintf['base'] = base_attr
mods = {
'stats': ['internal/bset_tree_stats', 'writeback_rate_debug', 'metadata_written', 'nbuckets', 'written',
'average_key_size', 'btree_cache_size'],
}
for modt, modlist in mods.items():
found = []
if modt not in bintf:
continue
for mod in modlist:
for intflist in bintf.values():
if mod in intflist:
found.append(mod)
intflist.remove(mod)
bintf[modt] += found
# -------- Fetch SysFS vals --------
bintflist = [intf for iflist in bintf.values() for intf in iflist]
result.update(__salt__['sysfs.read'](bintflist, path))
# -------- Parse through well known string lists --------
for strlist in ('writeback_rate_debug', 'internal/bset_tree_stats', 'priority_stats'):
if strlist in result:
listres = {}
for line in result[strlist].split('\n'):
key, val = line.split(':', 1)
val = val.strip()
try:
val = int(val)
except Exception:
try:
val = float(val)
except Exception:
pass
listres[key.strip()] = val
result[strlist] = listres
# -------- Parse through selection lists --------
if not options:
for sellist in ('cache_mode', 'cache_replacement_policy', 'errors'):
if sellist in result:
result[sellist] = re.search(r'\[(.+)\]', result[sellist]).groups()[0]
# -------- Parse through well known bools --------
for boolkey in ('running', 'writeback_running', 'congested'):
if boolkey in result:
result[boolkey] = bool(result[boolkey])
# -------- Recategorize results --------
bresult = {}
for iftype, intflist in bintf.items():
ifres = {}
for intf in intflist:
if intf in result:
ifres[intf] = result.pop(intf)
if ifres:
bresult[iftype] = ifres
return bresult
def _size_map(size):
'''
Map Bcache's size strings to real bytes
'''
try:
# I know, I know, EAFP.
# But everything else is reason for None
if not isinstance(size, int):
if re.search(r'[Kk]', size):
size = 1024 * float(re.sub(r'[Kk]', '', size))
elif re.search(r'[Mm]', size):
size = 1024**2 * float(re.sub(r'[Mm]', '', size))
size = int(size)
return size
except Exception:
return None
def _sizes(dev):
'''
Return neigh useless sizing info about a blockdev
:return: (total size in blocks, blocksize, maximum discard size in bytes)
'''
dev = _devbase(dev)
# standarization yay
block_sizes = ('hw_sector_size', 'minimum_io_size', 'physical_block_size', 'logical_block_size')
discard_sizes = ('discard_max_bytes', 'discard_max_hw_bytes', )
sysfs = __salt__['sysfs.read'](
('size',
'queue/hw_sector_size', '../queue/hw_sector_size',
'queue/discard_max_bytes', '../queue/discard_max_bytes'),
root=_syspath(dev))
# TODO: makes no sense
# First of all, it has to be a power of 2
# Secondly, this returns 4GiB - 512b on Intel 3500's for some weird reason
# discard_granularity seems in bytes, resolves to 512b ???
# max_hw_sectors_kb???
# There's also discard_max_hw_bytes more recently
# See: https://www.kernel.org/doc/Documentation/block/queue-sysfs.txt
# Also, I cant find any docs yet regarding bucket sizes;
# it's supposed to be discard_max_hw_bytes,
# but no way to figure that one reliably out apparently
discard = sysfs.get('queue/discard_max_bytes', sysfs.get('../queue/discard_max_bytes', None))
block = sysfs.get('queue/hw_sector_size', sysfs.get('../queue/hw_sector_size', None))
return 512*sysfs['size'], block, discard
def _wipe(dev):
'''
REALLY DESTRUCTIVE STUFF RIGHT AHEAD
'''
endres = 0
dev = _devbase(dev)
size, block, discard = _sizes(dev)
if discard is None:
log.error('Unable to read SysFS props for %s', dev)
return None
elif not discard:
log.warning('%s seems unable to discard', dev)
wiper = 'dd'
elif not HAS_BLKDISCARD:
log.warning('blkdiscard binary not available, properly wipe the dev manually for optimal results')
wiper = 'dd'
else:
wiper = 'blkdiscard'
wipe_failmsg = 'Error wiping {0}: %s'.format(dev)
if wiper == 'dd':
blocks = 4
cmd = 'dd if=/dev/zero of=/dev/{0} bs=1M count={1}'.format(dev, blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# Some stuff (<cough>GPT</cough>) writes stuff at the end of a dev as well
cmd += ' seek={0}'.format((size/1024**2) - blocks)
endres += _run_all(cmd, 'warn', wipe_failmsg)
elif wiper == 'blkdiscard':
cmd = 'blkdiscard /dev/{0}'.format(dev)
endres += _run_all(cmd, 'warn', wipe_failmsg)
# TODO: fix annoying bug failing blkdiscard by trying to discard 1 sector past blkdev
endres = 1
return endres > 0
def _wait(lfunc, log_lvl=None, log_msg=None, tries=10):
'''
Wait for lfunc to be True
:return: True if lfunc succeeded within tries, False if it didn't
'''
i = 0
while i < tries:
time.sleep(1)
if lfunc():
return True
else:
i += 1
if log_lvl is not None:
log.log(LOG[log_lvl], log_msg)
return False
def _alltrue(resdict):
if resdict is None:
return True
return len([val for val in resdict.values() if val]) > 0
|
saltstack/salt
|
salt/modules/salt_version.py
|
get_release_number
|
python
|
def get_release_number(name):
'''
Returns the release number of a given release code name in a
``<year>.<month>`` context.
If the release name has not been given an assigned release number, the
function returns a string. If the release cannot be found, it returns
``None``.
name
The release codename for which to find a release number.
CLI Example:
.. code-block:: bash
salt '*' salt_version.get_release_number 'Oxygen'
'''
name = name.lower()
version_map = salt.version.SaltStackVersion.LNAMES
version = version_map.get(name)
if version is None:
log.info('Version %s not found.', name)
return None
if version[1] == 0:
log.info('Version %s found, but no release number has been assigned yet.', name)
return 'No version assigned.'
return '.'.join(str(item) for item in version)
|
Returns the release number of a given release code name in a
``<year>.<month>`` context.
If the release name has not been given an assigned release number, the
function returns a string. If the release cannot be found, it returns
``None``.
name
The release codename for which to find a release number.
CLI Example:
.. code-block:: bash
salt '*' salt_version.get_release_number 'Oxygen'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/salt_version.py#L56-L85
| null |
# -*- coding: utf-8 -*-
'''
Access Salt's elemental release code-names.
.. versionadded:: Neon
Salt's feature release schedule is based on the Periodic Table, as described
in the :ref:`Version Numbers <version-numbers>` documentation.
Since deprecation notices often use the elemental release code-name when warning
users about deprecated changes, it can be difficult to build out future-proof
functionality that are dependent on a naming scheme that moves.
For example, a state syntax needs to change to support an option that will be
removed in the future, but there are many Minion versions in use across an
infrastructure. It would be handy to use some Jinja syntax to check for these
instances to perform one state syntax over another.
A simple example might be something like the following:
.. code-block:: jinja
{# a boolean check #}
{% set option_deprecated = salt['salt_version.is_older']("Sodium") %}
{% if option_deprecated %}
<use old syntax>
{% else %}
<use new syntax>
{% endif %}
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
from salt.ext import six
import salt.version
import salt.utils.versions
log = logging.getLogger(__name__)
__virtualname__ = 'salt_version'
def __virtual__():
'''
Only work on POSIX-like systems
'''
return __virtualname__
def is_equal(name):
'''
Returns a boolean if the named version matches the minion's current Salt
version.
name
The release codename to check the version against.
CLI Example:
.. code-block:: bash
salt '*' salt_version.is_equal 'Oxygen'
'''
if _check_release_cmp(name) == 0:
log.info('Release codename \'%s\' equals the minion\'s version.', name)
return True
return False
def is_newer(name):
'''
Returns a boolean if the named version is newer that the minion's current
Salt version.
name
The release codename to check the version against.
CLI Example:
.. code-block:: bash
salt '*' salt_version.is_newer 'Sodium'
'''
if _check_release_cmp(name) == 1:
log.info('Release codename \'%s\' is newer than the minion\'s version.', name)
return True
return False
def is_older(name):
'''
Returns a boolean if the named version is older that the minion's current
Salt version.
name
The release codename to check the version against.
CLI Example:
.. code-block:: bash
salt '*' salt_version.is_newer 'Sodium'
'''
if _check_release_cmp(name) == -1:
log.info('Release codename \'%s\' is older than the minion\'s version.', name)
return True
return False
def _check_release_cmp(name):
'''
Helper function to compare release codename versions to the minion's current
Salt version.
If release codename isn't found, the function returns None. Otherwise, it
returns the results of the version comparison as documented by the
``versions_cmp`` function in ``salt.utils.versions.py``.
'''
map_version = get_release_number(name)
if map_version is None:
log.info('Release codename %s was not found.', name)
return None
current_version = six.text_type(salt.version.SaltStackVersion(
*salt.version.__version_info__))
current_version = current_version.rsplit('.', 1)[0]
version_cmp = salt.utils.versions.version_cmp(map_version, current_version)
return version_cmp
|
saltstack/salt
|
salt/modules/salt_version.py
|
_check_release_cmp
|
python
|
def _check_release_cmp(name):
'''
Helper function to compare release codename versions to the minion's current
Salt version.
If release codename isn't found, the function returns None. Otherwise, it
returns the results of the version comparison as documented by the
``versions_cmp`` function in ``salt.utils.versions.py``.
'''
map_version = get_release_number(name)
if map_version is None:
log.info('Release codename %s was not found.', name)
return None
current_version = six.text_type(salt.version.SaltStackVersion(
*salt.version.__version_info__))
current_version = current_version.rsplit('.', 1)[0]
version_cmp = salt.utils.versions.version_cmp(map_version, current_version)
return version_cmp
|
Helper function to compare release codename versions to the minion's current
Salt version.
If release codename isn't found, the function returns None. Otherwise, it
returns the results of the version comparison as documented by the
``versions_cmp`` function in ``salt.utils.versions.py``.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/salt_version.py#L151-L170
|
[
"def version_cmp(pkg1, pkg2, ignore_epoch=False):\n '''\n Compares two version strings using salt.utils.versions.LooseVersion. This\n is a fallback for providers which don't have a version comparison utility\n built into them. Return -1 if version1 < version2, 0 if version1 ==\n version2, and 1 if version1 > version2. Return None if there was a problem\n making the comparison.\n '''\n normalize = lambda x: six.text_type(x).split(':', 1)[-1] \\\n if ignore_epoch else six.text_type(x)\n pkg1 = normalize(pkg1)\n pkg2 = normalize(pkg2)\n\n try:\n # pylint: disable=no-member\n if LooseVersion(pkg1) < LooseVersion(pkg2):\n return -1\n elif LooseVersion(pkg1) == LooseVersion(pkg2):\n return 0\n elif LooseVersion(pkg1) > LooseVersion(pkg2):\n return 1\n except Exception as exc:\n log.exception(exc)\n return None\n",
"def get_release_number(name):\n '''\n Returns the release number of a given release code name in a\n ``<year>.<month>`` context.\n\n If the release name has not been given an assigned release number, the\n function returns a string. If the release cannot be found, it returns\n ``None``.\n\n name\n The release codename for which to find a release number.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' salt_version.get_release_number 'Oxygen'\n '''\n name = name.lower()\n version_map = salt.version.SaltStackVersion.LNAMES\n version = version_map.get(name)\n if version is None:\n log.info('Version %s not found.', name)\n return None\n\n if version[1] == 0:\n log.info('Version %s found, but no release number has been assigned yet.', name)\n return 'No version assigned.'\n\n return '.'.join(str(item) for item in version)\n"
] |
# -*- coding: utf-8 -*-
'''
Access Salt's elemental release code-names.
.. versionadded:: Neon
Salt's feature release schedule is based on the Periodic Table, as described
in the :ref:`Version Numbers <version-numbers>` documentation.
Since deprecation notices often use the elemental release code-name when warning
users about deprecated changes, it can be difficult to build out future-proof
functionality that are dependent on a naming scheme that moves.
For example, a state syntax needs to change to support an option that will be
removed in the future, but there are many Minion versions in use across an
infrastructure. It would be handy to use some Jinja syntax to check for these
instances to perform one state syntax over another.
A simple example might be something like the following:
.. code-block:: jinja
{# a boolean check #}
{% set option_deprecated = salt['salt_version.is_older']("Sodium") %}
{% if option_deprecated %}
<use old syntax>
{% else %}
<use new syntax>
{% endif %}
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
from salt.ext import six
import salt.version
import salt.utils.versions
log = logging.getLogger(__name__)
__virtualname__ = 'salt_version'
def __virtual__():
'''
Only work on POSIX-like systems
'''
return __virtualname__
def get_release_number(name):
'''
Returns the release number of a given release code name in a
``<year>.<month>`` context.
If the release name has not been given an assigned release number, the
function returns a string. If the release cannot be found, it returns
``None``.
name
The release codename for which to find a release number.
CLI Example:
.. code-block:: bash
salt '*' salt_version.get_release_number 'Oxygen'
'''
name = name.lower()
version_map = salt.version.SaltStackVersion.LNAMES
version = version_map.get(name)
if version is None:
log.info('Version %s not found.', name)
return None
if version[1] == 0:
log.info('Version %s found, but no release number has been assigned yet.', name)
return 'No version assigned.'
return '.'.join(str(item) for item in version)
def is_equal(name):
'''
Returns a boolean if the named version matches the minion's current Salt
version.
name
The release codename to check the version against.
CLI Example:
.. code-block:: bash
salt '*' salt_version.is_equal 'Oxygen'
'''
if _check_release_cmp(name) == 0:
log.info('Release codename \'%s\' equals the minion\'s version.', name)
return True
return False
def is_newer(name):
'''
Returns a boolean if the named version is newer that the minion's current
Salt version.
name
The release codename to check the version against.
CLI Example:
.. code-block:: bash
salt '*' salt_version.is_newer 'Sodium'
'''
if _check_release_cmp(name) == 1:
log.info('Release codename \'%s\' is newer than the minion\'s version.', name)
return True
return False
def is_older(name):
'''
Returns a boolean if the named version is older that the minion's current
Salt version.
name
The release codename to check the version against.
CLI Example:
.. code-block:: bash
salt '*' salt_version.is_newer 'Sodium'
'''
if _check_release_cmp(name) == -1:
log.info('Release codename \'%s\' is older than the minion\'s version.', name)
return True
return False
|
saltstack/salt
|
salt/modules/rbenv.py
|
install
|
python
|
def install(runas=None, path=None):
'''
Install rbenv systemwide
CLI Example:
.. code-block:: bash
salt '*' rbenv.install
'''
path = path or _rbenv_path(runas)
path = os.path.expanduser(path)
return _install_rbenv(path, runas) and _install_ruby_build(path, runas)
|
Install rbenv systemwide
CLI Example:
.. code-block:: bash
salt '*' rbenv.install
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rbenv.py#L159-L171
|
[
"def _rbenv_path(runas=None):\n path = None\n if runas in (None, 'root'):\n path = __salt__['config.option']('rbenv.root') or '/usr/local/rbenv'\n else:\n path = __salt__['config.option']('rbenv.root') \\\n or '~{0}/.rbenv'.format(runas)\n\n return os.path.expanduser(path)\n",
"def _install_rbenv(path, runas=None):\n if os.path.isdir(path):\n return True\n\n cmd = ['git', 'clone', 'https://github.com/sstephenson/rbenv.git', path]\n return __salt__['cmd.retcode'](cmd, runas=runas, python_shell=False) == 0\n",
"def _install_ruby_build(path, runas=None):\n path = '{0}/plugins/ruby-build'.format(path)\n if os.path.isdir(path):\n return True\n\n cmd = ['git', 'clone',\n 'https://github.com/sstephenson/ruby-build.git', path]\n return __salt__['cmd.retcode'](cmd, runas=runas, python_shell=False) == 0\n"
] |
# -*- coding: utf-8 -*-
'''
Manage ruby installations with rbenv. rbenv is supported on Linux and macOS.
rbenv doesn't work on Windows (and isn't really necessary on Windows as there is
no system Ruby on Windows). On Windows, the RubyInstaller and/or Pik are both
good alternatives to work with multiple versions of Ruby on the same box.
http://misheska.com/blog/2013/06/15/using-rbenv-to-manage-multiple-versions-of-ruby/
.. versionadded:: 0.16.0
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import os
import re
import logging
# Import Salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.path
import salt.utils.platform
from salt.exceptions import SaltInvocationError
# Import 3rd-party libs
from salt.ext import six
# Set up logger
log = logging.getLogger(__name__)
__func_alias__ = {
'list_': 'list'
}
__opts__ = {
'rbenv.root': None,
'rbenv.build_env': None,
}
def __virtual__():
'''
Only work on POSIX-like systems
'''
if salt.utils.platform.is_windows():
return (False, 'The rbenv execution module failed to load: only available on non-Windows systems.')
return True
def _shlex_split(s):
# from python:salt.utils.args.shlex_split: passing None for s will read
# the string to split from standard input.
if s is None:
ret = salt.utils.args.shlex_split('')
else:
ret = salt.utils.args.shlex_split(s)
return ret
def _parse_env(env):
if not env:
env = {}
if isinstance(env, list):
env = salt.utils.data.repack_dictlist(env)
if not isinstance(env, dict):
env = {}
for bad_env_key in (x for x, y in six.iteritems(env) if y is None):
log.error('Environment variable \'%s\' passed without a value. '
'Setting value to an empty string', bad_env_key)
env[bad_env_key] = ''
return env
def _rbenv_bin(runas=None):
path = _rbenv_path(runas)
return '{0}/bin/rbenv'.format(path)
def _rbenv_path(runas=None):
path = None
if runas in (None, 'root'):
path = __salt__['config.option']('rbenv.root') or '/usr/local/rbenv'
else:
path = __salt__['config.option']('rbenv.root') \
or '~{0}/.rbenv'.format(runas)
return os.path.expanduser(path)
def _rbenv_exec(command, env=None, runas=None, ret=None):
if not is_installed(runas):
return False
binary = _rbenv_bin(runas)
path = _rbenv_path(runas)
environ = _parse_env(env)
environ['RBENV_ROOT'] = path
result = __salt__['cmd.run_all'](
[binary] + command,
runas=runas,
env=environ
)
if isinstance(ret, dict):
ret.update(result)
return ret
if result['retcode'] == 0:
return result['stdout']
else:
return False
def _install_rbenv(path, runas=None):
if os.path.isdir(path):
return True
cmd = ['git', 'clone', 'https://github.com/sstephenson/rbenv.git', path]
return __salt__['cmd.retcode'](cmd, runas=runas, python_shell=False) == 0
def _install_ruby_build(path, runas=None):
path = '{0}/plugins/ruby-build'.format(path)
if os.path.isdir(path):
return True
cmd = ['git', 'clone',
'https://github.com/sstephenson/ruby-build.git', path]
return __salt__['cmd.retcode'](cmd, runas=runas, python_shell=False) == 0
def _update_rbenv(path, runas=None):
if not os.path.isdir(path):
return False
return __salt__['cmd.retcode'](['git', 'pull'],
runas=runas,
cwd=path,
python_shell=False) == 0
def _update_ruby_build(path, runas=None):
path = '{0}/plugins/ruby-build'.format(path)
if not os.path.isdir(path):
return False
return __salt__['cmd.retcode'](['git', 'pull'],
runas=runas,
cwd=path,
python_shell=False) == 0
def update(runas=None, path=None):
'''
Updates the current versions of rbenv and ruby-build
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.update
'''
path = path or _rbenv_path(runas)
path = os.path.expanduser(path)
return _update_rbenv(path, runas) and _update_ruby_build(path, runas)
def is_installed(runas=None):
'''
Check if rbenv is installed
CLI Example:
.. code-block:: bash
salt '*' rbenv.is_installed
'''
return __salt__['cmd.has_exec'](_rbenv_bin(runas))
def install_ruby(ruby, runas=None):
'''
Install a ruby implementation.
ruby
The version of Ruby to install, should match one of the
versions listed by :py:func:`rbenv.list <salt.modules.rbenv.list>`
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
Additional environment variables can be configured in pillar /
grains / master:
.. code-block:: yaml
rbenv:
build_env: 'CONFIGURE_OPTS="--no-tcmalloc" CFLAGS="-fno-tree-dce"'
CLI Example:
.. code-block:: bash
salt '*' rbenv.install_ruby 2.0.0-p0
'''
ruby = re.sub(r'^ruby-', '', ruby)
env = None
env_list = []
if __grains__['os'] in ('FreeBSD', 'NetBSD', 'OpenBSD'):
env_list.append('MAKE=gmake')
if __salt__['config.get']('rbenv:build_env'):
env_list.append(__salt__['config.get']('rbenv:build_env'))
elif __salt__['config.option']('rbenv.build_env'):
env_list.append(__salt__['config.option']('rbenv.build_env'))
if env_list:
env = ' '.join(env_list)
ret = {}
ret = _rbenv_exec(['install', ruby], env=env, runas=runas, ret=ret)
if ret is not False and ret['retcode'] == 0:
rehash(runas=runas)
return ret['stderr']
else:
# Cleanup the failed installation so it doesn't list as installed
uninstall_ruby(ruby, runas=runas)
return False
def uninstall_ruby(ruby, runas=None):
'''
Uninstall a ruby implementation.
ruby
The version of ruby to uninstall. Should match one of the versions
listed by :py:func:`rbenv.versions <salt.modules.rbenv.versions>`.
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.uninstall_ruby 2.0.0-p0
'''
ruby = re.sub(r'^ruby-', '', ruby)
_rbenv_exec(['uninstall', '--force', ruby], runas=runas)
return True
def versions(runas=None):
'''
List the installed versions of ruby
CLI Example:
.. code-block:: bash
salt '*' rbenv.versions
'''
ret = _rbenv_exec(['versions', '--bare'], runas=runas)
return [] if ret is False else ret.splitlines()
def default(ruby=None, runas=None):
'''
Returns or sets the currently defined default ruby
ruby
The version to set as the default. Should match one of the versions
listed by :py:func:`rbenv.versions <salt.modules.rbenv.versions>`.
Leave blank to return the current default.
CLI Example:
.. code-block:: bash
salt '*' rbenv.default
salt '*' rbenv.default 2.0.0-p0
'''
if ruby:
_rbenv_exec(['global', ruby], runas=runas)
return True
else:
ret = _rbenv_exec(['global'], runas=runas)
return '' if ret is False else ret.strip()
def list_(runas=None):
'''
List the installable versions of ruby
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.list
'''
ret = []
output = _rbenv_exec(['install', '--list'], runas=runas)
if output:
for line in output.splitlines():
if line == 'Available versions:':
continue
ret.append(line.strip())
return ret
def rehash(runas=None):
'''
Run ``rbenv rehash`` to update the installed shims
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.rehash
'''
_rbenv_exec(['rehash'], runas=runas)
return True
def do(cmdline, runas=None, env=None):
'''
Execute a ruby command with rbenv's shims from the user or the system
CLI Example:
.. code-block:: bash
salt '*' rbenv.do 'gem list bundler'
salt '*' rbenv.do 'gem list bundler' deploy
'''
if not cmdline:
# This is a positional argument so this should never happen, but this
# will handle cases where someone explicitly passes a false value for
# cmdline.
raise SaltInvocationError('Command must be specified')
path = _rbenv_path(runas)
if not env:
env = {}
# NOTE: Env vars (and their values) need to be str type on both Python 2
# and 3. The code below first normalizes all path components to unicode to
# stitch them together, and then converts the result back to a str type.
env[str('PATH')] = salt.utils.stringutils.to_str( # future lint: disable=blacklisted-function
os.pathsep.join((
salt.utils.path.join(path, 'shims'),
salt.utils.stringutils.to_unicode(os.environ['PATH'])
))
)
try:
cmdline = salt.utils.args.shlex_split(cmdline)
except AttributeError:
cmdauth = salt.utils.args.shlex_split(six.text_type(cmdline))
result = __salt__['cmd.run_all'](
cmdline,
runas=runas,
env=env,
python_shell=False
)
if result['retcode'] == 0:
rehash(runas=runas)
return result['stdout']
else:
return False
def do_with_ruby(ruby, cmdline, runas=None):
'''
Execute a ruby command with rbenv's shims using a specific ruby version
CLI Example:
.. code-block:: bash
salt '*' rbenv.do_with_ruby 2.0.0-p0 'gem list bundler'
salt '*' rbenv.do_with_ruby 2.0.0-p0 'gem list bundler' runas=deploy
'''
if not cmdline:
# This is a positional argument so this should never happen, but this
# will handle cases where someone explicitly passes a false value for
# cmdline.
raise SaltInvocationError('Command must be specified')
try:
cmdline = salt.utils.args.shlex_split(cmdline)
except AttributeError:
cmdline = salt.utils.args.shlex_split(six.text_type(cmdline))
env = {}
if ruby:
env['RBENV_VERSION'] = ruby
cmd = cmdline
else:
cmd = cmdline
return do(cmd, runas=runas, env=env)
|
saltstack/salt
|
salt/modules/rbenv.py
|
update
|
python
|
def update(runas=None, path=None):
'''
Updates the current versions of rbenv and ruby-build
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.update
'''
path = path or _rbenv_path(runas)
path = os.path.expanduser(path)
return _update_rbenv(path, runas) and _update_ruby_build(path, runas)
|
Updates the current versions of rbenv and ruby-build
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.update
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rbenv.py#L174-L191
|
[
"def _rbenv_path(runas=None):\n path = None\n if runas in (None, 'root'):\n path = __salt__['config.option']('rbenv.root') or '/usr/local/rbenv'\n else:\n path = __salt__['config.option']('rbenv.root') \\\n or '~{0}/.rbenv'.format(runas)\n\n return os.path.expanduser(path)\n",
"def _update_rbenv(path, runas=None):\n if not os.path.isdir(path):\n return False\n\n return __salt__['cmd.retcode'](['git', 'pull'],\n runas=runas,\n cwd=path,\n python_shell=False) == 0\n",
"def _update_ruby_build(path, runas=None):\n path = '{0}/plugins/ruby-build'.format(path)\n if not os.path.isdir(path):\n return False\n\n return __salt__['cmd.retcode'](['git', 'pull'],\n runas=runas,\n cwd=path,\n python_shell=False) == 0\n"
] |
# -*- coding: utf-8 -*-
'''
Manage ruby installations with rbenv. rbenv is supported on Linux and macOS.
rbenv doesn't work on Windows (and isn't really necessary on Windows as there is
no system Ruby on Windows). On Windows, the RubyInstaller and/or Pik are both
good alternatives to work with multiple versions of Ruby on the same box.
http://misheska.com/blog/2013/06/15/using-rbenv-to-manage-multiple-versions-of-ruby/
.. versionadded:: 0.16.0
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import os
import re
import logging
# Import Salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.path
import salt.utils.platform
from salt.exceptions import SaltInvocationError
# Import 3rd-party libs
from salt.ext import six
# Set up logger
log = logging.getLogger(__name__)
__func_alias__ = {
'list_': 'list'
}
__opts__ = {
'rbenv.root': None,
'rbenv.build_env': None,
}
def __virtual__():
'''
Only work on POSIX-like systems
'''
if salt.utils.platform.is_windows():
return (False, 'The rbenv execution module failed to load: only available on non-Windows systems.')
return True
def _shlex_split(s):
# from python:salt.utils.args.shlex_split: passing None for s will read
# the string to split from standard input.
if s is None:
ret = salt.utils.args.shlex_split('')
else:
ret = salt.utils.args.shlex_split(s)
return ret
def _parse_env(env):
if not env:
env = {}
if isinstance(env, list):
env = salt.utils.data.repack_dictlist(env)
if not isinstance(env, dict):
env = {}
for bad_env_key in (x for x, y in six.iteritems(env) if y is None):
log.error('Environment variable \'%s\' passed without a value. '
'Setting value to an empty string', bad_env_key)
env[bad_env_key] = ''
return env
def _rbenv_bin(runas=None):
path = _rbenv_path(runas)
return '{0}/bin/rbenv'.format(path)
def _rbenv_path(runas=None):
path = None
if runas in (None, 'root'):
path = __salt__['config.option']('rbenv.root') or '/usr/local/rbenv'
else:
path = __salt__['config.option']('rbenv.root') \
or '~{0}/.rbenv'.format(runas)
return os.path.expanduser(path)
def _rbenv_exec(command, env=None, runas=None, ret=None):
if not is_installed(runas):
return False
binary = _rbenv_bin(runas)
path = _rbenv_path(runas)
environ = _parse_env(env)
environ['RBENV_ROOT'] = path
result = __salt__['cmd.run_all'](
[binary] + command,
runas=runas,
env=environ
)
if isinstance(ret, dict):
ret.update(result)
return ret
if result['retcode'] == 0:
return result['stdout']
else:
return False
def _install_rbenv(path, runas=None):
if os.path.isdir(path):
return True
cmd = ['git', 'clone', 'https://github.com/sstephenson/rbenv.git', path]
return __salt__['cmd.retcode'](cmd, runas=runas, python_shell=False) == 0
def _install_ruby_build(path, runas=None):
path = '{0}/plugins/ruby-build'.format(path)
if os.path.isdir(path):
return True
cmd = ['git', 'clone',
'https://github.com/sstephenson/ruby-build.git', path]
return __salt__['cmd.retcode'](cmd, runas=runas, python_shell=False) == 0
def _update_rbenv(path, runas=None):
if not os.path.isdir(path):
return False
return __salt__['cmd.retcode'](['git', 'pull'],
runas=runas,
cwd=path,
python_shell=False) == 0
def _update_ruby_build(path, runas=None):
path = '{0}/plugins/ruby-build'.format(path)
if not os.path.isdir(path):
return False
return __salt__['cmd.retcode'](['git', 'pull'],
runas=runas,
cwd=path,
python_shell=False) == 0
def install(runas=None, path=None):
'''
Install rbenv systemwide
CLI Example:
.. code-block:: bash
salt '*' rbenv.install
'''
path = path or _rbenv_path(runas)
path = os.path.expanduser(path)
return _install_rbenv(path, runas) and _install_ruby_build(path, runas)
def is_installed(runas=None):
'''
Check if rbenv is installed
CLI Example:
.. code-block:: bash
salt '*' rbenv.is_installed
'''
return __salt__['cmd.has_exec'](_rbenv_bin(runas))
def install_ruby(ruby, runas=None):
'''
Install a ruby implementation.
ruby
The version of Ruby to install, should match one of the
versions listed by :py:func:`rbenv.list <salt.modules.rbenv.list>`
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
Additional environment variables can be configured in pillar /
grains / master:
.. code-block:: yaml
rbenv:
build_env: 'CONFIGURE_OPTS="--no-tcmalloc" CFLAGS="-fno-tree-dce"'
CLI Example:
.. code-block:: bash
salt '*' rbenv.install_ruby 2.0.0-p0
'''
ruby = re.sub(r'^ruby-', '', ruby)
env = None
env_list = []
if __grains__['os'] in ('FreeBSD', 'NetBSD', 'OpenBSD'):
env_list.append('MAKE=gmake')
if __salt__['config.get']('rbenv:build_env'):
env_list.append(__salt__['config.get']('rbenv:build_env'))
elif __salt__['config.option']('rbenv.build_env'):
env_list.append(__salt__['config.option']('rbenv.build_env'))
if env_list:
env = ' '.join(env_list)
ret = {}
ret = _rbenv_exec(['install', ruby], env=env, runas=runas, ret=ret)
if ret is not False and ret['retcode'] == 0:
rehash(runas=runas)
return ret['stderr']
else:
# Cleanup the failed installation so it doesn't list as installed
uninstall_ruby(ruby, runas=runas)
return False
def uninstall_ruby(ruby, runas=None):
'''
Uninstall a ruby implementation.
ruby
The version of ruby to uninstall. Should match one of the versions
listed by :py:func:`rbenv.versions <salt.modules.rbenv.versions>`.
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.uninstall_ruby 2.0.0-p0
'''
ruby = re.sub(r'^ruby-', '', ruby)
_rbenv_exec(['uninstall', '--force', ruby], runas=runas)
return True
def versions(runas=None):
'''
List the installed versions of ruby
CLI Example:
.. code-block:: bash
salt '*' rbenv.versions
'''
ret = _rbenv_exec(['versions', '--bare'], runas=runas)
return [] if ret is False else ret.splitlines()
def default(ruby=None, runas=None):
'''
Returns or sets the currently defined default ruby
ruby
The version to set as the default. Should match one of the versions
listed by :py:func:`rbenv.versions <salt.modules.rbenv.versions>`.
Leave blank to return the current default.
CLI Example:
.. code-block:: bash
salt '*' rbenv.default
salt '*' rbenv.default 2.0.0-p0
'''
if ruby:
_rbenv_exec(['global', ruby], runas=runas)
return True
else:
ret = _rbenv_exec(['global'], runas=runas)
return '' if ret is False else ret.strip()
def list_(runas=None):
'''
List the installable versions of ruby
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.list
'''
ret = []
output = _rbenv_exec(['install', '--list'], runas=runas)
if output:
for line in output.splitlines():
if line == 'Available versions:':
continue
ret.append(line.strip())
return ret
def rehash(runas=None):
'''
Run ``rbenv rehash`` to update the installed shims
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.rehash
'''
_rbenv_exec(['rehash'], runas=runas)
return True
def do(cmdline, runas=None, env=None):
'''
Execute a ruby command with rbenv's shims from the user or the system
CLI Example:
.. code-block:: bash
salt '*' rbenv.do 'gem list bundler'
salt '*' rbenv.do 'gem list bundler' deploy
'''
if not cmdline:
# This is a positional argument so this should never happen, but this
# will handle cases where someone explicitly passes a false value for
# cmdline.
raise SaltInvocationError('Command must be specified')
path = _rbenv_path(runas)
if not env:
env = {}
# NOTE: Env vars (and their values) need to be str type on both Python 2
# and 3. The code below first normalizes all path components to unicode to
# stitch them together, and then converts the result back to a str type.
env[str('PATH')] = salt.utils.stringutils.to_str( # future lint: disable=blacklisted-function
os.pathsep.join((
salt.utils.path.join(path, 'shims'),
salt.utils.stringutils.to_unicode(os.environ['PATH'])
))
)
try:
cmdline = salt.utils.args.shlex_split(cmdline)
except AttributeError:
cmdauth = salt.utils.args.shlex_split(six.text_type(cmdline))
result = __salt__['cmd.run_all'](
cmdline,
runas=runas,
env=env,
python_shell=False
)
if result['retcode'] == 0:
rehash(runas=runas)
return result['stdout']
else:
return False
def do_with_ruby(ruby, cmdline, runas=None):
'''
Execute a ruby command with rbenv's shims using a specific ruby version
CLI Example:
.. code-block:: bash
salt '*' rbenv.do_with_ruby 2.0.0-p0 'gem list bundler'
salt '*' rbenv.do_with_ruby 2.0.0-p0 'gem list bundler' runas=deploy
'''
if not cmdline:
# This is a positional argument so this should never happen, but this
# will handle cases where someone explicitly passes a false value for
# cmdline.
raise SaltInvocationError('Command must be specified')
try:
cmdline = salt.utils.args.shlex_split(cmdline)
except AttributeError:
cmdline = salt.utils.args.shlex_split(six.text_type(cmdline))
env = {}
if ruby:
env['RBENV_VERSION'] = ruby
cmd = cmdline
else:
cmd = cmdline
return do(cmd, runas=runas, env=env)
|
saltstack/salt
|
salt/modules/rbenv.py
|
install_ruby
|
python
|
def install_ruby(ruby, runas=None):
'''
Install a ruby implementation.
ruby
The version of Ruby to install, should match one of the
versions listed by :py:func:`rbenv.list <salt.modules.rbenv.list>`
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
Additional environment variables can be configured in pillar /
grains / master:
.. code-block:: yaml
rbenv:
build_env: 'CONFIGURE_OPTS="--no-tcmalloc" CFLAGS="-fno-tree-dce"'
CLI Example:
.. code-block:: bash
salt '*' rbenv.install_ruby 2.0.0-p0
'''
ruby = re.sub(r'^ruby-', '', ruby)
env = None
env_list = []
if __grains__['os'] in ('FreeBSD', 'NetBSD', 'OpenBSD'):
env_list.append('MAKE=gmake')
if __salt__['config.get']('rbenv:build_env'):
env_list.append(__salt__['config.get']('rbenv:build_env'))
elif __salt__['config.option']('rbenv.build_env'):
env_list.append(__salt__['config.option']('rbenv.build_env'))
if env_list:
env = ' '.join(env_list)
ret = {}
ret = _rbenv_exec(['install', ruby], env=env, runas=runas, ret=ret)
if ret is not False and ret['retcode'] == 0:
rehash(runas=runas)
return ret['stderr']
else:
# Cleanup the failed installation so it doesn't list as installed
uninstall_ruby(ruby, runas=runas)
return False
|
Install a ruby implementation.
ruby
The version of Ruby to install, should match one of the
versions listed by :py:func:`rbenv.list <salt.modules.rbenv.list>`
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
Additional environment variables can be configured in pillar /
grains / master:
.. code-block:: yaml
rbenv:
build_env: 'CONFIGURE_OPTS="--no-tcmalloc" CFLAGS="-fno-tree-dce"'
CLI Example:
.. code-block:: bash
salt '*' rbenv.install_ruby 2.0.0-p0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rbenv.py#L207-L257
|
[
"def rehash(runas=None):\n '''\n Run ``rbenv rehash`` to update the installed shims\n\n runas\n The user under which to run rbenv. If not specified, then rbenv will be\n run as the user under which Salt is running.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' rbenv.rehash\n '''\n _rbenv_exec(['rehash'], runas=runas)\n return True\n",
"def _rbenv_exec(command, env=None, runas=None, ret=None):\n if not is_installed(runas):\n return False\n\n binary = _rbenv_bin(runas)\n path = _rbenv_path(runas)\n\n environ = _parse_env(env)\n environ['RBENV_ROOT'] = path\n\n result = __salt__['cmd.run_all'](\n [binary] + command,\n runas=runas,\n env=environ\n )\n\n if isinstance(ret, dict):\n ret.update(result)\n return ret\n\n if result['retcode'] == 0:\n return result['stdout']\n else:\n return False\n",
"def uninstall_ruby(ruby, runas=None):\n '''\n Uninstall a ruby implementation.\n\n ruby\n The version of ruby to uninstall. Should match one of the versions\n listed by :py:func:`rbenv.versions <salt.modules.rbenv.versions>`.\n\n runas\n The user under which to run rbenv. If not specified, then rbenv will be\n run as the user under which Salt is running.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' rbenv.uninstall_ruby 2.0.0-p0\n '''\n ruby = re.sub(r'^ruby-', '', ruby)\n _rbenv_exec(['uninstall', '--force', ruby], runas=runas)\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
Manage ruby installations with rbenv. rbenv is supported on Linux and macOS.
rbenv doesn't work on Windows (and isn't really necessary on Windows as there is
no system Ruby on Windows). On Windows, the RubyInstaller and/or Pik are both
good alternatives to work with multiple versions of Ruby on the same box.
http://misheska.com/blog/2013/06/15/using-rbenv-to-manage-multiple-versions-of-ruby/
.. versionadded:: 0.16.0
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import os
import re
import logging
# Import Salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.path
import salt.utils.platform
from salt.exceptions import SaltInvocationError
# Import 3rd-party libs
from salt.ext import six
# Set up logger
log = logging.getLogger(__name__)
__func_alias__ = {
'list_': 'list'
}
__opts__ = {
'rbenv.root': None,
'rbenv.build_env': None,
}
def __virtual__():
'''
Only work on POSIX-like systems
'''
if salt.utils.platform.is_windows():
return (False, 'The rbenv execution module failed to load: only available on non-Windows systems.')
return True
def _shlex_split(s):
# from python:salt.utils.args.shlex_split: passing None for s will read
# the string to split from standard input.
if s is None:
ret = salt.utils.args.shlex_split('')
else:
ret = salt.utils.args.shlex_split(s)
return ret
def _parse_env(env):
if not env:
env = {}
if isinstance(env, list):
env = salt.utils.data.repack_dictlist(env)
if not isinstance(env, dict):
env = {}
for bad_env_key in (x for x, y in six.iteritems(env) if y is None):
log.error('Environment variable \'%s\' passed without a value. '
'Setting value to an empty string', bad_env_key)
env[bad_env_key] = ''
return env
def _rbenv_bin(runas=None):
path = _rbenv_path(runas)
return '{0}/bin/rbenv'.format(path)
def _rbenv_path(runas=None):
path = None
if runas in (None, 'root'):
path = __salt__['config.option']('rbenv.root') or '/usr/local/rbenv'
else:
path = __salt__['config.option']('rbenv.root') \
or '~{0}/.rbenv'.format(runas)
return os.path.expanduser(path)
def _rbenv_exec(command, env=None, runas=None, ret=None):
if not is_installed(runas):
return False
binary = _rbenv_bin(runas)
path = _rbenv_path(runas)
environ = _parse_env(env)
environ['RBENV_ROOT'] = path
result = __salt__['cmd.run_all'](
[binary] + command,
runas=runas,
env=environ
)
if isinstance(ret, dict):
ret.update(result)
return ret
if result['retcode'] == 0:
return result['stdout']
else:
return False
def _install_rbenv(path, runas=None):
if os.path.isdir(path):
return True
cmd = ['git', 'clone', 'https://github.com/sstephenson/rbenv.git', path]
return __salt__['cmd.retcode'](cmd, runas=runas, python_shell=False) == 0
def _install_ruby_build(path, runas=None):
path = '{0}/plugins/ruby-build'.format(path)
if os.path.isdir(path):
return True
cmd = ['git', 'clone',
'https://github.com/sstephenson/ruby-build.git', path]
return __salt__['cmd.retcode'](cmd, runas=runas, python_shell=False) == 0
def _update_rbenv(path, runas=None):
if not os.path.isdir(path):
return False
return __salt__['cmd.retcode'](['git', 'pull'],
runas=runas,
cwd=path,
python_shell=False) == 0
def _update_ruby_build(path, runas=None):
path = '{0}/plugins/ruby-build'.format(path)
if not os.path.isdir(path):
return False
return __salt__['cmd.retcode'](['git', 'pull'],
runas=runas,
cwd=path,
python_shell=False) == 0
def install(runas=None, path=None):
'''
Install rbenv systemwide
CLI Example:
.. code-block:: bash
salt '*' rbenv.install
'''
path = path or _rbenv_path(runas)
path = os.path.expanduser(path)
return _install_rbenv(path, runas) and _install_ruby_build(path, runas)
def update(runas=None, path=None):
'''
Updates the current versions of rbenv and ruby-build
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.update
'''
path = path or _rbenv_path(runas)
path = os.path.expanduser(path)
return _update_rbenv(path, runas) and _update_ruby_build(path, runas)
def is_installed(runas=None):
'''
Check if rbenv is installed
CLI Example:
.. code-block:: bash
salt '*' rbenv.is_installed
'''
return __salt__['cmd.has_exec'](_rbenv_bin(runas))
def uninstall_ruby(ruby, runas=None):
'''
Uninstall a ruby implementation.
ruby
The version of ruby to uninstall. Should match one of the versions
listed by :py:func:`rbenv.versions <salt.modules.rbenv.versions>`.
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.uninstall_ruby 2.0.0-p0
'''
ruby = re.sub(r'^ruby-', '', ruby)
_rbenv_exec(['uninstall', '--force', ruby], runas=runas)
return True
def versions(runas=None):
'''
List the installed versions of ruby
CLI Example:
.. code-block:: bash
salt '*' rbenv.versions
'''
ret = _rbenv_exec(['versions', '--bare'], runas=runas)
return [] if ret is False else ret.splitlines()
def default(ruby=None, runas=None):
'''
Returns or sets the currently defined default ruby
ruby
The version to set as the default. Should match one of the versions
listed by :py:func:`rbenv.versions <salt.modules.rbenv.versions>`.
Leave blank to return the current default.
CLI Example:
.. code-block:: bash
salt '*' rbenv.default
salt '*' rbenv.default 2.0.0-p0
'''
if ruby:
_rbenv_exec(['global', ruby], runas=runas)
return True
else:
ret = _rbenv_exec(['global'], runas=runas)
return '' if ret is False else ret.strip()
def list_(runas=None):
'''
List the installable versions of ruby
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.list
'''
ret = []
output = _rbenv_exec(['install', '--list'], runas=runas)
if output:
for line in output.splitlines():
if line == 'Available versions:':
continue
ret.append(line.strip())
return ret
def rehash(runas=None):
'''
Run ``rbenv rehash`` to update the installed shims
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.rehash
'''
_rbenv_exec(['rehash'], runas=runas)
return True
def do(cmdline, runas=None, env=None):
'''
Execute a ruby command with rbenv's shims from the user or the system
CLI Example:
.. code-block:: bash
salt '*' rbenv.do 'gem list bundler'
salt '*' rbenv.do 'gem list bundler' deploy
'''
if not cmdline:
# This is a positional argument so this should never happen, but this
# will handle cases where someone explicitly passes a false value for
# cmdline.
raise SaltInvocationError('Command must be specified')
path = _rbenv_path(runas)
if not env:
env = {}
# NOTE: Env vars (and their values) need to be str type on both Python 2
# and 3. The code below first normalizes all path components to unicode to
# stitch them together, and then converts the result back to a str type.
env[str('PATH')] = salt.utils.stringutils.to_str( # future lint: disable=blacklisted-function
os.pathsep.join((
salt.utils.path.join(path, 'shims'),
salt.utils.stringutils.to_unicode(os.environ['PATH'])
))
)
try:
cmdline = salt.utils.args.shlex_split(cmdline)
except AttributeError:
cmdauth = salt.utils.args.shlex_split(six.text_type(cmdline))
result = __salt__['cmd.run_all'](
cmdline,
runas=runas,
env=env,
python_shell=False
)
if result['retcode'] == 0:
rehash(runas=runas)
return result['stdout']
else:
return False
def do_with_ruby(ruby, cmdline, runas=None):
'''
Execute a ruby command with rbenv's shims using a specific ruby version
CLI Example:
.. code-block:: bash
salt '*' rbenv.do_with_ruby 2.0.0-p0 'gem list bundler'
salt '*' rbenv.do_with_ruby 2.0.0-p0 'gem list bundler' runas=deploy
'''
if not cmdline:
# This is a positional argument so this should never happen, but this
# will handle cases where someone explicitly passes a false value for
# cmdline.
raise SaltInvocationError('Command must be specified')
try:
cmdline = salt.utils.args.shlex_split(cmdline)
except AttributeError:
cmdline = salt.utils.args.shlex_split(six.text_type(cmdline))
env = {}
if ruby:
env['RBENV_VERSION'] = ruby
cmd = cmdline
else:
cmd = cmdline
return do(cmd, runas=runas, env=env)
|
saltstack/salt
|
salt/modules/rbenv.py
|
uninstall_ruby
|
python
|
def uninstall_ruby(ruby, runas=None):
'''
Uninstall a ruby implementation.
ruby
The version of ruby to uninstall. Should match one of the versions
listed by :py:func:`rbenv.versions <salt.modules.rbenv.versions>`.
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.uninstall_ruby 2.0.0-p0
'''
ruby = re.sub(r'^ruby-', '', ruby)
_rbenv_exec(['uninstall', '--force', ruby], runas=runas)
return True
|
Uninstall a ruby implementation.
ruby
The version of ruby to uninstall. Should match one of the versions
listed by :py:func:`rbenv.versions <salt.modules.rbenv.versions>`.
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.uninstall_ruby 2.0.0-p0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rbenv.py#L260-L280
|
[
"def _rbenv_exec(command, env=None, runas=None, ret=None):\n if not is_installed(runas):\n return False\n\n binary = _rbenv_bin(runas)\n path = _rbenv_path(runas)\n\n environ = _parse_env(env)\n environ['RBENV_ROOT'] = path\n\n result = __salt__['cmd.run_all'](\n [binary] + command,\n runas=runas,\n env=environ\n )\n\n if isinstance(ret, dict):\n ret.update(result)\n return ret\n\n if result['retcode'] == 0:\n return result['stdout']\n else:\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Manage ruby installations with rbenv. rbenv is supported on Linux and macOS.
rbenv doesn't work on Windows (and isn't really necessary on Windows as there is
no system Ruby on Windows). On Windows, the RubyInstaller and/or Pik are both
good alternatives to work with multiple versions of Ruby on the same box.
http://misheska.com/blog/2013/06/15/using-rbenv-to-manage-multiple-versions-of-ruby/
.. versionadded:: 0.16.0
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import os
import re
import logging
# Import Salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.path
import salt.utils.platform
from salt.exceptions import SaltInvocationError
# Import 3rd-party libs
from salt.ext import six
# Set up logger
log = logging.getLogger(__name__)
__func_alias__ = {
'list_': 'list'
}
__opts__ = {
'rbenv.root': None,
'rbenv.build_env': None,
}
def __virtual__():
'''
Only work on POSIX-like systems
'''
if salt.utils.platform.is_windows():
return (False, 'The rbenv execution module failed to load: only available on non-Windows systems.')
return True
def _shlex_split(s):
# from python:salt.utils.args.shlex_split: passing None for s will read
# the string to split from standard input.
if s is None:
ret = salt.utils.args.shlex_split('')
else:
ret = salt.utils.args.shlex_split(s)
return ret
def _parse_env(env):
if not env:
env = {}
if isinstance(env, list):
env = salt.utils.data.repack_dictlist(env)
if not isinstance(env, dict):
env = {}
for bad_env_key in (x for x, y in six.iteritems(env) if y is None):
log.error('Environment variable \'%s\' passed without a value. '
'Setting value to an empty string', bad_env_key)
env[bad_env_key] = ''
return env
def _rbenv_bin(runas=None):
path = _rbenv_path(runas)
return '{0}/bin/rbenv'.format(path)
def _rbenv_path(runas=None):
path = None
if runas in (None, 'root'):
path = __salt__['config.option']('rbenv.root') or '/usr/local/rbenv'
else:
path = __salt__['config.option']('rbenv.root') \
or '~{0}/.rbenv'.format(runas)
return os.path.expanduser(path)
def _rbenv_exec(command, env=None, runas=None, ret=None):
if not is_installed(runas):
return False
binary = _rbenv_bin(runas)
path = _rbenv_path(runas)
environ = _parse_env(env)
environ['RBENV_ROOT'] = path
result = __salt__['cmd.run_all'](
[binary] + command,
runas=runas,
env=environ
)
if isinstance(ret, dict):
ret.update(result)
return ret
if result['retcode'] == 0:
return result['stdout']
else:
return False
def _install_rbenv(path, runas=None):
if os.path.isdir(path):
return True
cmd = ['git', 'clone', 'https://github.com/sstephenson/rbenv.git', path]
return __salt__['cmd.retcode'](cmd, runas=runas, python_shell=False) == 0
def _install_ruby_build(path, runas=None):
path = '{0}/plugins/ruby-build'.format(path)
if os.path.isdir(path):
return True
cmd = ['git', 'clone',
'https://github.com/sstephenson/ruby-build.git', path]
return __salt__['cmd.retcode'](cmd, runas=runas, python_shell=False) == 0
def _update_rbenv(path, runas=None):
if not os.path.isdir(path):
return False
return __salt__['cmd.retcode'](['git', 'pull'],
runas=runas,
cwd=path,
python_shell=False) == 0
def _update_ruby_build(path, runas=None):
path = '{0}/plugins/ruby-build'.format(path)
if not os.path.isdir(path):
return False
return __salt__['cmd.retcode'](['git', 'pull'],
runas=runas,
cwd=path,
python_shell=False) == 0
def install(runas=None, path=None):
'''
Install rbenv systemwide
CLI Example:
.. code-block:: bash
salt '*' rbenv.install
'''
path = path or _rbenv_path(runas)
path = os.path.expanduser(path)
return _install_rbenv(path, runas) and _install_ruby_build(path, runas)
def update(runas=None, path=None):
'''
Updates the current versions of rbenv and ruby-build
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.update
'''
path = path or _rbenv_path(runas)
path = os.path.expanduser(path)
return _update_rbenv(path, runas) and _update_ruby_build(path, runas)
def is_installed(runas=None):
'''
Check if rbenv is installed
CLI Example:
.. code-block:: bash
salt '*' rbenv.is_installed
'''
return __salt__['cmd.has_exec'](_rbenv_bin(runas))
def install_ruby(ruby, runas=None):
'''
Install a ruby implementation.
ruby
The version of Ruby to install, should match one of the
versions listed by :py:func:`rbenv.list <salt.modules.rbenv.list>`
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
Additional environment variables can be configured in pillar /
grains / master:
.. code-block:: yaml
rbenv:
build_env: 'CONFIGURE_OPTS="--no-tcmalloc" CFLAGS="-fno-tree-dce"'
CLI Example:
.. code-block:: bash
salt '*' rbenv.install_ruby 2.0.0-p0
'''
ruby = re.sub(r'^ruby-', '', ruby)
env = None
env_list = []
if __grains__['os'] in ('FreeBSD', 'NetBSD', 'OpenBSD'):
env_list.append('MAKE=gmake')
if __salt__['config.get']('rbenv:build_env'):
env_list.append(__salt__['config.get']('rbenv:build_env'))
elif __salt__['config.option']('rbenv.build_env'):
env_list.append(__salt__['config.option']('rbenv.build_env'))
if env_list:
env = ' '.join(env_list)
ret = {}
ret = _rbenv_exec(['install', ruby], env=env, runas=runas, ret=ret)
if ret is not False and ret['retcode'] == 0:
rehash(runas=runas)
return ret['stderr']
else:
# Cleanup the failed installation so it doesn't list as installed
uninstall_ruby(ruby, runas=runas)
return False
def versions(runas=None):
'''
List the installed versions of ruby
CLI Example:
.. code-block:: bash
salt '*' rbenv.versions
'''
ret = _rbenv_exec(['versions', '--bare'], runas=runas)
return [] if ret is False else ret.splitlines()
def default(ruby=None, runas=None):
'''
Returns or sets the currently defined default ruby
ruby
The version to set as the default. Should match one of the versions
listed by :py:func:`rbenv.versions <salt.modules.rbenv.versions>`.
Leave blank to return the current default.
CLI Example:
.. code-block:: bash
salt '*' rbenv.default
salt '*' rbenv.default 2.0.0-p0
'''
if ruby:
_rbenv_exec(['global', ruby], runas=runas)
return True
else:
ret = _rbenv_exec(['global'], runas=runas)
return '' if ret is False else ret.strip()
def list_(runas=None):
'''
List the installable versions of ruby
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.list
'''
ret = []
output = _rbenv_exec(['install', '--list'], runas=runas)
if output:
for line in output.splitlines():
if line == 'Available versions:':
continue
ret.append(line.strip())
return ret
def rehash(runas=None):
'''
Run ``rbenv rehash`` to update the installed shims
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.rehash
'''
_rbenv_exec(['rehash'], runas=runas)
return True
def do(cmdline, runas=None, env=None):
'''
Execute a ruby command with rbenv's shims from the user or the system
CLI Example:
.. code-block:: bash
salt '*' rbenv.do 'gem list bundler'
salt '*' rbenv.do 'gem list bundler' deploy
'''
if not cmdline:
# This is a positional argument so this should never happen, but this
# will handle cases where someone explicitly passes a false value for
# cmdline.
raise SaltInvocationError('Command must be specified')
path = _rbenv_path(runas)
if not env:
env = {}
# NOTE: Env vars (and their values) need to be str type on both Python 2
# and 3. The code below first normalizes all path components to unicode to
# stitch them together, and then converts the result back to a str type.
env[str('PATH')] = salt.utils.stringutils.to_str( # future lint: disable=blacklisted-function
os.pathsep.join((
salt.utils.path.join(path, 'shims'),
salt.utils.stringutils.to_unicode(os.environ['PATH'])
))
)
try:
cmdline = salt.utils.args.shlex_split(cmdline)
except AttributeError:
cmdauth = salt.utils.args.shlex_split(six.text_type(cmdline))
result = __salt__['cmd.run_all'](
cmdline,
runas=runas,
env=env,
python_shell=False
)
if result['retcode'] == 0:
rehash(runas=runas)
return result['stdout']
else:
return False
def do_with_ruby(ruby, cmdline, runas=None):
'''
Execute a ruby command with rbenv's shims using a specific ruby version
CLI Example:
.. code-block:: bash
salt '*' rbenv.do_with_ruby 2.0.0-p0 'gem list bundler'
salt '*' rbenv.do_with_ruby 2.0.0-p0 'gem list bundler' runas=deploy
'''
if not cmdline:
# This is a positional argument so this should never happen, but this
# will handle cases where someone explicitly passes a false value for
# cmdline.
raise SaltInvocationError('Command must be specified')
try:
cmdline = salt.utils.args.shlex_split(cmdline)
except AttributeError:
cmdline = salt.utils.args.shlex_split(six.text_type(cmdline))
env = {}
if ruby:
env['RBENV_VERSION'] = ruby
cmd = cmdline
else:
cmd = cmdline
return do(cmd, runas=runas, env=env)
|
saltstack/salt
|
salt/modules/rbenv.py
|
versions
|
python
|
def versions(runas=None):
'''
List the installed versions of ruby
CLI Example:
.. code-block:: bash
salt '*' rbenv.versions
'''
ret = _rbenv_exec(['versions', '--bare'], runas=runas)
return [] if ret is False else ret.splitlines()
|
List the installed versions of ruby
CLI Example:
.. code-block:: bash
salt '*' rbenv.versions
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rbenv.py#L283-L294
|
[
"def _rbenv_exec(command, env=None, runas=None, ret=None):\n if not is_installed(runas):\n return False\n\n binary = _rbenv_bin(runas)\n path = _rbenv_path(runas)\n\n environ = _parse_env(env)\n environ['RBENV_ROOT'] = path\n\n result = __salt__['cmd.run_all'](\n [binary] + command,\n runas=runas,\n env=environ\n )\n\n if isinstance(ret, dict):\n ret.update(result)\n return ret\n\n if result['retcode'] == 0:\n return result['stdout']\n else:\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Manage ruby installations with rbenv. rbenv is supported on Linux and macOS.
rbenv doesn't work on Windows (and isn't really necessary on Windows as there is
no system Ruby on Windows). On Windows, the RubyInstaller and/or Pik are both
good alternatives to work with multiple versions of Ruby on the same box.
http://misheska.com/blog/2013/06/15/using-rbenv-to-manage-multiple-versions-of-ruby/
.. versionadded:: 0.16.0
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import os
import re
import logging
# Import Salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.path
import salt.utils.platform
from salt.exceptions import SaltInvocationError
# Import 3rd-party libs
from salt.ext import six
# Set up logger
log = logging.getLogger(__name__)
__func_alias__ = {
'list_': 'list'
}
__opts__ = {
'rbenv.root': None,
'rbenv.build_env': None,
}
def __virtual__():
'''
Only work on POSIX-like systems
'''
if salt.utils.platform.is_windows():
return (False, 'The rbenv execution module failed to load: only available on non-Windows systems.')
return True
def _shlex_split(s):
# from python:salt.utils.args.shlex_split: passing None for s will read
# the string to split from standard input.
if s is None:
ret = salt.utils.args.shlex_split('')
else:
ret = salt.utils.args.shlex_split(s)
return ret
def _parse_env(env):
if not env:
env = {}
if isinstance(env, list):
env = salt.utils.data.repack_dictlist(env)
if not isinstance(env, dict):
env = {}
for bad_env_key in (x for x, y in six.iteritems(env) if y is None):
log.error('Environment variable \'%s\' passed without a value. '
'Setting value to an empty string', bad_env_key)
env[bad_env_key] = ''
return env
def _rbenv_bin(runas=None):
path = _rbenv_path(runas)
return '{0}/bin/rbenv'.format(path)
def _rbenv_path(runas=None):
path = None
if runas in (None, 'root'):
path = __salt__['config.option']('rbenv.root') or '/usr/local/rbenv'
else:
path = __salt__['config.option']('rbenv.root') \
or '~{0}/.rbenv'.format(runas)
return os.path.expanduser(path)
def _rbenv_exec(command, env=None, runas=None, ret=None):
if not is_installed(runas):
return False
binary = _rbenv_bin(runas)
path = _rbenv_path(runas)
environ = _parse_env(env)
environ['RBENV_ROOT'] = path
result = __salt__['cmd.run_all'](
[binary] + command,
runas=runas,
env=environ
)
if isinstance(ret, dict):
ret.update(result)
return ret
if result['retcode'] == 0:
return result['stdout']
else:
return False
def _install_rbenv(path, runas=None):
if os.path.isdir(path):
return True
cmd = ['git', 'clone', 'https://github.com/sstephenson/rbenv.git', path]
return __salt__['cmd.retcode'](cmd, runas=runas, python_shell=False) == 0
def _install_ruby_build(path, runas=None):
path = '{0}/plugins/ruby-build'.format(path)
if os.path.isdir(path):
return True
cmd = ['git', 'clone',
'https://github.com/sstephenson/ruby-build.git', path]
return __salt__['cmd.retcode'](cmd, runas=runas, python_shell=False) == 0
def _update_rbenv(path, runas=None):
if not os.path.isdir(path):
return False
return __salt__['cmd.retcode'](['git', 'pull'],
runas=runas,
cwd=path,
python_shell=False) == 0
def _update_ruby_build(path, runas=None):
path = '{0}/plugins/ruby-build'.format(path)
if not os.path.isdir(path):
return False
return __salt__['cmd.retcode'](['git', 'pull'],
runas=runas,
cwd=path,
python_shell=False) == 0
def install(runas=None, path=None):
'''
Install rbenv systemwide
CLI Example:
.. code-block:: bash
salt '*' rbenv.install
'''
path = path or _rbenv_path(runas)
path = os.path.expanduser(path)
return _install_rbenv(path, runas) and _install_ruby_build(path, runas)
def update(runas=None, path=None):
'''
Updates the current versions of rbenv and ruby-build
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.update
'''
path = path or _rbenv_path(runas)
path = os.path.expanduser(path)
return _update_rbenv(path, runas) and _update_ruby_build(path, runas)
def is_installed(runas=None):
'''
Check if rbenv is installed
CLI Example:
.. code-block:: bash
salt '*' rbenv.is_installed
'''
return __salt__['cmd.has_exec'](_rbenv_bin(runas))
def install_ruby(ruby, runas=None):
'''
Install a ruby implementation.
ruby
The version of Ruby to install, should match one of the
versions listed by :py:func:`rbenv.list <salt.modules.rbenv.list>`
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
Additional environment variables can be configured in pillar /
grains / master:
.. code-block:: yaml
rbenv:
build_env: 'CONFIGURE_OPTS="--no-tcmalloc" CFLAGS="-fno-tree-dce"'
CLI Example:
.. code-block:: bash
salt '*' rbenv.install_ruby 2.0.0-p0
'''
ruby = re.sub(r'^ruby-', '', ruby)
env = None
env_list = []
if __grains__['os'] in ('FreeBSD', 'NetBSD', 'OpenBSD'):
env_list.append('MAKE=gmake')
if __salt__['config.get']('rbenv:build_env'):
env_list.append(__salt__['config.get']('rbenv:build_env'))
elif __salt__['config.option']('rbenv.build_env'):
env_list.append(__salt__['config.option']('rbenv.build_env'))
if env_list:
env = ' '.join(env_list)
ret = {}
ret = _rbenv_exec(['install', ruby], env=env, runas=runas, ret=ret)
if ret is not False and ret['retcode'] == 0:
rehash(runas=runas)
return ret['stderr']
else:
# Cleanup the failed installation so it doesn't list as installed
uninstall_ruby(ruby, runas=runas)
return False
def uninstall_ruby(ruby, runas=None):
'''
Uninstall a ruby implementation.
ruby
The version of ruby to uninstall. Should match one of the versions
listed by :py:func:`rbenv.versions <salt.modules.rbenv.versions>`.
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.uninstall_ruby 2.0.0-p0
'''
ruby = re.sub(r'^ruby-', '', ruby)
_rbenv_exec(['uninstall', '--force', ruby], runas=runas)
return True
def default(ruby=None, runas=None):
'''
Returns or sets the currently defined default ruby
ruby
The version to set as the default. Should match one of the versions
listed by :py:func:`rbenv.versions <salt.modules.rbenv.versions>`.
Leave blank to return the current default.
CLI Example:
.. code-block:: bash
salt '*' rbenv.default
salt '*' rbenv.default 2.0.0-p0
'''
if ruby:
_rbenv_exec(['global', ruby], runas=runas)
return True
else:
ret = _rbenv_exec(['global'], runas=runas)
return '' if ret is False else ret.strip()
def list_(runas=None):
'''
List the installable versions of ruby
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.list
'''
ret = []
output = _rbenv_exec(['install', '--list'], runas=runas)
if output:
for line in output.splitlines():
if line == 'Available versions:':
continue
ret.append(line.strip())
return ret
def rehash(runas=None):
'''
Run ``rbenv rehash`` to update the installed shims
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.rehash
'''
_rbenv_exec(['rehash'], runas=runas)
return True
def do(cmdline, runas=None, env=None):
'''
Execute a ruby command with rbenv's shims from the user or the system
CLI Example:
.. code-block:: bash
salt '*' rbenv.do 'gem list bundler'
salt '*' rbenv.do 'gem list bundler' deploy
'''
if not cmdline:
# This is a positional argument so this should never happen, but this
# will handle cases where someone explicitly passes a false value for
# cmdline.
raise SaltInvocationError('Command must be specified')
path = _rbenv_path(runas)
if not env:
env = {}
# NOTE: Env vars (and their values) need to be str type on both Python 2
# and 3. The code below first normalizes all path components to unicode to
# stitch them together, and then converts the result back to a str type.
env[str('PATH')] = salt.utils.stringutils.to_str( # future lint: disable=blacklisted-function
os.pathsep.join((
salt.utils.path.join(path, 'shims'),
salt.utils.stringutils.to_unicode(os.environ['PATH'])
))
)
try:
cmdline = salt.utils.args.shlex_split(cmdline)
except AttributeError:
cmdauth = salt.utils.args.shlex_split(six.text_type(cmdline))
result = __salt__['cmd.run_all'](
cmdline,
runas=runas,
env=env,
python_shell=False
)
if result['retcode'] == 0:
rehash(runas=runas)
return result['stdout']
else:
return False
def do_with_ruby(ruby, cmdline, runas=None):
'''
Execute a ruby command with rbenv's shims using a specific ruby version
CLI Example:
.. code-block:: bash
salt '*' rbenv.do_with_ruby 2.0.0-p0 'gem list bundler'
salt '*' rbenv.do_with_ruby 2.0.0-p0 'gem list bundler' runas=deploy
'''
if not cmdline:
# This is a positional argument so this should never happen, but this
# will handle cases where someone explicitly passes a false value for
# cmdline.
raise SaltInvocationError('Command must be specified')
try:
cmdline = salt.utils.args.shlex_split(cmdline)
except AttributeError:
cmdline = salt.utils.args.shlex_split(six.text_type(cmdline))
env = {}
if ruby:
env['RBENV_VERSION'] = ruby
cmd = cmdline
else:
cmd = cmdline
return do(cmd, runas=runas, env=env)
|
saltstack/salt
|
salt/modules/rbenv.py
|
default
|
python
|
def default(ruby=None, runas=None):
'''
Returns or sets the currently defined default ruby
ruby
The version to set as the default. Should match one of the versions
listed by :py:func:`rbenv.versions <salt.modules.rbenv.versions>`.
Leave blank to return the current default.
CLI Example:
.. code-block:: bash
salt '*' rbenv.default
salt '*' rbenv.default 2.0.0-p0
'''
if ruby:
_rbenv_exec(['global', ruby], runas=runas)
return True
else:
ret = _rbenv_exec(['global'], runas=runas)
return '' if ret is False else ret.strip()
|
Returns or sets the currently defined default ruby
ruby
The version to set as the default. Should match one of the versions
listed by :py:func:`rbenv.versions <salt.modules.rbenv.versions>`.
Leave blank to return the current default.
CLI Example:
.. code-block:: bash
salt '*' rbenv.default
salt '*' rbenv.default 2.0.0-p0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rbenv.py#L297-L318
|
[
"def _rbenv_exec(command, env=None, runas=None, ret=None):\n if not is_installed(runas):\n return False\n\n binary = _rbenv_bin(runas)\n path = _rbenv_path(runas)\n\n environ = _parse_env(env)\n environ['RBENV_ROOT'] = path\n\n result = __salt__['cmd.run_all'](\n [binary] + command,\n runas=runas,\n env=environ\n )\n\n if isinstance(ret, dict):\n ret.update(result)\n return ret\n\n if result['retcode'] == 0:\n return result['stdout']\n else:\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Manage ruby installations with rbenv. rbenv is supported on Linux and macOS.
rbenv doesn't work on Windows (and isn't really necessary on Windows as there is
no system Ruby on Windows). On Windows, the RubyInstaller and/or Pik are both
good alternatives to work with multiple versions of Ruby on the same box.
http://misheska.com/blog/2013/06/15/using-rbenv-to-manage-multiple-versions-of-ruby/
.. versionadded:: 0.16.0
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import os
import re
import logging
# Import Salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.path
import salt.utils.platform
from salt.exceptions import SaltInvocationError
# Import 3rd-party libs
from salt.ext import six
# Set up logger
log = logging.getLogger(__name__)
__func_alias__ = {
'list_': 'list'
}
__opts__ = {
'rbenv.root': None,
'rbenv.build_env': None,
}
def __virtual__():
'''
Only work on POSIX-like systems
'''
if salt.utils.platform.is_windows():
return (False, 'The rbenv execution module failed to load: only available on non-Windows systems.')
return True
def _shlex_split(s):
# from python:salt.utils.args.shlex_split: passing None for s will read
# the string to split from standard input.
if s is None:
ret = salt.utils.args.shlex_split('')
else:
ret = salt.utils.args.shlex_split(s)
return ret
def _parse_env(env):
if not env:
env = {}
if isinstance(env, list):
env = salt.utils.data.repack_dictlist(env)
if not isinstance(env, dict):
env = {}
for bad_env_key in (x for x, y in six.iteritems(env) if y is None):
log.error('Environment variable \'%s\' passed without a value. '
'Setting value to an empty string', bad_env_key)
env[bad_env_key] = ''
return env
def _rbenv_bin(runas=None):
path = _rbenv_path(runas)
return '{0}/bin/rbenv'.format(path)
def _rbenv_path(runas=None):
path = None
if runas in (None, 'root'):
path = __salt__['config.option']('rbenv.root') or '/usr/local/rbenv'
else:
path = __salt__['config.option']('rbenv.root') \
or '~{0}/.rbenv'.format(runas)
return os.path.expanduser(path)
def _rbenv_exec(command, env=None, runas=None, ret=None):
if not is_installed(runas):
return False
binary = _rbenv_bin(runas)
path = _rbenv_path(runas)
environ = _parse_env(env)
environ['RBENV_ROOT'] = path
result = __salt__['cmd.run_all'](
[binary] + command,
runas=runas,
env=environ
)
if isinstance(ret, dict):
ret.update(result)
return ret
if result['retcode'] == 0:
return result['stdout']
else:
return False
def _install_rbenv(path, runas=None):
if os.path.isdir(path):
return True
cmd = ['git', 'clone', 'https://github.com/sstephenson/rbenv.git', path]
return __salt__['cmd.retcode'](cmd, runas=runas, python_shell=False) == 0
def _install_ruby_build(path, runas=None):
path = '{0}/plugins/ruby-build'.format(path)
if os.path.isdir(path):
return True
cmd = ['git', 'clone',
'https://github.com/sstephenson/ruby-build.git', path]
return __salt__['cmd.retcode'](cmd, runas=runas, python_shell=False) == 0
def _update_rbenv(path, runas=None):
if not os.path.isdir(path):
return False
return __salt__['cmd.retcode'](['git', 'pull'],
runas=runas,
cwd=path,
python_shell=False) == 0
def _update_ruby_build(path, runas=None):
path = '{0}/plugins/ruby-build'.format(path)
if not os.path.isdir(path):
return False
return __salt__['cmd.retcode'](['git', 'pull'],
runas=runas,
cwd=path,
python_shell=False) == 0
def install(runas=None, path=None):
'''
Install rbenv systemwide
CLI Example:
.. code-block:: bash
salt '*' rbenv.install
'''
path = path or _rbenv_path(runas)
path = os.path.expanduser(path)
return _install_rbenv(path, runas) and _install_ruby_build(path, runas)
def update(runas=None, path=None):
'''
Updates the current versions of rbenv and ruby-build
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.update
'''
path = path or _rbenv_path(runas)
path = os.path.expanduser(path)
return _update_rbenv(path, runas) and _update_ruby_build(path, runas)
def is_installed(runas=None):
'''
Check if rbenv is installed
CLI Example:
.. code-block:: bash
salt '*' rbenv.is_installed
'''
return __salt__['cmd.has_exec'](_rbenv_bin(runas))
def install_ruby(ruby, runas=None):
'''
Install a ruby implementation.
ruby
The version of Ruby to install, should match one of the
versions listed by :py:func:`rbenv.list <salt.modules.rbenv.list>`
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
Additional environment variables can be configured in pillar /
grains / master:
.. code-block:: yaml
rbenv:
build_env: 'CONFIGURE_OPTS="--no-tcmalloc" CFLAGS="-fno-tree-dce"'
CLI Example:
.. code-block:: bash
salt '*' rbenv.install_ruby 2.0.0-p0
'''
ruby = re.sub(r'^ruby-', '', ruby)
env = None
env_list = []
if __grains__['os'] in ('FreeBSD', 'NetBSD', 'OpenBSD'):
env_list.append('MAKE=gmake')
if __salt__['config.get']('rbenv:build_env'):
env_list.append(__salt__['config.get']('rbenv:build_env'))
elif __salt__['config.option']('rbenv.build_env'):
env_list.append(__salt__['config.option']('rbenv.build_env'))
if env_list:
env = ' '.join(env_list)
ret = {}
ret = _rbenv_exec(['install', ruby], env=env, runas=runas, ret=ret)
if ret is not False and ret['retcode'] == 0:
rehash(runas=runas)
return ret['stderr']
else:
# Cleanup the failed installation so it doesn't list as installed
uninstall_ruby(ruby, runas=runas)
return False
def uninstall_ruby(ruby, runas=None):
'''
Uninstall a ruby implementation.
ruby
The version of ruby to uninstall. Should match one of the versions
listed by :py:func:`rbenv.versions <salt.modules.rbenv.versions>`.
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.uninstall_ruby 2.0.0-p0
'''
ruby = re.sub(r'^ruby-', '', ruby)
_rbenv_exec(['uninstall', '--force', ruby], runas=runas)
return True
def versions(runas=None):
'''
List the installed versions of ruby
CLI Example:
.. code-block:: bash
salt '*' rbenv.versions
'''
ret = _rbenv_exec(['versions', '--bare'], runas=runas)
return [] if ret is False else ret.splitlines()
def list_(runas=None):
'''
List the installable versions of ruby
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.list
'''
ret = []
output = _rbenv_exec(['install', '--list'], runas=runas)
if output:
for line in output.splitlines():
if line == 'Available versions:':
continue
ret.append(line.strip())
return ret
def rehash(runas=None):
'''
Run ``rbenv rehash`` to update the installed shims
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.rehash
'''
_rbenv_exec(['rehash'], runas=runas)
return True
def do(cmdline, runas=None, env=None):
'''
Execute a ruby command with rbenv's shims from the user or the system
CLI Example:
.. code-block:: bash
salt '*' rbenv.do 'gem list bundler'
salt '*' rbenv.do 'gem list bundler' deploy
'''
if not cmdline:
# This is a positional argument so this should never happen, but this
# will handle cases where someone explicitly passes a false value for
# cmdline.
raise SaltInvocationError('Command must be specified')
path = _rbenv_path(runas)
if not env:
env = {}
# NOTE: Env vars (and their values) need to be str type on both Python 2
# and 3. The code below first normalizes all path components to unicode to
# stitch them together, and then converts the result back to a str type.
env[str('PATH')] = salt.utils.stringutils.to_str( # future lint: disable=blacklisted-function
os.pathsep.join((
salt.utils.path.join(path, 'shims'),
salt.utils.stringutils.to_unicode(os.environ['PATH'])
))
)
try:
cmdline = salt.utils.args.shlex_split(cmdline)
except AttributeError:
cmdauth = salt.utils.args.shlex_split(six.text_type(cmdline))
result = __salt__['cmd.run_all'](
cmdline,
runas=runas,
env=env,
python_shell=False
)
if result['retcode'] == 0:
rehash(runas=runas)
return result['stdout']
else:
return False
def do_with_ruby(ruby, cmdline, runas=None):
'''
Execute a ruby command with rbenv's shims using a specific ruby version
CLI Example:
.. code-block:: bash
salt '*' rbenv.do_with_ruby 2.0.0-p0 'gem list bundler'
salt '*' rbenv.do_with_ruby 2.0.0-p0 'gem list bundler' runas=deploy
'''
if not cmdline:
# This is a positional argument so this should never happen, but this
# will handle cases where someone explicitly passes a false value for
# cmdline.
raise SaltInvocationError('Command must be specified')
try:
cmdline = salt.utils.args.shlex_split(cmdline)
except AttributeError:
cmdline = salt.utils.args.shlex_split(six.text_type(cmdline))
env = {}
if ruby:
env['RBENV_VERSION'] = ruby
cmd = cmdline
else:
cmd = cmdline
return do(cmd, runas=runas, env=env)
|
saltstack/salt
|
salt/modules/rbenv.py
|
list_
|
python
|
def list_(runas=None):
'''
List the installable versions of ruby
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.list
'''
ret = []
output = _rbenv_exec(['install', '--list'], runas=runas)
if output:
for line in output.splitlines():
if line == 'Available versions:':
continue
ret.append(line.strip())
return ret
|
List the installable versions of ruby
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.list
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rbenv.py#L321-L342
|
[
"def _rbenv_exec(command, env=None, runas=None, ret=None):\n if not is_installed(runas):\n return False\n\n binary = _rbenv_bin(runas)\n path = _rbenv_path(runas)\n\n environ = _parse_env(env)\n environ['RBENV_ROOT'] = path\n\n result = __salt__['cmd.run_all'](\n [binary] + command,\n runas=runas,\n env=environ\n )\n\n if isinstance(ret, dict):\n ret.update(result)\n return ret\n\n if result['retcode'] == 0:\n return result['stdout']\n else:\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Manage ruby installations with rbenv. rbenv is supported on Linux and macOS.
rbenv doesn't work on Windows (and isn't really necessary on Windows as there is
no system Ruby on Windows). On Windows, the RubyInstaller and/or Pik are both
good alternatives to work with multiple versions of Ruby on the same box.
http://misheska.com/blog/2013/06/15/using-rbenv-to-manage-multiple-versions-of-ruby/
.. versionadded:: 0.16.0
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import os
import re
import logging
# Import Salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.path
import salt.utils.platform
from salt.exceptions import SaltInvocationError
# Import 3rd-party libs
from salt.ext import six
# Set up logger
log = logging.getLogger(__name__)
__func_alias__ = {
'list_': 'list'
}
__opts__ = {
'rbenv.root': None,
'rbenv.build_env': None,
}
def __virtual__():
'''
Only work on POSIX-like systems
'''
if salt.utils.platform.is_windows():
return (False, 'The rbenv execution module failed to load: only available on non-Windows systems.')
return True
def _shlex_split(s):
# from python:salt.utils.args.shlex_split: passing None for s will read
# the string to split from standard input.
if s is None:
ret = salt.utils.args.shlex_split('')
else:
ret = salt.utils.args.shlex_split(s)
return ret
def _parse_env(env):
if not env:
env = {}
if isinstance(env, list):
env = salt.utils.data.repack_dictlist(env)
if not isinstance(env, dict):
env = {}
for bad_env_key in (x for x, y in six.iteritems(env) if y is None):
log.error('Environment variable \'%s\' passed without a value. '
'Setting value to an empty string', bad_env_key)
env[bad_env_key] = ''
return env
def _rbenv_bin(runas=None):
path = _rbenv_path(runas)
return '{0}/bin/rbenv'.format(path)
def _rbenv_path(runas=None):
path = None
if runas in (None, 'root'):
path = __salt__['config.option']('rbenv.root') or '/usr/local/rbenv'
else:
path = __salt__['config.option']('rbenv.root') \
or '~{0}/.rbenv'.format(runas)
return os.path.expanduser(path)
def _rbenv_exec(command, env=None, runas=None, ret=None):
if not is_installed(runas):
return False
binary = _rbenv_bin(runas)
path = _rbenv_path(runas)
environ = _parse_env(env)
environ['RBENV_ROOT'] = path
result = __salt__['cmd.run_all'](
[binary] + command,
runas=runas,
env=environ
)
if isinstance(ret, dict):
ret.update(result)
return ret
if result['retcode'] == 0:
return result['stdout']
else:
return False
def _install_rbenv(path, runas=None):
if os.path.isdir(path):
return True
cmd = ['git', 'clone', 'https://github.com/sstephenson/rbenv.git', path]
return __salt__['cmd.retcode'](cmd, runas=runas, python_shell=False) == 0
def _install_ruby_build(path, runas=None):
path = '{0}/plugins/ruby-build'.format(path)
if os.path.isdir(path):
return True
cmd = ['git', 'clone',
'https://github.com/sstephenson/ruby-build.git', path]
return __salt__['cmd.retcode'](cmd, runas=runas, python_shell=False) == 0
def _update_rbenv(path, runas=None):
if not os.path.isdir(path):
return False
return __salt__['cmd.retcode'](['git', 'pull'],
runas=runas,
cwd=path,
python_shell=False) == 0
def _update_ruby_build(path, runas=None):
path = '{0}/plugins/ruby-build'.format(path)
if not os.path.isdir(path):
return False
return __salt__['cmd.retcode'](['git', 'pull'],
runas=runas,
cwd=path,
python_shell=False) == 0
def install(runas=None, path=None):
'''
Install rbenv systemwide
CLI Example:
.. code-block:: bash
salt '*' rbenv.install
'''
path = path or _rbenv_path(runas)
path = os.path.expanduser(path)
return _install_rbenv(path, runas) and _install_ruby_build(path, runas)
def update(runas=None, path=None):
'''
Updates the current versions of rbenv and ruby-build
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.update
'''
path = path or _rbenv_path(runas)
path = os.path.expanduser(path)
return _update_rbenv(path, runas) and _update_ruby_build(path, runas)
def is_installed(runas=None):
'''
Check if rbenv is installed
CLI Example:
.. code-block:: bash
salt '*' rbenv.is_installed
'''
return __salt__['cmd.has_exec'](_rbenv_bin(runas))
def install_ruby(ruby, runas=None):
'''
Install a ruby implementation.
ruby
The version of Ruby to install, should match one of the
versions listed by :py:func:`rbenv.list <salt.modules.rbenv.list>`
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
Additional environment variables can be configured in pillar /
grains / master:
.. code-block:: yaml
rbenv:
build_env: 'CONFIGURE_OPTS="--no-tcmalloc" CFLAGS="-fno-tree-dce"'
CLI Example:
.. code-block:: bash
salt '*' rbenv.install_ruby 2.0.0-p0
'''
ruby = re.sub(r'^ruby-', '', ruby)
env = None
env_list = []
if __grains__['os'] in ('FreeBSD', 'NetBSD', 'OpenBSD'):
env_list.append('MAKE=gmake')
if __salt__['config.get']('rbenv:build_env'):
env_list.append(__salt__['config.get']('rbenv:build_env'))
elif __salt__['config.option']('rbenv.build_env'):
env_list.append(__salt__['config.option']('rbenv.build_env'))
if env_list:
env = ' '.join(env_list)
ret = {}
ret = _rbenv_exec(['install', ruby], env=env, runas=runas, ret=ret)
if ret is not False and ret['retcode'] == 0:
rehash(runas=runas)
return ret['stderr']
else:
# Cleanup the failed installation so it doesn't list as installed
uninstall_ruby(ruby, runas=runas)
return False
def uninstall_ruby(ruby, runas=None):
'''
Uninstall a ruby implementation.
ruby
The version of ruby to uninstall. Should match one of the versions
listed by :py:func:`rbenv.versions <salt.modules.rbenv.versions>`.
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.uninstall_ruby 2.0.0-p0
'''
ruby = re.sub(r'^ruby-', '', ruby)
_rbenv_exec(['uninstall', '--force', ruby], runas=runas)
return True
def versions(runas=None):
'''
List the installed versions of ruby
CLI Example:
.. code-block:: bash
salt '*' rbenv.versions
'''
ret = _rbenv_exec(['versions', '--bare'], runas=runas)
return [] if ret is False else ret.splitlines()
def default(ruby=None, runas=None):
'''
Returns or sets the currently defined default ruby
ruby
The version to set as the default. Should match one of the versions
listed by :py:func:`rbenv.versions <salt.modules.rbenv.versions>`.
Leave blank to return the current default.
CLI Example:
.. code-block:: bash
salt '*' rbenv.default
salt '*' rbenv.default 2.0.0-p0
'''
if ruby:
_rbenv_exec(['global', ruby], runas=runas)
return True
else:
ret = _rbenv_exec(['global'], runas=runas)
return '' if ret is False else ret.strip()
def rehash(runas=None):
'''
Run ``rbenv rehash`` to update the installed shims
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.rehash
'''
_rbenv_exec(['rehash'], runas=runas)
return True
def do(cmdline, runas=None, env=None):
'''
Execute a ruby command with rbenv's shims from the user or the system
CLI Example:
.. code-block:: bash
salt '*' rbenv.do 'gem list bundler'
salt '*' rbenv.do 'gem list bundler' deploy
'''
if not cmdline:
# This is a positional argument so this should never happen, but this
# will handle cases where someone explicitly passes a false value for
# cmdline.
raise SaltInvocationError('Command must be specified')
path = _rbenv_path(runas)
if not env:
env = {}
# NOTE: Env vars (and their values) need to be str type on both Python 2
# and 3. The code below first normalizes all path components to unicode to
# stitch them together, and then converts the result back to a str type.
env[str('PATH')] = salt.utils.stringutils.to_str( # future lint: disable=blacklisted-function
os.pathsep.join((
salt.utils.path.join(path, 'shims'),
salt.utils.stringutils.to_unicode(os.environ['PATH'])
))
)
try:
cmdline = salt.utils.args.shlex_split(cmdline)
except AttributeError:
cmdauth = salt.utils.args.shlex_split(six.text_type(cmdline))
result = __salt__['cmd.run_all'](
cmdline,
runas=runas,
env=env,
python_shell=False
)
if result['retcode'] == 0:
rehash(runas=runas)
return result['stdout']
else:
return False
def do_with_ruby(ruby, cmdline, runas=None):
'''
Execute a ruby command with rbenv's shims using a specific ruby version
CLI Example:
.. code-block:: bash
salt '*' rbenv.do_with_ruby 2.0.0-p0 'gem list bundler'
salt '*' rbenv.do_with_ruby 2.0.0-p0 'gem list bundler' runas=deploy
'''
if not cmdline:
# This is a positional argument so this should never happen, but this
# will handle cases where someone explicitly passes a false value for
# cmdline.
raise SaltInvocationError('Command must be specified')
try:
cmdline = salt.utils.args.shlex_split(cmdline)
except AttributeError:
cmdline = salt.utils.args.shlex_split(six.text_type(cmdline))
env = {}
if ruby:
env['RBENV_VERSION'] = ruby
cmd = cmdline
else:
cmd = cmdline
return do(cmd, runas=runas, env=env)
|
saltstack/salt
|
salt/modules/rbenv.py
|
do
|
python
|
def do(cmdline, runas=None, env=None):
'''
Execute a ruby command with rbenv's shims from the user or the system
CLI Example:
.. code-block:: bash
salt '*' rbenv.do 'gem list bundler'
salt '*' rbenv.do 'gem list bundler' deploy
'''
if not cmdline:
# This is a positional argument so this should never happen, but this
# will handle cases where someone explicitly passes a false value for
# cmdline.
raise SaltInvocationError('Command must be specified')
path = _rbenv_path(runas)
if not env:
env = {}
# NOTE: Env vars (and their values) need to be str type on both Python 2
# and 3. The code below first normalizes all path components to unicode to
# stitch them together, and then converts the result back to a str type.
env[str('PATH')] = salt.utils.stringutils.to_str( # future lint: disable=blacklisted-function
os.pathsep.join((
salt.utils.path.join(path, 'shims'),
salt.utils.stringutils.to_unicode(os.environ['PATH'])
))
)
try:
cmdline = salt.utils.args.shlex_split(cmdline)
except AttributeError:
cmdauth = salt.utils.args.shlex_split(six.text_type(cmdline))
result = __salt__['cmd.run_all'](
cmdline,
runas=runas,
env=env,
python_shell=False
)
if result['retcode'] == 0:
rehash(runas=runas)
return result['stdout']
else:
return False
|
Execute a ruby command with rbenv's shims from the user or the system
CLI Example:
.. code-block:: bash
salt '*' rbenv.do 'gem list bundler'
salt '*' rbenv.do 'gem list bundler' deploy
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rbenv.py#L363-L410
|
[
"def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n",
"def to_str(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str, bytes, bytearray, or unicode (py2), return str\n '''\n def _normalize(s):\n try:\n return unicodedata.normalize('NFC', s) if normalize else s\n except TypeError:\n return s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n # This shouldn't be six.string_types because if we're on PY2 and we already\n # have a string, we should just return it.\n if isinstance(s, str):\n return _normalize(s)\n\n exc = None\n if six.PY3:\n if isinstance(s, (bytes, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytes, or bytearray not {}'.format(type(s)))\n else:\n if isinstance(s, bytearray):\n return str(s) # future lint: disable=blacklisted-function\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n for enc in encoding:\n try:\n return _normalize(s).encode(enc, errors)\n except UnicodeEncodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytearray, or unicode')\n",
"def shlex_split(s, **kwargs):\n '''\n Only split if variable is a string\n '''\n if isinstance(s, six.string_types):\n # On PY2, shlex.split will fail with unicode types if there are\n # non-ascii characters in the string. So, we need to make sure we\n # invoke it with a str type, and then decode the resulting string back\n # to unicode to return it.\n return salt.utils.data.decode(\n shlex.split(salt.utils.stringutils.to_str(s), **kwargs)\n )\n else:\n return s\n",
"def rehash(runas=None):\n '''\n Run ``rbenv rehash`` to update the installed shims\n\n runas\n The user under which to run rbenv. If not specified, then rbenv will be\n run as the user under which Salt is running.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' rbenv.rehash\n '''\n _rbenv_exec(['rehash'], runas=runas)\n return True\n",
"def _rbenv_path(runas=None):\n path = None\n if runas in (None, 'root'):\n path = __salt__['config.option']('rbenv.root') or '/usr/local/rbenv'\n else:\n path = __salt__['config.option']('rbenv.root') \\\n or '~{0}/.rbenv'.format(runas)\n\n return os.path.expanduser(path)\n"
] |
# -*- coding: utf-8 -*-
'''
Manage ruby installations with rbenv. rbenv is supported on Linux and macOS.
rbenv doesn't work on Windows (and isn't really necessary on Windows as there is
no system Ruby on Windows). On Windows, the RubyInstaller and/or Pik are both
good alternatives to work with multiple versions of Ruby on the same box.
http://misheska.com/blog/2013/06/15/using-rbenv-to-manage-multiple-versions-of-ruby/
.. versionadded:: 0.16.0
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import os
import re
import logging
# Import Salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.path
import salt.utils.platform
from salt.exceptions import SaltInvocationError
# Import 3rd-party libs
from salt.ext import six
# Set up logger
log = logging.getLogger(__name__)
__func_alias__ = {
'list_': 'list'
}
__opts__ = {
'rbenv.root': None,
'rbenv.build_env': None,
}
def __virtual__():
'''
Only work on POSIX-like systems
'''
if salt.utils.platform.is_windows():
return (False, 'The rbenv execution module failed to load: only available on non-Windows systems.')
return True
def _shlex_split(s):
# from python:salt.utils.args.shlex_split: passing None for s will read
# the string to split from standard input.
if s is None:
ret = salt.utils.args.shlex_split('')
else:
ret = salt.utils.args.shlex_split(s)
return ret
def _parse_env(env):
if not env:
env = {}
if isinstance(env, list):
env = salt.utils.data.repack_dictlist(env)
if not isinstance(env, dict):
env = {}
for bad_env_key in (x for x, y in six.iteritems(env) if y is None):
log.error('Environment variable \'%s\' passed without a value. '
'Setting value to an empty string', bad_env_key)
env[bad_env_key] = ''
return env
def _rbenv_bin(runas=None):
path = _rbenv_path(runas)
return '{0}/bin/rbenv'.format(path)
def _rbenv_path(runas=None):
path = None
if runas in (None, 'root'):
path = __salt__['config.option']('rbenv.root') or '/usr/local/rbenv'
else:
path = __salt__['config.option']('rbenv.root') \
or '~{0}/.rbenv'.format(runas)
return os.path.expanduser(path)
def _rbenv_exec(command, env=None, runas=None, ret=None):
if not is_installed(runas):
return False
binary = _rbenv_bin(runas)
path = _rbenv_path(runas)
environ = _parse_env(env)
environ['RBENV_ROOT'] = path
result = __salt__['cmd.run_all'](
[binary] + command,
runas=runas,
env=environ
)
if isinstance(ret, dict):
ret.update(result)
return ret
if result['retcode'] == 0:
return result['stdout']
else:
return False
def _install_rbenv(path, runas=None):
if os.path.isdir(path):
return True
cmd = ['git', 'clone', 'https://github.com/sstephenson/rbenv.git', path]
return __salt__['cmd.retcode'](cmd, runas=runas, python_shell=False) == 0
def _install_ruby_build(path, runas=None):
path = '{0}/plugins/ruby-build'.format(path)
if os.path.isdir(path):
return True
cmd = ['git', 'clone',
'https://github.com/sstephenson/ruby-build.git', path]
return __salt__['cmd.retcode'](cmd, runas=runas, python_shell=False) == 0
def _update_rbenv(path, runas=None):
if not os.path.isdir(path):
return False
return __salt__['cmd.retcode'](['git', 'pull'],
runas=runas,
cwd=path,
python_shell=False) == 0
def _update_ruby_build(path, runas=None):
path = '{0}/plugins/ruby-build'.format(path)
if not os.path.isdir(path):
return False
return __salt__['cmd.retcode'](['git', 'pull'],
runas=runas,
cwd=path,
python_shell=False) == 0
def install(runas=None, path=None):
'''
Install rbenv systemwide
CLI Example:
.. code-block:: bash
salt '*' rbenv.install
'''
path = path or _rbenv_path(runas)
path = os.path.expanduser(path)
return _install_rbenv(path, runas) and _install_ruby_build(path, runas)
def update(runas=None, path=None):
'''
Updates the current versions of rbenv and ruby-build
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.update
'''
path = path or _rbenv_path(runas)
path = os.path.expanduser(path)
return _update_rbenv(path, runas) and _update_ruby_build(path, runas)
def is_installed(runas=None):
'''
Check if rbenv is installed
CLI Example:
.. code-block:: bash
salt '*' rbenv.is_installed
'''
return __salt__['cmd.has_exec'](_rbenv_bin(runas))
def install_ruby(ruby, runas=None):
'''
Install a ruby implementation.
ruby
The version of Ruby to install, should match one of the
versions listed by :py:func:`rbenv.list <salt.modules.rbenv.list>`
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
Additional environment variables can be configured in pillar /
grains / master:
.. code-block:: yaml
rbenv:
build_env: 'CONFIGURE_OPTS="--no-tcmalloc" CFLAGS="-fno-tree-dce"'
CLI Example:
.. code-block:: bash
salt '*' rbenv.install_ruby 2.0.0-p0
'''
ruby = re.sub(r'^ruby-', '', ruby)
env = None
env_list = []
if __grains__['os'] in ('FreeBSD', 'NetBSD', 'OpenBSD'):
env_list.append('MAKE=gmake')
if __salt__['config.get']('rbenv:build_env'):
env_list.append(__salt__['config.get']('rbenv:build_env'))
elif __salt__['config.option']('rbenv.build_env'):
env_list.append(__salt__['config.option']('rbenv.build_env'))
if env_list:
env = ' '.join(env_list)
ret = {}
ret = _rbenv_exec(['install', ruby], env=env, runas=runas, ret=ret)
if ret is not False and ret['retcode'] == 0:
rehash(runas=runas)
return ret['stderr']
else:
# Cleanup the failed installation so it doesn't list as installed
uninstall_ruby(ruby, runas=runas)
return False
def uninstall_ruby(ruby, runas=None):
'''
Uninstall a ruby implementation.
ruby
The version of ruby to uninstall. Should match one of the versions
listed by :py:func:`rbenv.versions <salt.modules.rbenv.versions>`.
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.uninstall_ruby 2.0.0-p0
'''
ruby = re.sub(r'^ruby-', '', ruby)
_rbenv_exec(['uninstall', '--force', ruby], runas=runas)
return True
def versions(runas=None):
'''
List the installed versions of ruby
CLI Example:
.. code-block:: bash
salt '*' rbenv.versions
'''
ret = _rbenv_exec(['versions', '--bare'], runas=runas)
return [] if ret is False else ret.splitlines()
def default(ruby=None, runas=None):
'''
Returns or sets the currently defined default ruby
ruby
The version to set as the default. Should match one of the versions
listed by :py:func:`rbenv.versions <salt.modules.rbenv.versions>`.
Leave blank to return the current default.
CLI Example:
.. code-block:: bash
salt '*' rbenv.default
salt '*' rbenv.default 2.0.0-p0
'''
if ruby:
_rbenv_exec(['global', ruby], runas=runas)
return True
else:
ret = _rbenv_exec(['global'], runas=runas)
return '' if ret is False else ret.strip()
def list_(runas=None):
'''
List the installable versions of ruby
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.list
'''
ret = []
output = _rbenv_exec(['install', '--list'], runas=runas)
if output:
for line in output.splitlines():
if line == 'Available versions:':
continue
ret.append(line.strip())
return ret
def rehash(runas=None):
'''
Run ``rbenv rehash`` to update the installed shims
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.rehash
'''
_rbenv_exec(['rehash'], runas=runas)
return True
def do_with_ruby(ruby, cmdline, runas=None):
'''
Execute a ruby command with rbenv's shims using a specific ruby version
CLI Example:
.. code-block:: bash
salt '*' rbenv.do_with_ruby 2.0.0-p0 'gem list bundler'
salt '*' rbenv.do_with_ruby 2.0.0-p0 'gem list bundler' runas=deploy
'''
if not cmdline:
# This is a positional argument so this should never happen, but this
# will handle cases where someone explicitly passes a false value for
# cmdline.
raise SaltInvocationError('Command must be specified')
try:
cmdline = salt.utils.args.shlex_split(cmdline)
except AttributeError:
cmdline = salt.utils.args.shlex_split(six.text_type(cmdline))
env = {}
if ruby:
env['RBENV_VERSION'] = ruby
cmd = cmdline
else:
cmd = cmdline
return do(cmd, runas=runas, env=env)
|
saltstack/salt
|
salt/modules/rbenv.py
|
do_with_ruby
|
python
|
def do_with_ruby(ruby, cmdline, runas=None):
'''
Execute a ruby command with rbenv's shims using a specific ruby version
CLI Example:
.. code-block:: bash
salt '*' rbenv.do_with_ruby 2.0.0-p0 'gem list bundler'
salt '*' rbenv.do_with_ruby 2.0.0-p0 'gem list bundler' runas=deploy
'''
if not cmdline:
# This is a positional argument so this should never happen, but this
# will handle cases where someone explicitly passes a false value for
# cmdline.
raise SaltInvocationError('Command must be specified')
try:
cmdline = salt.utils.args.shlex_split(cmdline)
except AttributeError:
cmdline = salt.utils.args.shlex_split(six.text_type(cmdline))
env = {}
if ruby:
env['RBENV_VERSION'] = ruby
cmd = cmdline
else:
cmd = cmdline
return do(cmd, runas=runas, env=env)
|
Execute a ruby command with rbenv's shims using a specific ruby version
CLI Example:
.. code-block:: bash
salt '*' rbenv.do_with_ruby 2.0.0-p0 'gem list bundler'
salt '*' rbenv.do_with_ruby 2.0.0-p0 'gem list bundler' runas=deploy
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rbenv.py#L413-L442
|
[
"def do(cmdline, runas=None, env=None):\n '''\n Execute a ruby command with rbenv's shims from the user or the system\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' rbenv.do 'gem list bundler'\n salt '*' rbenv.do 'gem list bundler' deploy\n '''\n if not cmdline:\n # This is a positional argument so this should never happen, but this\n # will handle cases where someone explicitly passes a false value for\n # cmdline.\n raise SaltInvocationError('Command must be specified')\n\n path = _rbenv_path(runas)\n if not env:\n env = {}\n\n # NOTE: Env vars (and their values) need to be str type on both Python 2\n # and 3. The code below first normalizes all path components to unicode to\n # stitch them together, and then converts the result back to a str type.\n env[str('PATH')] = salt.utils.stringutils.to_str( # future lint: disable=blacklisted-function\n os.pathsep.join((\n salt.utils.path.join(path, 'shims'),\n salt.utils.stringutils.to_unicode(os.environ['PATH'])\n ))\n )\n\n try:\n cmdline = salt.utils.args.shlex_split(cmdline)\n except AttributeError:\n cmdauth = salt.utils.args.shlex_split(six.text_type(cmdline))\n\n result = __salt__['cmd.run_all'](\n cmdline,\n runas=runas,\n env=env,\n python_shell=False\n )\n\n if result['retcode'] == 0:\n rehash(runas=runas)\n return result['stdout']\n else:\n return False\n",
"def shlex_split(s, **kwargs):\n '''\n Only split if variable is a string\n '''\n if isinstance(s, six.string_types):\n # On PY2, shlex.split will fail with unicode types if there are\n # non-ascii characters in the string. So, we need to make sure we\n # invoke it with a str type, and then decode the resulting string back\n # to unicode to return it.\n return salt.utils.data.decode(\n shlex.split(salt.utils.stringutils.to_str(s), **kwargs)\n )\n else:\n return s\n"
] |
# -*- coding: utf-8 -*-
'''
Manage ruby installations with rbenv. rbenv is supported on Linux and macOS.
rbenv doesn't work on Windows (and isn't really necessary on Windows as there is
no system Ruby on Windows). On Windows, the RubyInstaller and/or Pik are both
good alternatives to work with multiple versions of Ruby on the same box.
http://misheska.com/blog/2013/06/15/using-rbenv-to-manage-multiple-versions-of-ruby/
.. versionadded:: 0.16.0
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import os
import re
import logging
# Import Salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.path
import salt.utils.platform
from salt.exceptions import SaltInvocationError
# Import 3rd-party libs
from salt.ext import six
# Set up logger
log = logging.getLogger(__name__)
__func_alias__ = {
'list_': 'list'
}
__opts__ = {
'rbenv.root': None,
'rbenv.build_env': None,
}
def __virtual__():
'''
Only work on POSIX-like systems
'''
if salt.utils.platform.is_windows():
return (False, 'The rbenv execution module failed to load: only available on non-Windows systems.')
return True
def _shlex_split(s):
# from python:salt.utils.args.shlex_split: passing None for s will read
# the string to split from standard input.
if s is None:
ret = salt.utils.args.shlex_split('')
else:
ret = salt.utils.args.shlex_split(s)
return ret
def _parse_env(env):
if not env:
env = {}
if isinstance(env, list):
env = salt.utils.data.repack_dictlist(env)
if not isinstance(env, dict):
env = {}
for bad_env_key in (x for x, y in six.iteritems(env) if y is None):
log.error('Environment variable \'%s\' passed without a value. '
'Setting value to an empty string', bad_env_key)
env[bad_env_key] = ''
return env
def _rbenv_bin(runas=None):
path = _rbenv_path(runas)
return '{0}/bin/rbenv'.format(path)
def _rbenv_path(runas=None):
path = None
if runas in (None, 'root'):
path = __salt__['config.option']('rbenv.root') or '/usr/local/rbenv'
else:
path = __salt__['config.option']('rbenv.root') \
or '~{0}/.rbenv'.format(runas)
return os.path.expanduser(path)
def _rbenv_exec(command, env=None, runas=None, ret=None):
if not is_installed(runas):
return False
binary = _rbenv_bin(runas)
path = _rbenv_path(runas)
environ = _parse_env(env)
environ['RBENV_ROOT'] = path
result = __salt__['cmd.run_all'](
[binary] + command,
runas=runas,
env=environ
)
if isinstance(ret, dict):
ret.update(result)
return ret
if result['retcode'] == 0:
return result['stdout']
else:
return False
def _install_rbenv(path, runas=None):
if os.path.isdir(path):
return True
cmd = ['git', 'clone', 'https://github.com/sstephenson/rbenv.git', path]
return __salt__['cmd.retcode'](cmd, runas=runas, python_shell=False) == 0
def _install_ruby_build(path, runas=None):
path = '{0}/plugins/ruby-build'.format(path)
if os.path.isdir(path):
return True
cmd = ['git', 'clone',
'https://github.com/sstephenson/ruby-build.git', path]
return __salt__['cmd.retcode'](cmd, runas=runas, python_shell=False) == 0
def _update_rbenv(path, runas=None):
if not os.path.isdir(path):
return False
return __salt__['cmd.retcode'](['git', 'pull'],
runas=runas,
cwd=path,
python_shell=False) == 0
def _update_ruby_build(path, runas=None):
path = '{0}/plugins/ruby-build'.format(path)
if not os.path.isdir(path):
return False
return __salt__['cmd.retcode'](['git', 'pull'],
runas=runas,
cwd=path,
python_shell=False) == 0
def install(runas=None, path=None):
'''
Install rbenv systemwide
CLI Example:
.. code-block:: bash
salt '*' rbenv.install
'''
path = path or _rbenv_path(runas)
path = os.path.expanduser(path)
return _install_rbenv(path, runas) and _install_ruby_build(path, runas)
def update(runas=None, path=None):
'''
Updates the current versions of rbenv and ruby-build
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.update
'''
path = path or _rbenv_path(runas)
path = os.path.expanduser(path)
return _update_rbenv(path, runas) and _update_ruby_build(path, runas)
def is_installed(runas=None):
'''
Check if rbenv is installed
CLI Example:
.. code-block:: bash
salt '*' rbenv.is_installed
'''
return __salt__['cmd.has_exec'](_rbenv_bin(runas))
def install_ruby(ruby, runas=None):
'''
Install a ruby implementation.
ruby
The version of Ruby to install, should match one of the
versions listed by :py:func:`rbenv.list <salt.modules.rbenv.list>`
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
Additional environment variables can be configured in pillar /
grains / master:
.. code-block:: yaml
rbenv:
build_env: 'CONFIGURE_OPTS="--no-tcmalloc" CFLAGS="-fno-tree-dce"'
CLI Example:
.. code-block:: bash
salt '*' rbenv.install_ruby 2.0.0-p0
'''
ruby = re.sub(r'^ruby-', '', ruby)
env = None
env_list = []
if __grains__['os'] in ('FreeBSD', 'NetBSD', 'OpenBSD'):
env_list.append('MAKE=gmake')
if __salt__['config.get']('rbenv:build_env'):
env_list.append(__salt__['config.get']('rbenv:build_env'))
elif __salt__['config.option']('rbenv.build_env'):
env_list.append(__salt__['config.option']('rbenv.build_env'))
if env_list:
env = ' '.join(env_list)
ret = {}
ret = _rbenv_exec(['install', ruby], env=env, runas=runas, ret=ret)
if ret is not False and ret['retcode'] == 0:
rehash(runas=runas)
return ret['stderr']
else:
# Cleanup the failed installation so it doesn't list as installed
uninstall_ruby(ruby, runas=runas)
return False
def uninstall_ruby(ruby, runas=None):
'''
Uninstall a ruby implementation.
ruby
The version of ruby to uninstall. Should match one of the versions
listed by :py:func:`rbenv.versions <salt.modules.rbenv.versions>`.
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.uninstall_ruby 2.0.0-p0
'''
ruby = re.sub(r'^ruby-', '', ruby)
_rbenv_exec(['uninstall', '--force', ruby], runas=runas)
return True
def versions(runas=None):
'''
List the installed versions of ruby
CLI Example:
.. code-block:: bash
salt '*' rbenv.versions
'''
ret = _rbenv_exec(['versions', '--bare'], runas=runas)
return [] if ret is False else ret.splitlines()
def default(ruby=None, runas=None):
'''
Returns or sets the currently defined default ruby
ruby
The version to set as the default. Should match one of the versions
listed by :py:func:`rbenv.versions <salt.modules.rbenv.versions>`.
Leave blank to return the current default.
CLI Example:
.. code-block:: bash
salt '*' rbenv.default
salt '*' rbenv.default 2.0.0-p0
'''
if ruby:
_rbenv_exec(['global', ruby], runas=runas)
return True
else:
ret = _rbenv_exec(['global'], runas=runas)
return '' if ret is False else ret.strip()
def list_(runas=None):
'''
List the installable versions of ruby
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.list
'''
ret = []
output = _rbenv_exec(['install', '--list'], runas=runas)
if output:
for line in output.splitlines():
if line == 'Available versions:':
continue
ret.append(line.strip())
return ret
def rehash(runas=None):
'''
Run ``rbenv rehash`` to update the installed shims
runas
The user under which to run rbenv. If not specified, then rbenv will be
run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rbenv.rehash
'''
_rbenv_exec(['rehash'], runas=runas)
return True
def do(cmdline, runas=None, env=None):
'''
Execute a ruby command with rbenv's shims from the user or the system
CLI Example:
.. code-block:: bash
salt '*' rbenv.do 'gem list bundler'
salt '*' rbenv.do 'gem list bundler' deploy
'''
if not cmdline:
# This is a positional argument so this should never happen, but this
# will handle cases where someone explicitly passes a false value for
# cmdline.
raise SaltInvocationError('Command must be specified')
path = _rbenv_path(runas)
if not env:
env = {}
# NOTE: Env vars (and their values) need to be str type on both Python 2
# and 3. The code below first normalizes all path components to unicode to
# stitch them together, and then converts the result back to a str type.
env[str('PATH')] = salt.utils.stringutils.to_str( # future lint: disable=blacklisted-function
os.pathsep.join((
salt.utils.path.join(path, 'shims'),
salt.utils.stringutils.to_unicode(os.environ['PATH'])
))
)
try:
cmdline = salt.utils.args.shlex_split(cmdline)
except AttributeError:
cmdauth = salt.utils.args.shlex_split(six.text_type(cmdline))
result = __salt__['cmd.run_all'](
cmdline,
runas=runas,
env=env,
python_shell=False
)
if result['retcode'] == 0:
rehash(runas=runas)
return result['stdout']
else:
return False
|
saltstack/salt
|
salt/states/mac_assistive.py
|
installed
|
python
|
def installed(name, enabled=True):
'''
Make sure that we have the given bundle ID or path to command
installed in the assistive access panel.
name
The bundle ID or path to command
enable
Should assistive access be enabled on this application?
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}}
is_installed = __salt__['assistive.installed'](name)
if is_installed:
is_enabled = __salt__['assistive.enabled'](name)
if enabled != is_enabled:
__salt__['assistive.enable'](name, enabled)
ret['comment'] = 'Updated enable to {0}'.format(enabled)
else:
ret['comment'] = 'Already in the correct state'
else:
__salt__['assistive.install'](name, enabled)
ret['comment'] = 'Installed {0} into the assistive access panel'.format(name)
return ret
|
Make sure that we have the given bundle ID or path to command
installed in the assistive access panel.
name
The bundle ID or path to command
enable
Should assistive access be enabled on this application?
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/mac_assistive.py#L38-L70
| null |
# -*- coding: utf-8 -*-
'''
Allows you to manage assistive access on macOS minions with 10.9+
=================================================================
Install, enable and disable assistive access on macOS minions
.. code-block:: yaml
/usr/bin/osacript:
assistive.installed:
- enabled: True
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import logging
# Import Salt libs
import salt.utils.platform
from salt.utils.versions import LooseVersion as _LooseVersion
log = logging.getLogger(__name__)
__virtualname__ = "assistive"
def __virtual__():
'''
Only work on Mac OS
'''
if salt.utils.platform.is_darwin() \
and _LooseVersion(__grains__['osrelease']) >= _LooseVersion('10.9'):
return True
return False
|
saltstack/salt
|
salt/states/service.py
|
_enable
|
python
|
def _enable(name, started, result=True, skip_verify=False, **kwargs):
'''
Enable the service
'''
ret = {}
if not skip_verify:
# is service available?
try:
if not _available(name, ret):
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# Set default expected result
ret['result'] = result
# Check to see if this minion supports enable
if 'service.enable' not in __salt__ or 'service.enabled' not in __salt__:
if started is True:
ret['comment'] = ('Enable is not available on this minion,'
' service {0} started').format(name)
elif started is None:
ret['comment'] = ('Enable is not available on this minion,'
' service {0} is in the desired state'
).format(name)
else:
ret['comment'] = ('Enable is not available on this minion,'
' service {0} is dead').format(name)
return ret
# Service can be enabled
before_toggle_enable_status = __salt__['service.enabled'](name, **kwargs)
if before_toggle_enable_status:
# Service is enabled
if started is True:
ret['comment'] = ('Service {0} is already enabled,'
' and is running').format(name)
elif started is None:
# always be sure in this case to reset the changes dict
ret['changes'] = {}
ret['comment'] = ('Service {0} is already enabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} is already enabled,'
' and is dead').format(name)
return ret
# Service needs to be enabled
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service {0} set to be enabled'.format(name)
return ret
try:
if __salt__['service.enable'](name, **kwargs):
# Service has been enabled
ret['changes'] = {}
after_toggle_enable_status = __salt__['service.enabled'](
name,
**kwargs)
# on upstart, certain services like apparmor will always return
# False, even if correctly activated
# do not trigger a change
if before_toggle_enable_status != after_toggle_enable_status:
ret['changes'][name] = True
if started is True:
ret['comment'] = ('Service {0} has been enabled,'
' and is running').format(name)
elif started is None:
ret['comment'] = ('Service {0} has been enabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} has been enabled,'
' and is dead').format(name)
return ret
except CommandExecutionError as exc:
enable_error = exc.strerror
else:
enable_error = False
# Service failed to be enabled
ret['result'] = False
if started is True:
ret['comment'] = ('Failed when setting service {0} to start at boot,'
' but the service is running').format(name)
elif started is None:
ret['comment'] = ('Failed when setting service {0} to start at boot,'
' but the service was already running').format(name)
else:
ret['comment'] = ('Failed when setting service {0} to start at boot,'
' and the service is dead').format(name)
if enable_error:
ret['comment'] += '. Additional information follows:\n\n{0}'.format(
enable_error
)
return ret
|
Enable the service
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/service.py#L123-L223
|
[
"def _available(name, ret):\n '''\n Check if the service is available\n '''\n avail = False\n if 'service.available' in __salt__:\n avail = __salt__['service.available'](name)\n elif 'service.get_all' in __salt__:\n avail = name in __salt__['service.get_all']()\n if not avail:\n ret['result'] = False\n ret['comment'] = 'The named service {0} is not available'.format(name)\n return avail\n"
] |
# -*- coding: utf-8 -*-
'''
Starting or restarting of services and daemons
==============================================
Services are defined as system daemons and are typically launched using system
init or rc scripts. This service state uses whichever service module is loaded
on the minion with the virtualname of ``service``. Services can be defined as
either running or dead.
If you need to know if your init system is supported, see the list of supported
:mod:`service modules <salt.modules.service.py>` for your desired init system
(systemd, sysvinit, launchctl, etc.).
Note that Salt's service execution module, and therefore this service state,
uses OS grains to ascertain which service module should be loaded and used to
execute service functions. As existing distributions change init systems or
new distributions are created, OS detection can sometimes be incomplete.
If your service states are running into trouble with init system detection,
please see the :ref:`Overriding Virtual Module Providers <module-provider-override>`
section of Salt's module documentation to work around possible errors.
.. note::
The current status of a service is determined by the return code of the init/rc
script status command. A status return code of 0 it is considered running. Any
other return code is considered dead.
.. code-block:: yaml
httpd:
service.running: []
The service can also be set to start at runtime via the enable option:
.. code-block:: yaml
openvpn:
service.running:
- enable: True
By default if a service is triggered to refresh due to a watch statement the
service is restarted. If the desired behavior is to reload the service, then
set the reload value to True:
.. code-block:: yaml
redis:
service.running:
- enable: True
- reload: True
- watch:
- pkg: redis
.. note::
More details regarding ``watch`` can be found in the
:ref:`Requisites <requisites>` documentation.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
# Import Salt libs
import salt.utils.data
import salt.utils.platform
from salt.utils.args import get_function_argspec as _argspec
from salt.exceptions import CommandExecutionError
from salt.state import _gen_tag
# Import 3rd-party libs
from salt.ext import six
SYSTEMD_ONLY = ('no_block', 'unmask', 'unmask_runtime')
__virtualname__ = 'service'
def __virtual__():
'''
Only make these states available if a service provider has been detected or
assigned for this minion
'''
if 'service.start' in __salt__:
return __virtualname__
else:
return (False, 'No service execution module loaded: '
'check support for service management on {0} '
''.format(__grains__.get('osfinger', __grains__['os']))
)
# Double-asterisk deliberately not used here
def _get_systemd_only(func, kwargs):
ret = {}
warnings = []
valid_args = _argspec(func).args
for systemd_arg in SYSTEMD_ONLY:
arg_val = kwargs.get(systemd_arg, False)
if arg_val:
if systemd_arg in valid_args:
ret[systemd_arg] = arg_val
else:
warnings.append(
'The \'{0}\' argument is not supported by this '
'platform/action'.format(systemd_arg)
)
return ret, warnings
def _enabled_used_error(ret):
'''
Warn of potential typo.
'''
ret['result'] = False
ret['comment'] = (
'Service {0} uses non-existent option "enabled". ' +
'Perhaps "enable" option was intended?'
).format(ret['name'])
return ret
def _disable(name, started, result=True, skip_verify=False, **kwargs):
'''
Disable the service
'''
ret = {}
if not skip_verify:
# is service available?
try:
if not _available(name, ret):
ret['result'] = True
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# Set default expected result
ret['result'] = result
# is enable/disable available?
if 'service.disable' not in __salt__ or 'service.disabled' not in __salt__:
if started is True:
ret['comment'] = ('Disable is not available on this minion,'
' service {0} started').format(name)
elif started is None:
ret['comment'] = ('Disable is not available on this minion,'
' service {0} is in the desired state'
).format(name)
else:
ret['comment'] = ('Disable is not available on this minion,'
' service {0} is dead').format(name)
return ret
# Service can be disabled
if salt.utils.platform.is_windows():
# service.disabled in Windows returns True for services that are set to
# Manual start, so we need to check specifically for Disabled
before_toggle_disable_status = __salt__['service.info'](name)['StartType'] in ['Disabled']
else:
before_toggle_disable_status = __salt__['service.disabled'](name)
if before_toggle_disable_status:
# Service is disabled
if started is True:
ret['comment'] = ('Service {0} is already disabled,'
' and is running').format(name)
elif started is None:
# always be sure in this case to reset the changes dict
ret['changes'] = {}
ret['comment'] = ('Service {0} is already disabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} is already disabled,'
' and is dead').format(name)
return ret
# Service needs to be disabled
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service {0} set to be disabled'.format(name)
return ret
if __salt__['service.disable'](name, **kwargs):
# Service has been disabled
ret['changes'] = {}
after_toggle_disable_status = __salt__['service.disabled'](name)
# on upstart, certain services like apparmor will always return
# False, even if correctly activated
# do not trigger a change
if before_toggle_disable_status != after_toggle_disable_status:
ret['changes'][name] = True
if started is True:
ret['comment'] = ('Service {0} has been disabled,'
' and is running').format(name)
elif started is None:
ret['comment'] = ('Service {0} has been disabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} has been disabled,'
' and is dead').format(name)
return ret
# Service failed to be disabled
ret['result'] = False
if started is True:
ret['comment'] = ('Failed when setting service {0} to not start'
' at boot, and is running').format(name)
elif started is None:
ret['comment'] = ('Failed when setting service {0} to not start'
' at boot, but the service was already running'
).format(name)
else:
ret['comment'] = ('Failed when setting service {0} to not start'
' at boot, and the service is dead').format(name)
return ret
def _available(name, ret):
'''
Check if the service is available
'''
avail = False
if 'service.available' in __salt__:
avail = __salt__['service.available'](name)
elif 'service.get_all' in __salt__:
avail = name in __salt__['service.get_all']()
if not avail:
ret['result'] = False
ret['comment'] = 'The named service {0} is not available'.format(name)
return avail
def running(name,
enable=None,
sig=None,
init_delay=None,
no_block=False,
unmask=False,
unmask_runtime=False,
**kwargs):
'''
Ensure that the service is running
name
The name of the init or rc script used to manage the service
enable
Set the service to be enabled at boot time, ``True`` sets the service
to be enabled, ``False`` sets the named service to be disabled. The
default is ``None``, which does not enable or disable anything.
sig
The string to search for when looking for the service process with ps
init_delay
Some services may not be truly available for a short period after their
startup script indicates to the system that they are. Provide an
'init_delay' to specify that this state should wait an additional given
number of seconds after a service has started before returning. Useful
for requisite states wherein a dependent state might assume a service
has started but is not yet fully initialized.
no_block : False
**For systemd minions only.** Starts the service using ``--no-block``.
.. versionadded:: 2017.7.0
unmask : False
**For systemd minions only.** Set to ``True`` to remove an indefinite
mask before attempting to start the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
making any changes. This behavior is no longer the default.
unmask_runtime : False
**For systemd minions only.** Set to ``True`` to remove a runtime mask
before attempting to start the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
making any changes. This behavior is no longer the default.
.. note::
``watch`` can be used with service.running to restart a service when
another state changes ( example: a file.managed state that creates the
service's config file ). More details regarding ``watch`` can be found
in the :ref:`Requisites <requisites>` documentation.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
# Check for common error: using enabled option instead of enable
if 'enabled' in kwargs:
return _enabled_used_error(ret)
# Convert enable to boolean in case user passed a string value
if isinstance(enable, six.string_types):
enable = salt.utils.data.is_true(enable)
# Check if the service is available
try:
if not _available(name, ret):
if __opts__.get('test'):
ret['result'] = None
ret['comment'] = 'Service {0} not present; if created in this state run, it would have been started'.format(name)
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# lot of custom init script won't or mis implement the status
# command, so it is just an indicator but can not be fully trusted
before_toggle_status = __salt__['service.status'](name, sig)
if 'service.enabled' in __salt__:
before_toggle_enable_status = __salt__['service.enabled'](name)
else:
before_toggle_enable_status = True
unmask_ret = {'comment': ''}
if unmask:
unmask_ret = unmasked(name, unmask_runtime)
# See if the service is already running
if before_toggle_status:
ret['comment'] = '\n'.join(
[_f for _f in ['The service {0} is already running'.format(name),
unmask_ret['comment']] if _f]
)
if enable is True and not before_toggle_enable_status:
ret.update(_enable(name, None, skip_verify=False, **kwargs))
elif enable is False and before_toggle_enable_status:
ret.update(_disable(name, None, skip_verify=False, **kwargs))
return ret
# Run the tests
if __opts__['test']:
ret['result'] = None
ret['comment'] = '\n'.join(
[_f for _f in ['Service {0} is set to start'.format(name),
unmask_ret['comment']] if _f])
return ret
# Conditionally add systemd-specific args to call to service.start
start_kwargs, warnings = \
_get_systemd_only(__salt__['service.start'], locals())
if warnings:
ret.setdefault('warnings', []).extend(warnings)
if salt.utils.platform.is_windows():
for arg in ['timeout', 'with_deps', 'with_parents']:
if kwargs.get(arg, False):
start_kwargs.update({arg: kwargs.get(arg)})
try:
func_ret = __salt__['service.start'](name, **start_kwargs)
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
if not func_ret:
ret['result'] = False
ret['comment'] = 'Service {0} failed to start'.format(name)
if enable is True:
ret.update(_enable(name, False, result=False, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, False, result=False, skip_verify=False, **kwargs))
return ret
if init_delay:
time.sleep(init_delay)
# only force a change state if we have explicitly detected them
after_toggle_status = __salt__['service.status'](name, sig)
if 'service.enabled' in __salt__:
after_toggle_enable_status = __salt__['service.enabled'](name)
else:
after_toggle_enable_status = True
if (
(before_toggle_enable_status != after_toggle_enable_status) or
(before_toggle_status != after_toggle_status)
) and not ret.get('changes', {}):
ret['changes'][name] = after_toggle_status
if after_toggle_status:
ret['comment'] = 'Started Service {0}'.format(name)
else:
ret['comment'] = 'Service {0} failed to start'.format(name)
ret['result'] = False
if enable is True:
ret.update(_enable(name, after_toggle_status, result=after_toggle_status, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, after_toggle_status, result=after_toggle_status, skip_verify=False, **kwargs))
if init_delay:
ret['comment'] = (
'{0}\nDelayed return for {1} seconds'
.format(ret['comment'], init_delay)
)
if unmask:
ret['comment'] = '\n'.join([ret['comment'], unmask_ret['comment']])
return ret
def dead(name,
enable=None,
sig=None,
init_delay=None,
**kwargs):
'''
Ensure that the named service is dead by stopping the service if it is running
name
The name of the init or rc script used to manage the service
enable
Set the service to be enabled at boot time, ``True`` sets the service
to be enabled, ``False`` sets the named service to be disabled. The
default is ``None``, which does not enable or disable anything.
sig
The string to search for when looking for the service process with ps
init_delay
Add a sleep command (in seconds) before the check to make sure service
is killed.
.. versionadded:: 2017.7.0
no_block : False
**For systemd minions only.** Stops the service using ``--no-block``.
.. versionadded:: 2017.7.0
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
# Check for common error: using enabled option instead of enable
if 'enabled' in kwargs:
return _enabled_used_error(ret)
# Convert enable to boolean in case user passed a string value
if isinstance(enable, six.string_types):
enable = salt.utils.data.is_true(enable)
# Check if the service is available
try:
if not _available(name, ret):
if __opts__.get('test'):
ret['result'] = None
ret['comment'] = 'Service {0} not present; if created in this state run, it would have been stopped'.format(name)
else:
# A non-available service is OK here, don't let the state fail
# because of it.
ret['result'] = True
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# lot of custom init script won't or mis implement the status
# command, so it is just an indicator but can not be fully trusted
before_toggle_status = __salt__['service.status'](name, sig)
if 'service.enabled' in __salt__:
if salt.utils.platform.is_windows():
# service.enabled in Windows returns True for services that are set
# to Auto start, but services set to Manual can also be disabled
before_toggle_enable_status = __salt__['service.info'](name)['StartType'] in ['Auto', 'Manual']
else:
before_toggle_enable_status = __salt__['service.enabled'](name)
else:
before_toggle_enable_status = True
# See if the service is already dead
if not before_toggle_status:
ret['comment'] = 'The service {0} is already dead'.format(name)
if enable is True and not before_toggle_enable_status:
ret.update(_enable(name, None, skip_verify=False, **kwargs))
elif enable is False and before_toggle_enable_status:
ret.update(_disable(name, None, skip_verify=False, **kwargs))
return ret
# Run the tests
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service {0} is set to be killed'.format(name)
return ret
# Conditionally add systemd-specific args to call to service.start
stop_kwargs, warnings = _get_systemd_only(__salt__['service.stop'], kwargs)
if warnings:
ret.setdefault('warnings', []).extend(warnings)
if salt.utils.platform.is_windows():
for arg in ['timeout', 'with_deps', 'with_parents']:
if kwargs.get(arg, False):
stop_kwargs.update({arg: kwargs.get(arg)})
func_ret = __salt__['service.stop'](name, **stop_kwargs)
if not func_ret:
ret['result'] = False
ret['comment'] = 'Service {0} failed to die'.format(name)
if enable is True:
ret.update(_enable(name, True, result=False, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, True, result=False, skip_verify=False, **kwargs))
return ret
if init_delay:
time.sleep(init_delay)
# only force a change state if we have explicitly detected them
after_toggle_status = __salt__['service.status'](name)
if 'service.enabled' in __salt__:
after_toggle_enable_status = __salt__['service.enabled'](name)
else:
after_toggle_enable_status = True
if (
(before_toggle_enable_status != after_toggle_enable_status) or
(before_toggle_status != after_toggle_status)
) and not ret.get('changes', {}):
ret['changes'][name] = after_toggle_status
# be sure to stop, in case we mis detected in the check
if after_toggle_status:
ret['result'] = False
ret['comment'] = 'Service {0} failed to die'.format(name)
else:
ret['comment'] = 'Service {0} was killed'.format(name)
if enable is True:
ret.update(_enable(name, after_toggle_status, result=not after_toggle_status, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, after_toggle_status, result=not after_toggle_status, skip_verify=False, **kwargs))
return ret
def enabled(name,
skip_verify=False,
**kwargs):
'''
Ensure that the service is enabled on boot, only use this state if you
don't want to manage the running process, remember that if you want to
enable a running service to use the enable: True option for the running
or dead function.
name
The name of the init or rc script used to manage the service
skip_verify
Skip verifying that the service is available before enabling it.
``True`` will skip the verification. The default is ``False``,
which will ensure the service is available before enabling it.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
ret.update(_enable(name, None, skip_verify=skip_verify, **kwargs))
return ret
def disabled(name,
skip_verify=False,
**kwargs):
'''
Ensure that the service is disabled on boot, only use this state if you
don't want to manage the running process, remember that if you want to
disable a service to use the enable: False option for the running or dead
function.
name
The name of the init or rc script used to manage the service
skip_verify
Skip verifying that the service is available before disabling it.
``True`` will skip the verification. The default is ``False``,
which will ensure the service is available before disabling it.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
ret.update(_disable(name, None, skip_verify=skip_verify, **kwargs))
return ret
def masked(name, runtime=False):
'''
.. versionadded:: 2017.7.0
.. note::
This state is only available on minions which use systemd_.
Ensures that the named service is masked (i.e. prevented from being
started).
name
Name of the service to mask
runtime : False
By default, this state will manage an indefinite mask for the named
service. Set this argument to ``True`` to runtime mask the service.
.. note::
It is possible for a service to have both indefinite and runtime masks
set for it. Therefore, this state will manage a runtime or indefinite
mask independently of each other. This means that if the service is
already indefinitely masked, running this state with ``runtime`` set to
``True`` will _not_ remove the indefinite mask before setting a runtime
mask. In these cases, if it is desirable to ensure that the service is
runtime masked and not indefinitely masked, pair this state with a
:py:func:`service.unmasked <salt.states.service.unmasked>` state, like
so:
.. code-block:: yaml
mask_runtime_foo:
service.masked:
- name: foo
- runtime: True
unmask_indefinite_foo:
service.unmasked:
- name: foo
- runtime: False
.. _systemd: https://freedesktop.org/wiki/Software/systemd/
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if 'service.masked' not in __salt__:
ret['comment'] = 'Service masking not available on this minion'
ret['result'] = False
return ret
mask_type = 'runtime masked' if runtime else 'masked'
expected_changes = {mask_type: {'old': False, 'new': True}}
try:
if __salt__['service.masked'](name, runtime):
ret['comment'] = 'Service {0} is already {1}'.format(
name,
mask_type,
)
return ret
if __opts__['test']:
ret['result'] = None
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} would be {1}'.format(name, mask_type)
return ret
__salt__['service.mask'](name, runtime)
if __salt__['service.masked'](name, runtime):
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} was {1}'.format(name, mask_type)
else:
ret['comment'] = 'Failed to mask service {0}'.format(name)
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
def unmasked(name, runtime=False):
'''
.. versionadded:: 2017.7.0
.. note::
This state is only available on minions which use systemd_.
Ensures that the named service is unmasked
name
Name of the service to unmask
runtime : False
By default, this state will manage an indefinite mask for the named
service. Set this argument to ``True`` to ensure that the service is
runtime masked.
.. note::
It is possible for a service to have both indefinite and runtime masks
set for it. Therefore, this state will manage a runtime or indefinite
mask independently of each other. This means that if the service is
indefinitely masked, running this state with ``runtime`` set to
``True`` will _not_ remove the indefinite mask.
.. _systemd: https://freedesktop.org/wiki/Software/systemd/
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if 'service.masked' not in __salt__:
ret['comment'] = 'Service masking not available on this minion'
ret['result'] = False
return ret
mask_type = 'runtime masked' if runtime else 'masked'
action = 'runtime unmasked' if runtime else 'unmasked'
expected_changes = {mask_type: {'old': True, 'new': False}}
try:
if not __salt__['service.masked'](name, runtime):
ret['comment'] = 'Service {0} was already {1}'.format(name, action)
return ret
if __opts__['test']:
ret['result'] = None
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} would be {1}'.format(name, action)
return ret
__salt__['service.unmask'](name, runtime)
if not __salt__['service.masked'](name, runtime):
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} was {1}'.format(name, action)
else:
ret['comment'] = 'Failed to unmask service {0}'.format(name)
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
def mod_watch(name,
sfun=None,
sig=None,
full_restart=False,
init_delay=None,
force=False,
**kwargs):
'''
The service watcher, called to invoke the watch command.
When called, it will restart or reload the named service.
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the watching service.
(i.e. ``service.running``)
name
The name of the init or rc script used to manage the service
sfun
The original function which triggered the mod_watch call
(`service.running`, for example).
sig
The string to search for when looking for the service process with ps
reload
If True use reload instead of the default restart. If value is a list of
requisites; reload only if all watched changes are contained in the reload list.
Otherwise watch will restart.
full_restart
Use service.full_restart instead of restart.
When set, reload the service instead of restarting it.
(i.e. ``service nginx reload``)
full_restart
Perform a full stop/start of a service by passing ``--full-restart``.
This option is ignored if ``reload`` is set and is supported by only a few
:py:func:`service modules <salt.modules.service>`.
force
Use service.force_reload instead of reload (needs reload to be set to True)
init_delay
Add a sleep command (in seconds) before the service is restarted/reloaded
'''
reload_ = kwargs.pop('reload', False)
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
past_participle = None
if sfun == 'dead':
verb = 'stop'
past_participle = verb + 'ped'
if __salt__['service.status'](name, sig):
func = __salt__['service.stop']
else:
ret['result'] = True
ret['comment'] = 'Service is already {0}'.format(past_participle)
return ret
elif sfun == 'running':
if __salt__['service.status'](name, sig):
if 'service.reload' in __salt__ and reload_:
if isinstance(reload_, list):
only_reload_needed = True
for watch_item in kwargs['__reqs__']['watch']:
if __running__[_gen_tag(watch_item)]['changes']:
match_found = False
for this_reload in reload_:
for state, id_ in six.iteritems(this_reload):
if state == watch_item['state'] \
and id_ == watch_item['__id__']:
match_found = True
if not match_found:
only_reload_needed = False
if only_reload_needed:
if 'service.force_reload' in __salt__ and force:
func = __salt__['service.force_reload']
verb = 'forcefully reload'
else:
func = __salt__['service.reload']
verb = 'reload'
else:
if 'service.full_restart' in __salt__ and full_restart:
func = __salt__['service.full_restart']
verb = 'fully restart'
else:
func = __salt__['service.restart']
verb = 'restart'
else:
if 'service.force_reload' in __salt__ and force:
func = __salt__['service.force_reload']
verb = 'forcefully reload'
else:
func = __salt__['service.reload']
verb = 'reload'
elif 'service.full_restart' in __salt__ and full_restart:
func = __salt__['service.full_restart']
verb = 'fully restart'
else:
func = __salt__['service.restart']
verb = 'restart'
else:
func = __salt__['service.start']
verb = 'start'
if not past_participle:
past_participle = verb + 'ed'
else:
ret['comment'] = 'Unable to trigger watch for service.{0}'.format(sfun)
ret['result'] = False
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service is set to be {0}'.format(past_participle)
return ret
if verb == 'start' and 'service.stop' in __salt__:
# stop service before start
__salt__['service.stop'](name)
func_kwargs, warnings = _get_systemd_only(func, kwargs)
if warnings:
ret.setdefault('warnings', []).extend(warnings)
try:
result = func(name, **func_kwargs)
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
if init_delay:
time.sleep(init_delay)
ret['changes'] = {name: result}
ret['result'] = result
ret['comment'] = 'Service {0}'.format(past_participle) if result else \
'Failed to {0} the service'.format(verb)
return ret
|
saltstack/salt
|
salt/states/service.py
|
_disable
|
python
|
def _disable(name, started, result=True, skip_verify=False, **kwargs):
'''
Disable the service
'''
ret = {}
if not skip_verify:
# is service available?
try:
if not _available(name, ret):
ret['result'] = True
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# Set default expected result
ret['result'] = result
# is enable/disable available?
if 'service.disable' not in __salt__ or 'service.disabled' not in __salt__:
if started is True:
ret['comment'] = ('Disable is not available on this minion,'
' service {0} started').format(name)
elif started is None:
ret['comment'] = ('Disable is not available on this minion,'
' service {0} is in the desired state'
).format(name)
else:
ret['comment'] = ('Disable is not available on this minion,'
' service {0} is dead').format(name)
return ret
# Service can be disabled
if salt.utils.platform.is_windows():
# service.disabled in Windows returns True for services that are set to
# Manual start, so we need to check specifically for Disabled
before_toggle_disable_status = __salt__['service.info'](name)['StartType'] in ['Disabled']
else:
before_toggle_disable_status = __salt__['service.disabled'](name)
if before_toggle_disable_status:
# Service is disabled
if started is True:
ret['comment'] = ('Service {0} is already disabled,'
' and is running').format(name)
elif started is None:
# always be sure in this case to reset the changes dict
ret['changes'] = {}
ret['comment'] = ('Service {0} is already disabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} is already disabled,'
' and is dead').format(name)
return ret
# Service needs to be disabled
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service {0} set to be disabled'.format(name)
return ret
if __salt__['service.disable'](name, **kwargs):
# Service has been disabled
ret['changes'] = {}
after_toggle_disable_status = __salt__['service.disabled'](name)
# on upstart, certain services like apparmor will always return
# False, even if correctly activated
# do not trigger a change
if before_toggle_disable_status != after_toggle_disable_status:
ret['changes'][name] = True
if started is True:
ret['comment'] = ('Service {0} has been disabled,'
' and is running').format(name)
elif started is None:
ret['comment'] = ('Service {0} has been disabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} has been disabled,'
' and is dead').format(name)
return ret
# Service failed to be disabled
ret['result'] = False
if started is True:
ret['comment'] = ('Failed when setting service {0} to not start'
' at boot, and is running').format(name)
elif started is None:
ret['comment'] = ('Failed when setting service {0} to not start'
' at boot, but the service was already running'
).format(name)
else:
ret['comment'] = ('Failed when setting service {0} to not start'
' at boot, and the service is dead').format(name)
return ret
|
Disable the service
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/service.py#L226-L320
|
[
"def _available(name, ret):\n '''\n Check if the service is available\n '''\n avail = False\n if 'service.available' in __salt__:\n avail = __salt__['service.available'](name)\n elif 'service.get_all' in __salt__:\n avail = name in __salt__['service.get_all']()\n if not avail:\n ret['result'] = False\n ret['comment'] = 'The named service {0} is not available'.format(name)\n return avail\n"
] |
# -*- coding: utf-8 -*-
'''
Starting or restarting of services and daemons
==============================================
Services are defined as system daemons and are typically launched using system
init or rc scripts. This service state uses whichever service module is loaded
on the minion with the virtualname of ``service``. Services can be defined as
either running or dead.
If you need to know if your init system is supported, see the list of supported
:mod:`service modules <salt.modules.service.py>` for your desired init system
(systemd, sysvinit, launchctl, etc.).
Note that Salt's service execution module, and therefore this service state,
uses OS grains to ascertain which service module should be loaded and used to
execute service functions. As existing distributions change init systems or
new distributions are created, OS detection can sometimes be incomplete.
If your service states are running into trouble with init system detection,
please see the :ref:`Overriding Virtual Module Providers <module-provider-override>`
section of Salt's module documentation to work around possible errors.
.. note::
The current status of a service is determined by the return code of the init/rc
script status command. A status return code of 0 it is considered running. Any
other return code is considered dead.
.. code-block:: yaml
httpd:
service.running: []
The service can also be set to start at runtime via the enable option:
.. code-block:: yaml
openvpn:
service.running:
- enable: True
By default if a service is triggered to refresh due to a watch statement the
service is restarted. If the desired behavior is to reload the service, then
set the reload value to True:
.. code-block:: yaml
redis:
service.running:
- enable: True
- reload: True
- watch:
- pkg: redis
.. note::
More details regarding ``watch`` can be found in the
:ref:`Requisites <requisites>` documentation.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
# Import Salt libs
import salt.utils.data
import salt.utils.platform
from salt.utils.args import get_function_argspec as _argspec
from salt.exceptions import CommandExecutionError
from salt.state import _gen_tag
# Import 3rd-party libs
from salt.ext import six
SYSTEMD_ONLY = ('no_block', 'unmask', 'unmask_runtime')
__virtualname__ = 'service'
def __virtual__():
'''
Only make these states available if a service provider has been detected or
assigned for this minion
'''
if 'service.start' in __salt__:
return __virtualname__
else:
return (False, 'No service execution module loaded: '
'check support for service management on {0} '
''.format(__grains__.get('osfinger', __grains__['os']))
)
# Double-asterisk deliberately not used here
def _get_systemd_only(func, kwargs):
ret = {}
warnings = []
valid_args = _argspec(func).args
for systemd_arg in SYSTEMD_ONLY:
arg_val = kwargs.get(systemd_arg, False)
if arg_val:
if systemd_arg in valid_args:
ret[systemd_arg] = arg_val
else:
warnings.append(
'The \'{0}\' argument is not supported by this '
'platform/action'.format(systemd_arg)
)
return ret, warnings
def _enabled_used_error(ret):
'''
Warn of potential typo.
'''
ret['result'] = False
ret['comment'] = (
'Service {0} uses non-existent option "enabled". ' +
'Perhaps "enable" option was intended?'
).format(ret['name'])
return ret
def _enable(name, started, result=True, skip_verify=False, **kwargs):
'''
Enable the service
'''
ret = {}
if not skip_verify:
# is service available?
try:
if not _available(name, ret):
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# Set default expected result
ret['result'] = result
# Check to see if this minion supports enable
if 'service.enable' not in __salt__ or 'service.enabled' not in __salt__:
if started is True:
ret['comment'] = ('Enable is not available on this minion,'
' service {0} started').format(name)
elif started is None:
ret['comment'] = ('Enable is not available on this minion,'
' service {0} is in the desired state'
).format(name)
else:
ret['comment'] = ('Enable is not available on this minion,'
' service {0} is dead').format(name)
return ret
# Service can be enabled
before_toggle_enable_status = __salt__['service.enabled'](name, **kwargs)
if before_toggle_enable_status:
# Service is enabled
if started is True:
ret['comment'] = ('Service {0} is already enabled,'
' and is running').format(name)
elif started is None:
# always be sure in this case to reset the changes dict
ret['changes'] = {}
ret['comment'] = ('Service {0} is already enabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} is already enabled,'
' and is dead').format(name)
return ret
# Service needs to be enabled
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service {0} set to be enabled'.format(name)
return ret
try:
if __salt__['service.enable'](name, **kwargs):
# Service has been enabled
ret['changes'] = {}
after_toggle_enable_status = __salt__['service.enabled'](
name,
**kwargs)
# on upstart, certain services like apparmor will always return
# False, even if correctly activated
# do not trigger a change
if before_toggle_enable_status != after_toggle_enable_status:
ret['changes'][name] = True
if started is True:
ret['comment'] = ('Service {0} has been enabled,'
' and is running').format(name)
elif started is None:
ret['comment'] = ('Service {0} has been enabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} has been enabled,'
' and is dead').format(name)
return ret
except CommandExecutionError as exc:
enable_error = exc.strerror
else:
enable_error = False
# Service failed to be enabled
ret['result'] = False
if started is True:
ret['comment'] = ('Failed when setting service {0} to start at boot,'
' but the service is running').format(name)
elif started is None:
ret['comment'] = ('Failed when setting service {0} to start at boot,'
' but the service was already running').format(name)
else:
ret['comment'] = ('Failed when setting service {0} to start at boot,'
' and the service is dead').format(name)
if enable_error:
ret['comment'] += '. Additional information follows:\n\n{0}'.format(
enable_error
)
return ret
def _available(name, ret):
'''
Check if the service is available
'''
avail = False
if 'service.available' in __salt__:
avail = __salt__['service.available'](name)
elif 'service.get_all' in __salt__:
avail = name in __salt__['service.get_all']()
if not avail:
ret['result'] = False
ret['comment'] = 'The named service {0} is not available'.format(name)
return avail
def running(name,
enable=None,
sig=None,
init_delay=None,
no_block=False,
unmask=False,
unmask_runtime=False,
**kwargs):
'''
Ensure that the service is running
name
The name of the init or rc script used to manage the service
enable
Set the service to be enabled at boot time, ``True`` sets the service
to be enabled, ``False`` sets the named service to be disabled. The
default is ``None``, which does not enable or disable anything.
sig
The string to search for when looking for the service process with ps
init_delay
Some services may not be truly available for a short period after their
startup script indicates to the system that they are. Provide an
'init_delay' to specify that this state should wait an additional given
number of seconds after a service has started before returning. Useful
for requisite states wherein a dependent state might assume a service
has started but is not yet fully initialized.
no_block : False
**For systemd minions only.** Starts the service using ``--no-block``.
.. versionadded:: 2017.7.0
unmask : False
**For systemd minions only.** Set to ``True`` to remove an indefinite
mask before attempting to start the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
making any changes. This behavior is no longer the default.
unmask_runtime : False
**For systemd minions only.** Set to ``True`` to remove a runtime mask
before attempting to start the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
making any changes. This behavior is no longer the default.
.. note::
``watch`` can be used with service.running to restart a service when
another state changes ( example: a file.managed state that creates the
service's config file ). More details regarding ``watch`` can be found
in the :ref:`Requisites <requisites>` documentation.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
# Check for common error: using enabled option instead of enable
if 'enabled' in kwargs:
return _enabled_used_error(ret)
# Convert enable to boolean in case user passed a string value
if isinstance(enable, six.string_types):
enable = salt.utils.data.is_true(enable)
# Check if the service is available
try:
if not _available(name, ret):
if __opts__.get('test'):
ret['result'] = None
ret['comment'] = 'Service {0} not present; if created in this state run, it would have been started'.format(name)
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# lot of custom init script won't or mis implement the status
# command, so it is just an indicator but can not be fully trusted
before_toggle_status = __salt__['service.status'](name, sig)
if 'service.enabled' in __salt__:
before_toggle_enable_status = __salt__['service.enabled'](name)
else:
before_toggle_enable_status = True
unmask_ret = {'comment': ''}
if unmask:
unmask_ret = unmasked(name, unmask_runtime)
# See if the service is already running
if before_toggle_status:
ret['comment'] = '\n'.join(
[_f for _f in ['The service {0} is already running'.format(name),
unmask_ret['comment']] if _f]
)
if enable is True and not before_toggle_enable_status:
ret.update(_enable(name, None, skip_verify=False, **kwargs))
elif enable is False and before_toggle_enable_status:
ret.update(_disable(name, None, skip_verify=False, **kwargs))
return ret
# Run the tests
if __opts__['test']:
ret['result'] = None
ret['comment'] = '\n'.join(
[_f for _f in ['Service {0} is set to start'.format(name),
unmask_ret['comment']] if _f])
return ret
# Conditionally add systemd-specific args to call to service.start
start_kwargs, warnings = \
_get_systemd_only(__salt__['service.start'], locals())
if warnings:
ret.setdefault('warnings', []).extend(warnings)
if salt.utils.platform.is_windows():
for arg in ['timeout', 'with_deps', 'with_parents']:
if kwargs.get(arg, False):
start_kwargs.update({arg: kwargs.get(arg)})
try:
func_ret = __salt__['service.start'](name, **start_kwargs)
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
if not func_ret:
ret['result'] = False
ret['comment'] = 'Service {0} failed to start'.format(name)
if enable is True:
ret.update(_enable(name, False, result=False, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, False, result=False, skip_verify=False, **kwargs))
return ret
if init_delay:
time.sleep(init_delay)
# only force a change state if we have explicitly detected them
after_toggle_status = __salt__['service.status'](name, sig)
if 'service.enabled' in __salt__:
after_toggle_enable_status = __salt__['service.enabled'](name)
else:
after_toggle_enable_status = True
if (
(before_toggle_enable_status != after_toggle_enable_status) or
(before_toggle_status != after_toggle_status)
) and not ret.get('changes', {}):
ret['changes'][name] = after_toggle_status
if after_toggle_status:
ret['comment'] = 'Started Service {0}'.format(name)
else:
ret['comment'] = 'Service {0} failed to start'.format(name)
ret['result'] = False
if enable is True:
ret.update(_enable(name, after_toggle_status, result=after_toggle_status, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, after_toggle_status, result=after_toggle_status, skip_verify=False, **kwargs))
if init_delay:
ret['comment'] = (
'{0}\nDelayed return for {1} seconds'
.format(ret['comment'], init_delay)
)
if unmask:
ret['comment'] = '\n'.join([ret['comment'], unmask_ret['comment']])
return ret
def dead(name,
enable=None,
sig=None,
init_delay=None,
**kwargs):
'''
Ensure that the named service is dead by stopping the service if it is running
name
The name of the init or rc script used to manage the service
enable
Set the service to be enabled at boot time, ``True`` sets the service
to be enabled, ``False`` sets the named service to be disabled. The
default is ``None``, which does not enable or disable anything.
sig
The string to search for when looking for the service process with ps
init_delay
Add a sleep command (in seconds) before the check to make sure service
is killed.
.. versionadded:: 2017.7.0
no_block : False
**For systemd minions only.** Stops the service using ``--no-block``.
.. versionadded:: 2017.7.0
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
# Check for common error: using enabled option instead of enable
if 'enabled' in kwargs:
return _enabled_used_error(ret)
# Convert enable to boolean in case user passed a string value
if isinstance(enable, six.string_types):
enable = salt.utils.data.is_true(enable)
# Check if the service is available
try:
if not _available(name, ret):
if __opts__.get('test'):
ret['result'] = None
ret['comment'] = 'Service {0} not present; if created in this state run, it would have been stopped'.format(name)
else:
# A non-available service is OK here, don't let the state fail
# because of it.
ret['result'] = True
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# lot of custom init script won't or mis implement the status
# command, so it is just an indicator but can not be fully trusted
before_toggle_status = __salt__['service.status'](name, sig)
if 'service.enabled' in __salt__:
if salt.utils.platform.is_windows():
# service.enabled in Windows returns True for services that are set
# to Auto start, but services set to Manual can also be disabled
before_toggle_enable_status = __salt__['service.info'](name)['StartType'] in ['Auto', 'Manual']
else:
before_toggle_enable_status = __salt__['service.enabled'](name)
else:
before_toggle_enable_status = True
# See if the service is already dead
if not before_toggle_status:
ret['comment'] = 'The service {0} is already dead'.format(name)
if enable is True and not before_toggle_enable_status:
ret.update(_enable(name, None, skip_verify=False, **kwargs))
elif enable is False and before_toggle_enable_status:
ret.update(_disable(name, None, skip_verify=False, **kwargs))
return ret
# Run the tests
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service {0} is set to be killed'.format(name)
return ret
# Conditionally add systemd-specific args to call to service.start
stop_kwargs, warnings = _get_systemd_only(__salt__['service.stop'], kwargs)
if warnings:
ret.setdefault('warnings', []).extend(warnings)
if salt.utils.platform.is_windows():
for arg in ['timeout', 'with_deps', 'with_parents']:
if kwargs.get(arg, False):
stop_kwargs.update({arg: kwargs.get(arg)})
func_ret = __salt__['service.stop'](name, **stop_kwargs)
if not func_ret:
ret['result'] = False
ret['comment'] = 'Service {0} failed to die'.format(name)
if enable is True:
ret.update(_enable(name, True, result=False, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, True, result=False, skip_verify=False, **kwargs))
return ret
if init_delay:
time.sleep(init_delay)
# only force a change state if we have explicitly detected them
after_toggle_status = __salt__['service.status'](name)
if 'service.enabled' in __salt__:
after_toggle_enable_status = __salt__['service.enabled'](name)
else:
after_toggle_enable_status = True
if (
(before_toggle_enable_status != after_toggle_enable_status) or
(before_toggle_status != after_toggle_status)
) and not ret.get('changes', {}):
ret['changes'][name] = after_toggle_status
# be sure to stop, in case we mis detected in the check
if after_toggle_status:
ret['result'] = False
ret['comment'] = 'Service {0} failed to die'.format(name)
else:
ret['comment'] = 'Service {0} was killed'.format(name)
if enable is True:
ret.update(_enable(name, after_toggle_status, result=not after_toggle_status, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, after_toggle_status, result=not after_toggle_status, skip_verify=False, **kwargs))
return ret
def enabled(name,
skip_verify=False,
**kwargs):
'''
Ensure that the service is enabled on boot, only use this state if you
don't want to manage the running process, remember that if you want to
enable a running service to use the enable: True option for the running
or dead function.
name
The name of the init or rc script used to manage the service
skip_verify
Skip verifying that the service is available before enabling it.
``True`` will skip the verification. The default is ``False``,
which will ensure the service is available before enabling it.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
ret.update(_enable(name, None, skip_verify=skip_verify, **kwargs))
return ret
def disabled(name,
skip_verify=False,
**kwargs):
'''
Ensure that the service is disabled on boot, only use this state if you
don't want to manage the running process, remember that if you want to
disable a service to use the enable: False option for the running or dead
function.
name
The name of the init or rc script used to manage the service
skip_verify
Skip verifying that the service is available before disabling it.
``True`` will skip the verification. The default is ``False``,
which will ensure the service is available before disabling it.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
ret.update(_disable(name, None, skip_verify=skip_verify, **kwargs))
return ret
def masked(name, runtime=False):
'''
.. versionadded:: 2017.7.0
.. note::
This state is only available on minions which use systemd_.
Ensures that the named service is masked (i.e. prevented from being
started).
name
Name of the service to mask
runtime : False
By default, this state will manage an indefinite mask for the named
service. Set this argument to ``True`` to runtime mask the service.
.. note::
It is possible for a service to have both indefinite and runtime masks
set for it. Therefore, this state will manage a runtime or indefinite
mask independently of each other. This means that if the service is
already indefinitely masked, running this state with ``runtime`` set to
``True`` will _not_ remove the indefinite mask before setting a runtime
mask. In these cases, if it is desirable to ensure that the service is
runtime masked and not indefinitely masked, pair this state with a
:py:func:`service.unmasked <salt.states.service.unmasked>` state, like
so:
.. code-block:: yaml
mask_runtime_foo:
service.masked:
- name: foo
- runtime: True
unmask_indefinite_foo:
service.unmasked:
- name: foo
- runtime: False
.. _systemd: https://freedesktop.org/wiki/Software/systemd/
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if 'service.masked' not in __salt__:
ret['comment'] = 'Service masking not available on this minion'
ret['result'] = False
return ret
mask_type = 'runtime masked' if runtime else 'masked'
expected_changes = {mask_type: {'old': False, 'new': True}}
try:
if __salt__['service.masked'](name, runtime):
ret['comment'] = 'Service {0} is already {1}'.format(
name,
mask_type,
)
return ret
if __opts__['test']:
ret['result'] = None
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} would be {1}'.format(name, mask_type)
return ret
__salt__['service.mask'](name, runtime)
if __salt__['service.masked'](name, runtime):
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} was {1}'.format(name, mask_type)
else:
ret['comment'] = 'Failed to mask service {0}'.format(name)
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
def unmasked(name, runtime=False):
'''
.. versionadded:: 2017.7.0
.. note::
This state is only available on minions which use systemd_.
Ensures that the named service is unmasked
name
Name of the service to unmask
runtime : False
By default, this state will manage an indefinite mask for the named
service. Set this argument to ``True`` to ensure that the service is
runtime masked.
.. note::
It is possible for a service to have both indefinite and runtime masks
set for it. Therefore, this state will manage a runtime or indefinite
mask independently of each other. This means that if the service is
indefinitely masked, running this state with ``runtime`` set to
``True`` will _not_ remove the indefinite mask.
.. _systemd: https://freedesktop.org/wiki/Software/systemd/
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if 'service.masked' not in __salt__:
ret['comment'] = 'Service masking not available on this minion'
ret['result'] = False
return ret
mask_type = 'runtime masked' if runtime else 'masked'
action = 'runtime unmasked' if runtime else 'unmasked'
expected_changes = {mask_type: {'old': True, 'new': False}}
try:
if not __salt__['service.masked'](name, runtime):
ret['comment'] = 'Service {0} was already {1}'.format(name, action)
return ret
if __opts__['test']:
ret['result'] = None
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} would be {1}'.format(name, action)
return ret
__salt__['service.unmask'](name, runtime)
if not __salt__['service.masked'](name, runtime):
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} was {1}'.format(name, action)
else:
ret['comment'] = 'Failed to unmask service {0}'.format(name)
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
def mod_watch(name,
sfun=None,
sig=None,
full_restart=False,
init_delay=None,
force=False,
**kwargs):
'''
The service watcher, called to invoke the watch command.
When called, it will restart or reload the named service.
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the watching service.
(i.e. ``service.running``)
name
The name of the init or rc script used to manage the service
sfun
The original function which triggered the mod_watch call
(`service.running`, for example).
sig
The string to search for when looking for the service process with ps
reload
If True use reload instead of the default restart. If value is a list of
requisites; reload only if all watched changes are contained in the reload list.
Otherwise watch will restart.
full_restart
Use service.full_restart instead of restart.
When set, reload the service instead of restarting it.
(i.e. ``service nginx reload``)
full_restart
Perform a full stop/start of a service by passing ``--full-restart``.
This option is ignored if ``reload`` is set and is supported by only a few
:py:func:`service modules <salt.modules.service>`.
force
Use service.force_reload instead of reload (needs reload to be set to True)
init_delay
Add a sleep command (in seconds) before the service is restarted/reloaded
'''
reload_ = kwargs.pop('reload', False)
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
past_participle = None
if sfun == 'dead':
verb = 'stop'
past_participle = verb + 'ped'
if __salt__['service.status'](name, sig):
func = __salt__['service.stop']
else:
ret['result'] = True
ret['comment'] = 'Service is already {0}'.format(past_participle)
return ret
elif sfun == 'running':
if __salt__['service.status'](name, sig):
if 'service.reload' in __salt__ and reload_:
if isinstance(reload_, list):
only_reload_needed = True
for watch_item in kwargs['__reqs__']['watch']:
if __running__[_gen_tag(watch_item)]['changes']:
match_found = False
for this_reload in reload_:
for state, id_ in six.iteritems(this_reload):
if state == watch_item['state'] \
and id_ == watch_item['__id__']:
match_found = True
if not match_found:
only_reload_needed = False
if only_reload_needed:
if 'service.force_reload' in __salt__ and force:
func = __salt__['service.force_reload']
verb = 'forcefully reload'
else:
func = __salt__['service.reload']
verb = 'reload'
else:
if 'service.full_restart' in __salt__ and full_restart:
func = __salt__['service.full_restart']
verb = 'fully restart'
else:
func = __salt__['service.restart']
verb = 'restart'
else:
if 'service.force_reload' in __salt__ and force:
func = __salt__['service.force_reload']
verb = 'forcefully reload'
else:
func = __salt__['service.reload']
verb = 'reload'
elif 'service.full_restart' in __salt__ and full_restart:
func = __salt__['service.full_restart']
verb = 'fully restart'
else:
func = __salt__['service.restart']
verb = 'restart'
else:
func = __salt__['service.start']
verb = 'start'
if not past_participle:
past_participle = verb + 'ed'
else:
ret['comment'] = 'Unable to trigger watch for service.{0}'.format(sfun)
ret['result'] = False
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service is set to be {0}'.format(past_participle)
return ret
if verb == 'start' and 'service.stop' in __salt__:
# stop service before start
__salt__['service.stop'](name)
func_kwargs, warnings = _get_systemd_only(func, kwargs)
if warnings:
ret.setdefault('warnings', []).extend(warnings)
try:
result = func(name, **func_kwargs)
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
if init_delay:
time.sleep(init_delay)
ret['changes'] = {name: result}
ret['result'] = result
ret['comment'] = 'Service {0}'.format(past_participle) if result else \
'Failed to {0} the service'.format(verb)
return ret
|
saltstack/salt
|
salt/states/service.py
|
_available
|
python
|
def _available(name, ret):
'''
Check if the service is available
'''
avail = False
if 'service.available' in __salt__:
avail = __salt__['service.available'](name)
elif 'service.get_all' in __salt__:
avail = name in __salt__['service.get_all']()
if not avail:
ret['result'] = False
ret['comment'] = 'The named service {0} is not available'.format(name)
return avail
|
Check if the service is available
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/service.py#L323-L335
| null |
# -*- coding: utf-8 -*-
'''
Starting or restarting of services and daemons
==============================================
Services are defined as system daemons and are typically launched using system
init or rc scripts. This service state uses whichever service module is loaded
on the minion with the virtualname of ``service``. Services can be defined as
either running or dead.
If you need to know if your init system is supported, see the list of supported
:mod:`service modules <salt.modules.service.py>` for your desired init system
(systemd, sysvinit, launchctl, etc.).
Note that Salt's service execution module, and therefore this service state,
uses OS grains to ascertain which service module should be loaded and used to
execute service functions. As existing distributions change init systems or
new distributions are created, OS detection can sometimes be incomplete.
If your service states are running into trouble with init system detection,
please see the :ref:`Overriding Virtual Module Providers <module-provider-override>`
section of Salt's module documentation to work around possible errors.
.. note::
The current status of a service is determined by the return code of the init/rc
script status command. A status return code of 0 it is considered running. Any
other return code is considered dead.
.. code-block:: yaml
httpd:
service.running: []
The service can also be set to start at runtime via the enable option:
.. code-block:: yaml
openvpn:
service.running:
- enable: True
By default if a service is triggered to refresh due to a watch statement the
service is restarted. If the desired behavior is to reload the service, then
set the reload value to True:
.. code-block:: yaml
redis:
service.running:
- enable: True
- reload: True
- watch:
- pkg: redis
.. note::
More details regarding ``watch`` can be found in the
:ref:`Requisites <requisites>` documentation.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
# Import Salt libs
import salt.utils.data
import salt.utils.platform
from salt.utils.args import get_function_argspec as _argspec
from salt.exceptions import CommandExecutionError
from salt.state import _gen_tag
# Import 3rd-party libs
from salt.ext import six
SYSTEMD_ONLY = ('no_block', 'unmask', 'unmask_runtime')
__virtualname__ = 'service'
def __virtual__():
'''
Only make these states available if a service provider has been detected or
assigned for this minion
'''
if 'service.start' in __salt__:
return __virtualname__
else:
return (False, 'No service execution module loaded: '
'check support for service management on {0} '
''.format(__grains__.get('osfinger', __grains__['os']))
)
# Double-asterisk deliberately not used here
def _get_systemd_only(func, kwargs):
ret = {}
warnings = []
valid_args = _argspec(func).args
for systemd_arg in SYSTEMD_ONLY:
arg_val = kwargs.get(systemd_arg, False)
if arg_val:
if systemd_arg in valid_args:
ret[systemd_arg] = arg_val
else:
warnings.append(
'The \'{0}\' argument is not supported by this '
'platform/action'.format(systemd_arg)
)
return ret, warnings
def _enabled_used_error(ret):
'''
Warn of potential typo.
'''
ret['result'] = False
ret['comment'] = (
'Service {0} uses non-existent option "enabled". ' +
'Perhaps "enable" option was intended?'
).format(ret['name'])
return ret
def _enable(name, started, result=True, skip_verify=False, **kwargs):
'''
Enable the service
'''
ret = {}
if not skip_verify:
# is service available?
try:
if not _available(name, ret):
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# Set default expected result
ret['result'] = result
# Check to see if this minion supports enable
if 'service.enable' not in __salt__ or 'service.enabled' not in __salt__:
if started is True:
ret['comment'] = ('Enable is not available on this minion,'
' service {0} started').format(name)
elif started is None:
ret['comment'] = ('Enable is not available on this minion,'
' service {0} is in the desired state'
).format(name)
else:
ret['comment'] = ('Enable is not available on this minion,'
' service {0} is dead').format(name)
return ret
# Service can be enabled
before_toggle_enable_status = __salt__['service.enabled'](name, **kwargs)
if before_toggle_enable_status:
# Service is enabled
if started is True:
ret['comment'] = ('Service {0} is already enabled,'
' and is running').format(name)
elif started is None:
# always be sure in this case to reset the changes dict
ret['changes'] = {}
ret['comment'] = ('Service {0} is already enabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} is already enabled,'
' and is dead').format(name)
return ret
# Service needs to be enabled
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service {0} set to be enabled'.format(name)
return ret
try:
if __salt__['service.enable'](name, **kwargs):
# Service has been enabled
ret['changes'] = {}
after_toggle_enable_status = __salt__['service.enabled'](
name,
**kwargs)
# on upstart, certain services like apparmor will always return
# False, even if correctly activated
# do not trigger a change
if before_toggle_enable_status != after_toggle_enable_status:
ret['changes'][name] = True
if started is True:
ret['comment'] = ('Service {0} has been enabled,'
' and is running').format(name)
elif started is None:
ret['comment'] = ('Service {0} has been enabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} has been enabled,'
' and is dead').format(name)
return ret
except CommandExecutionError as exc:
enable_error = exc.strerror
else:
enable_error = False
# Service failed to be enabled
ret['result'] = False
if started is True:
ret['comment'] = ('Failed when setting service {0} to start at boot,'
' but the service is running').format(name)
elif started is None:
ret['comment'] = ('Failed when setting service {0} to start at boot,'
' but the service was already running').format(name)
else:
ret['comment'] = ('Failed when setting service {0} to start at boot,'
' and the service is dead').format(name)
if enable_error:
ret['comment'] += '. Additional information follows:\n\n{0}'.format(
enable_error
)
return ret
def _disable(name, started, result=True, skip_verify=False, **kwargs):
'''
Disable the service
'''
ret = {}
if not skip_verify:
# is service available?
try:
if not _available(name, ret):
ret['result'] = True
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# Set default expected result
ret['result'] = result
# is enable/disable available?
if 'service.disable' not in __salt__ or 'service.disabled' not in __salt__:
if started is True:
ret['comment'] = ('Disable is not available on this minion,'
' service {0} started').format(name)
elif started is None:
ret['comment'] = ('Disable is not available on this minion,'
' service {0} is in the desired state'
).format(name)
else:
ret['comment'] = ('Disable is not available on this minion,'
' service {0} is dead').format(name)
return ret
# Service can be disabled
if salt.utils.platform.is_windows():
# service.disabled in Windows returns True for services that are set to
# Manual start, so we need to check specifically for Disabled
before_toggle_disable_status = __salt__['service.info'](name)['StartType'] in ['Disabled']
else:
before_toggle_disable_status = __salt__['service.disabled'](name)
if before_toggle_disable_status:
# Service is disabled
if started is True:
ret['comment'] = ('Service {0} is already disabled,'
' and is running').format(name)
elif started is None:
# always be sure in this case to reset the changes dict
ret['changes'] = {}
ret['comment'] = ('Service {0} is already disabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} is already disabled,'
' and is dead').format(name)
return ret
# Service needs to be disabled
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service {0} set to be disabled'.format(name)
return ret
if __salt__['service.disable'](name, **kwargs):
# Service has been disabled
ret['changes'] = {}
after_toggle_disable_status = __salt__['service.disabled'](name)
# on upstart, certain services like apparmor will always return
# False, even if correctly activated
# do not trigger a change
if before_toggle_disable_status != after_toggle_disable_status:
ret['changes'][name] = True
if started is True:
ret['comment'] = ('Service {0} has been disabled,'
' and is running').format(name)
elif started is None:
ret['comment'] = ('Service {0} has been disabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} has been disabled,'
' and is dead').format(name)
return ret
# Service failed to be disabled
ret['result'] = False
if started is True:
ret['comment'] = ('Failed when setting service {0} to not start'
' at boot, and is running').format(name)
elif started is None:
ret['comment'] = ('Failed when setting service {0} to not start'
' at boot, but the service was already running'
).format(name)
else:
ret['comment'] = ('Failed when setting service {0} to not start'
' at boot, and the service is dead').format(name)
return ret
def running(name,
enable=None,
sig=None,
init_delay=None,
no_block=False,
unmask=False,
unmask_runtime=False,
**kwargs):
'''
Ensure that the service is running
name
The name of the init or rc script used to manage the service
enable
Set the service to be enabled at boot time, ``True`` sets the service
to be enabled, ``False`` sets the named service to be disabled. The
default is ``None``, which does not enable or disable anything.
sig
The string to search for when looking for the service process with ps
init_delay
Some services may not be truly available for a short period after their
startup script indicates to the system that they are. Provide an
'init_delay' to specify that this state should wait an additional given
number of seconds after a service has started before returning. Useful
for requisite states wherein a dependent state might assume a service
has started but is not yet fully initialized.
no_block : False
**For systemd minions only.** Starts the service using ``--no-block``.
.. versionadded:: 2017.7.0
unmask : False
**For systemd minions only.** Set to ``True`` to remove an indefinite
mask before attempting to start the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
making any changes. This behavior is no longer the default.
unmask_runtime : False
**For systemd minions only.** Set to ``True`` to remove a runtime mask
before attempting to start the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
making any changes. This behavior is no longer the default.
.. note::
``watch`` can be used with service.running to restart a service when
another state changes ( example: a file.managed state that creates the
service's config file ). More details regarding ``watch`` can be found
in the :ref:`Requisites <requisites>` documentation.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
# Check for common error: using enabled option instead of enable
if 'enabled' in kwargs:
return _enabled_used_error(ret)
# Convert enable to boolean in case user passed a string value
if isinstance(enable, six.string_types):
enable = salt.utils.data.is_true(enable)
# Check if the service is available
try:
if not _available(name, ret):
if __opts__.get('test'):
ret['result'] = None
ret['comment'] = 'Service {0} not present; if created in this state run, it would have been started'.format(name)
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# lot of custom init script won't or mis implement the status
# command, so it is just an indicator but can not be fully trusted
before_toggle_status = __salt__['service.status'](name, sig)
if 'service.enabled' in __salt__:
before_toggle_enable_status = __salt__['service.enabled'](name)
else:
before_toggle_enable_status = True
unmask_ret = {'comment': ''}
if unmask:
unmask_ret = unmasked(name, unmask_runtime)
# See if the service is already running
if before_toggle_status:
ret['comment'] = '\n'.join(
[_f for _f in ['The service {0} is already running'.format(name),
unmask_ret['comment']] if _f]
)
if enable is True and not before_toggle_enable_status:
ret.update(_enable(name, None, skip_verify=False, **kwargs))
elif enable is False and before_toggle_enable_status:
ret.update(_disable(name, None, skip_verify=False, **kwargs))
return ret
# Run the tests
if __opts__['test']:
ret['result'] = None
ret['comment'] = '\n'.join(
[_f for _f in ['Service {0} is set to start'.format(name),
unmask_ret['comment']] if _f])
return ret
# Conditionally add systemd-specific args to call to service.start
start_kwargs, warnings = \
_get_systemd_only(__salt__['service.start'], locals())
if warnings:
ret.setdefault('warnings', []).extend(warnings)
if salt.utils.platform.is_windows():
for arg in ['timeout', 'with_deps', 'with_parents']:
if kwargs.get(arg, False):
start_kwargs.update({arg: kwargs.get(arg)})
try:
func_ret = __salt__['service.start'](name, **start_kwargs)
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
if not func_ret:
ret['result'] = False
ret['comment'] = 'Service {0} failed to start'.format(name)
if enable is True:
ret.update(_enable(name, False, result=False, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, False, result=False, skip_verify=False, **kwargs))
return ret
if init_delay:
time.sleep(init_delay)
# only force a change state if we have explicitly detected them
after_toggle_status = __salt__['service.status'](name, sig)
if 'service.enabled' in __salt__:
after_toggle_enable_status = __salt__['service.enabled'](name)
else:
after_toggle_enable_status = True
if (
(before_toggle_enable_status != after_toggle_enable_status) or
(before_toggle_status != after_toggle_status)
) and not ret.get('changes', {}):
ret['changes'][name] = after_toggle_status
if after_toggle_status:
ret['comment'] = 'Started Service {0}'.format(name)
else:
ret['comment'] = 'Service {0} failed to start'.format(name)
ret['result'] = False
if enable is True:
ret.update(_enable(name, after_toggle_status, result=after_toggle_status, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, after_toggle_status, result=after_toggle_status, skip_verify=False, **kwargs))
if init_delay:
ret['comment'] = (
'{0}\nDelayed return for {1} seconds'
.format(ret['comment'], init_delay)
)
if unmask:
ret['comment'] = '\n'.join([ret['comment'], unmask_ret['comment']])
return ret
def dead(name,
enable=None,
sig=None,
init_delay=None,
**kwargs):
'''
Ensure that the named service is dead by stopping the service if it is running
name
The name of the init or rc script used to manage the service
enable
Set the service to be enabled at boot time, ``True`` sets the service
to be enabled, ``False`` sets the named service to be disabled. The
default is ``None``, which does not enable or disable anything.
sig
The string to search for when looking for the service process with ps
init_delay
Add a sleep command (in seconds) before the check to make sure service
is killed.
.. versionadded:: 2017.7.0
no_block : False
**For systemd minions only.** Stops the service using ``--no-block``.
.. versionadded:: 2017.7.0
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
# Check for common error: using enabled option instead of enable
if 'enabled' in kwargs:
return _enabled_used_error(ret)
# Convert enable to boolean in case user passed a string value
if isinstance(enable, six.string_types):
enable = salt.utils.data.is_true(enable)
# Check if the service is available
try:
if not _available(name, ret):
if __opts__.get('test'):
ret['result'] = None
ret['comment'] = 'Service {0} not present; if created in this state run, it would have been stopped'.format(name)
else:
# A non-available service is OK here, don't let the state fail
# because of it.
ret['result'] = True
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# lot of custom init script won't or mis implement the status
# command, so it is just an indicator but can not be fully trusted
before_toggle_status = __salt__['service.status'](name, sig)
if 'service.enabled' in __salt__:
if salt.utils.platform.is_windows():
# service.enabled in Windows returns True for services that are set
# to Auto start, but services set to Manual can also be disabled
before_toggle_enable_status = __salt__['service.info'](name)['StartType'] in ['Auto', 'Manual']
else:
before_toggle_enable_status = __salt__['service.enabled'](name)
else:
before_toggle_enable_status = True
# See if the service is already dead
if not before_toggle_status:
ret['comment'] = 'The service {0} is already dead'.format(name)
if enable is True and not before_toggle_enable_status:
ret.update(_enable(name, None, skip_verify=False, **kwargs))
elif enable is False and before_toggle_enable_status:
ret.update(_disable(name, None, skip_verify=False, **kwargs))
return ret
# Run the tests
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service {0} is set to be killed'.format(name)
return ret
# Conditionally add systemd-specific args to call to service.start
stop_kwargs, warnings = _get_systemd_only(__salt__['service.stop'], kwargs)
if warnings:
ret.setdefault('warnings', []).extend(warnings)
if salt.utils.platform.is_windows():
for arg in ['timeout', 'with_deps', 'with_parents']:
if kwargs.get(arg, False):
stop_kwargs.update({arg: kwargs.get(arg)})
func_ret = __salt__['service.stop'](name, **stop_kwargs)
if not func_ret:
ret['result'] = False
ret['comment'] = 'Service {0} failed to die'.format(name)
if enable is True:
ret.update(_enable(name, True, result=False, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, True, result=False, skip_verify=False, **kwargs))
return ret
if init_delay:
time.sleep(init_delay)
# only force a change state if we have explicitly detected them
after_toggle_status = __salt__['service.status'](name)
if 'service.enabled' in __salt__:
after_toggle_enable_status = __salt__['service.enabled'](name)
else:
after_toggle_enable_status = True
if (
(before_toggle_enable_status != after_toggle_enable_status) or
(before_toggle_status != after_toggle_status)
) and not ret.get('changes', {}):
ret['changes'][name] = after_toggle_status
# be sure to stop, in case we mis detected in the check
if after_toggle_status:
ret['result'] = False
ret['comment'] = 'Service {0} failed to die'.format(name)
else:
ret['comment'] = 'Service {0} was killed'.format(name)
if enable is True:
ret.update(_enable(name, after_toggle_status, result=not after_toggle_status, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, after_toggle_status, result=not after_toggle_status, skip_verify=False, **kwargs))
return ret
def enabled(name,
skip_verify=False,
**kwargs):
'''
Ensure that the service is enabled on boot, only use this state if you
don't want to manage the running process, remember that if you want to
enable a running service to use the enable: True option for the running
or dead function.
name
The name of the init or rc script used to manage the service
skip_verify
Skip verifying that the service is available before enabling it.
``True`` will skip the verification. The default is ``False``,
which will ensure the service is available before enabling it.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
ret.update(_enable(name, None, skip_verify=skip_verify, **kwargs))
return ret
def disabled(name,
skip_verify=False,
**kwargs):
'''
Ensure that the service is disabled on boot, only use this state if you
don't want to manage the running process, remember that if you want to
disable a service to use the enable: False option for the running or dead
function.
name
The name of the init or rc script used to manage the service
skip_verify
Skip verifying that the service is available before disabling it.
``True`` will skip the verification. The default is ``False``,
which will ensure the service is available before disabling it.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
ret.update(_disable(name, None, skip_verify=skip_verify, **kwargs))
return ret
def masked(name, runtime=False):
'''
.. versionadded:: 2017.7.0
.. note::
This state is only available on minions which use systemd_.
Ensures that the named service is masked (i.e. prevented from being
started).
name
Name of the service to mask
runtime : False
By default, this state will manage an indefinite mask for the named
service. Set this argument to ``True`` to runtime mask the service.
.. note::
It is possible for a service to have both indefinite and runtime masks
set for it. Therefore, this state will manage a runtime or indefinite
mask independently of each other. This means that if the service is
already indefinitely masked, running this state with ``runtime`` set to
``True`` will _not_ remove the indefinite mask before setting a runtime
mask. In these cases, if it is desirable to ensure that the service is
runtime masked and not indefinitely masked, pair this state with a
:py:func:`service.unmasked <salt.states.service.unmasked>` state, like
so:
.. code-block:: yaml
mask_runtime_foo:
service.masked:
- name: foo
- runtime: True
unmask_indefinite_foo:
service.unmasked:
- name: foo
- runtime: False
.. _systemd: https://freedesktop.org/wiki/Software/systemd/
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if 'service.masked' not in __salt__:
ret['comment'] = 'Service masking not available on this minion'
ret['result'] = False
return ret
mask_type = 'runtime masked' if runtime else 'masked'
expected_changes = {mask_type: {'old': False, 'new': True}}
try:
if __salt__['service.masked'](name, runtime):
ret['comment'] = 'Service {0} is already {1}'.format(
name,
mask_type,
)
return ret
if __opts__['test']:
ret['result'] = None
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} would be {1}'.format(name, mask_type)
return ret
__salt__['service.mask'](name, runtime)
if __salt__['service.masked'](name, runtime):
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} was {1}'.format(name, mask_type)
else:
ret['comment'] = 'Failed to mask service {0}'.format(name)
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
def unmasked(name, runtime=False):
'''
.. versionadded:: 2017.7.0
.. note::
This state is only available on minions which use systemd_.
Ensures that the named service is unmasked
name
Name of the service to unmask
runtime : False
By default, this state will manage an indefinite mask for the named
service. Set this argument to ``True`` to ensure that the service is
runtime masked.
.. note::
It is possible for a service to have both indefinite and runtime masks
set for it. Therefore, this state will manage a runtime or indefinite
mask independently of each other. This means that if the service is
indefinitely masked, running this state with ``runtime`` set to
``True`` will _not_ remove the indefinite mask.
.. _systemd: https://freedesktop.org/wiki/Software/systemd/
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if 'service.masked' not in __salt__:
ret['comment'] = 'Service masking not available on this minion'
ret['result'] = False
return ret
mask_type = 'runtime masked' if runtime else 'masked'
action = 'runtime unmasked' if runtime else 'unmasked'
expected_changes = {mask_type: {'old': True, 'new': False}}
try:
if not __salt__['service.masked'](name, runtime):
ret['comment'] = 'Service {0} was already {1}'.format(name, action)
return ret
if __opts__['test']:
ret['result'] = None
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} would be {1}'.format(name, action)
return ret
__salt__['service.unmask'](name, runtime)
if not __salt__['service.masked'](name, runtime):
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} was {1}'.format(name, action)
else:
ret['comment'] = 'Failed to unmask service {0}'.format(name)
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
def mod_watch(name,
sfun=None,
sig=None,
full_restart=False,
init_delay=None,
force=False,
**kwargs):
'''
The service watcher, called to invoke the watch command.
When called, it will restart or reload the named service.
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the watching service.
(i.e. ``service.running``)
name
The name of the init or rc script used to manage the service
sfun
The original function which triggered the mod_watch call
(`service.running`, for example).
sig
The string to search for when looking for the service process with ps
reload
If True use reload instead of the default restart. If value is a list of
requisites; reload only if all watched changes are contained in the reload list.
Otherwise watch will restart.
full_restart
Use service.full_restart instead of restart.
When set, reload the service instead of restarting it.
(i.e. ``service nginx reload``)
full_restart
Perform a full stop/start of a service by passing ``--full-restart``.
This option is ignored if ``reload`` is set and is supported by only a few
:py:func:`service modules <salt.modules.service>`.
force
Use service.force_reload instead of reload (needs reload to be set to True)
init_delay
Add a sleep command (in seconds) before the service is restarted/reloaded
'''
reload_ = kwargs.pop('reload', False)
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
past_participle = None
if sfun == 'dead':
verb = 'stop'
past_participle = verb + 'ped'
if __salt__['service.status'](name, sig):
func = __salt__['service.stop']
else:
ret['result'] = True
ret['comment'] = 'Service is already {0}'.format(past_participle)
return ret
elif sfun == 'running':
if __salt__['service.status'](name, sig):
if 'service.reload' in __salt__ and reload_:
if isinstance(reload_, list):
only_reload_needed = True
for watch_item in kwargs['__reqs__']['watch']:
if __running__[_gen_tag(watch_item)]['changes']:
match_found = False
for this_reload in reload_:
for state, id_ in six.iteritems(this_reload):
if state == watch_item['state'] \
and id_ == watch_item['__id__']:
match_found = True
if not match_found:
only_reload_needed = False
if only_reload_needed:
if 'service.force_reload' in __salt__ and force:
func = __salt__['service.force_reload']
verb = 'forcefully reload'
else:
func = __salt__['service.reload']
verb = 'reload'
else:
if 'service.full_restart' in __salt__ and full_restart:
func = __salt__['service.full_restart']
verb = 'fully restart'
else:
func = __salt__['service.restart']
verb = 'restart'
else:
if 'service.force_reload' in __salt__ and force:
func = __salt__['service.force_reload']
verb = 'forcefully reload'
else:
func = __salt__['service.reload']
verb = 'reload'
elif 'service.full_restart' in __salt__ and full_restart:
func = __salt__['service.full_restart']
verb = 'fully restart'
else:
func = __salt__['service.restart']
verb = 'restart'
else:
func = __salt__['service.start']
verb = 'start'
if not past_participle:
past_participle = verb + 'ed'
else:
ret['comment'] = 'Unable to trigger watch for service.{0}'.format(sfun)
ret['result'] = False
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service is set to be {0}'.format(past_participle)
return ret
if verb == 'start' and 'service.stop' in __salt__:
# stop service before start
__salt__['service.stop'](name)
func_kwargs, warnings = _get_systemd_only(func, kwargs)
if warnings:
ret.setdefault('warnings', []).extend(warnings)
try:
result = func(name, **func_kwargs)
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
if init_delay:
time.sleep(init_delay)
ret['changes'] = {name: result}
ret['result'] = result
ret['comment'] = 'Service {0}'.format(past_participle) if result else \
'Failed to {0} the service'.format(verb)
return ret
|
saltstack/salt
|
salt/states/service.py
|
running
|
python
|
def running(name,
enable=None,
sig=None,
init_delay=None,
no_block=False,
unmask=False,
unmask_runtime=False,
**kwargs):
'''
Ensure that the service is running
name
The name of the init or rc script used to manage the service
enable
Set the service to be enabled at boot time, ``True`` sets the service
to be enabled, ``False`` sets the named service to be disabled. The
default is ``None``, which does not enable or disable anything.
sig
The string to search for when looking for the service process with ps
init_delay
Some services may not be truly available for a short period after their
startup script indicates to the system that they are. Provide an
'init_delay' to specify that this state should wait an additional given
number of seconds after a service has started before returning. Useful
for requisite states wherein a dependent state might assume a service
has started but is not yet fully initialized.
no_block : False
**For systemd minions only.** Starts the service using ``--no-block``.
.. versionadded:: 2017.7.0
unmask : False
**For systemd minions only.** Set to ``True`` to remove an indefinite
mask before attempting to start the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
making any changes. This behavior is no longer the default.
unmask_runtime : False
**For systemd minions only.** Set to ``True`` to remove a runtime mask
before attempting to start the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
making any changes. This behavior is no longer the default.
.. note::
``watch`` can be used with service.running to restart a service when
another state changes ( example: a file.managed state that creates the
service's config file ). More details regarding ``watch`` can be found
in the :ref:`Requisites <requisites>` documentation.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
# Check for common error: using enabled option instead of enable
if 'enabled' in kwargs:
return _enabled_used_error(ret)
# Convert enable to boolean in case user passed a string value
if isinstance(enable, six.string_types):
enable = salt.utils.data.is_true(enable)
# Check if the service is available
try:
if not _available(name, ret):
if __opts__.get('test'):
ret['result'] = None
ret['comment'] = 'Service {0} not present; if created in this state run, it would have been started'.format(name)
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# lot of custom init script won't or mis implement the status
# command, so it is just an indicator but can not be fully trusted
before_toggle_status = __salt__['service.status'](name, sig)
if 'service.enabled' in __salt__:
before_toggle_enable_status = __salt__['service.enabled'](name)
else:
before_toggle_enable_status = True
unmask_ret = {'comment': ''}
if unmask:
unmask_ret = unmasked(name, unmask_runtime)
# See if the service is already running
if before_toggle_status:
ret['comment'] = '\n'.join(
[_f for _f in ['The service {0} is already running'.format(name),
unmask_ret['comment']] if _f]
)
if enable is True and not before_toggle_enable_status:
ret.update(_enable(name, None, skip_verify=False, **kwargs))
elif enable is False and before_toggle_enable_status:
ret.update(_disable(name, None, skip_verify=False, **kwargs))
return ret
# Run the tests
if __opts__['test']:
ret['result'] = None
ret['comment'] = '\n'.join(
[_f for _f in ['Service {0} is set to start'.format(name),
unmask_ret['comment']] if _f])
return ret
# Conditionally add systemd-specific args to call to service.start
start_kwargs, warnings = \
_get_systemd_only(__salt__['service.start'], locals())
if warnings:
ret.setdefault('warnings', []).extend(warnings)
if salt.utils.platform.is_windows():
for arg in ['timeout', 'with_deps', 'with_parents']:
if kwargs.get(arg, False):
start_kwargs.update({arg: kwargs.get(arg)})
try:
func_ret = __salt__['service.start'](name, **start_kwargs)
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
if not func_ret:
ret['result'] = False
ret['comment'] = 'Service {0} failed to start'.format(name)
if enable is True:
ret.update(_enable(name, False, result=False, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, False, result=False, skip_verify=False, **kwargs))
return ret
if init_delay:
time.sleep(init_delay)
# only force a change state if we have explicitly detected them
after_toggle_status = __salt__['service.status'](name, sig)
if 'service.enabled' in __salt__:
after_toggle_enable_status = __salt__['service.enabled'](name)
else:
after_toggle_enable_status = True
if (
(before_toggle_enable_status != after_toggle_enable_status) or
(before_toggle_status != after_toggle_status)
) and not ret.get('changes', {}):
ret['changes'][name] = after_toggle_status
if after_toggle_status:
ret['comment'] = 'Started Service {0}'.format(name)
else:
ret['comment'] = 'Service {0} failed to start'.format(name)
ret['result'] = False
if enable is True:
ret.update(_enable(name, after_toggle_status, result=after_toggle_status, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, after_toggle_status, result=after_toggle_status, skip_verify=False, **kwargs))
if init_delay:
ret['comment'] = (
'{0}\nDelayed return for {1} seconds'
.format(ret['comment'], init_delay)
)
if unmask:
ret['comment'] = '\n'.join([ret['comment'], unmask_ret['comment']])
return ret
|
Ensure that the service is running
name
The name of the init or rc script used to manage the service
enable
Set the service to be enabled at boot time, ``True`` sets the service
to be enabled, ``False`` sets the named service to be disabled. The
default is ``None``, which does not enable or disable anything.
sig
The string to search for when looking for the service process with ps
init_delay
Some services may not be truly available for a short period after their
startup script indicates to the system that they are. Provide an
'init_delay' to specify that this state should wait an additional given
number of seconds after a service has started before returning. Useful
for requisite states wherein a dependent state might assume a service
has started but is not yet fully initialized.
no_block : False
**For systemd minions only.** Starts the service using ``--no-block``.
.. versionadded:: 2017.7.0
unmask : False
**For systemd minions only.** Set to ``True`` to remove an indefinite
mask before attempting to start the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
making any changes. This behavior is no longer the default.
unmask_runtime : False
**For systemd minions only.** Set to ``True`` to remove a runtime mask
before attempting to start the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
making any changes. This behavior is no longer the default.
.. note::
``watch`` can be used with service.running to restart a service when
another state changes ( example: a file.managed state that creates the
service's config file ). More details regarding ``watch`` can be found
in the :ref:`Requisites <requisites>` documentation.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/service.py#L338-L514
|
[
"def _disable(name, started, result=True, skip_verify=False, **kwargs):\n '''\n Disable the service\n '''\n ret = {}\n\n if not skip_verify:\n # is service available?\n try:\n if not _available(name, ret):\n ret['result'] = True\n return ret\n except CommandExecutionError as exc:\n ret['result'] = False\n ret['comment'] = exc.strerror\n return ret\n\n # Set default expected result\n ret['result'] = result\n\n # is enable/disable available?\n if 'service.disable' not in __salt__ or 'service.disabled' not in __salt__:\n if started is True:\n ret['comment'] = ('Disable is not available on this minion,'\n ' service {0} started').format(name)\n elif started is None:\n ret['comment'] = ('Disable is not available on this minion,'\n ' service {0} is in the desired state'\n ).format(name)\n else:\n ret['comment'] = ('Disable is not available on this minion,'\n ' service {0} is dead').format(name)\n return ret\n\n # Service can be disabled\n if salt.utils.platform.is_windows():\n # service.disabled in Windows returns True for services that are set to\n # Manual start, so we need to check specifically for Disabled\n before_toggle_disable_status = __salt__['service.info'](name)['StartType'] in ['Disabled']\n else:\n before_toggle_disable_status = __salt__['service.disabled'](name)\n if before_toggle_disable_status:\n # Service is disabled\n if started is True:\n ret['comment'] = ('Service {0} is already disabled,'\n ' and is running').format(name)\n elif started is None:\n # always be sure in this case to reset the changes dict\n ret['changes'] = {}\n ret['comment'] = ('Service {0} is already disabled,'\n ' and is in the desired state').format(name)\n else:\n ret['comment'] = ('Service {0} is already disabled,'\n ' and is dead').format(name)\n return ret\n\n # Service needs to be disabled\n if __opts__['test']:\n ret['result'] = None\n ret['comment'] = 'Service {0} set to be disabled'.format(name)\n return ret\n\n if __salt__['service.disable'](name, **kwargs):\n # Service has been disabled\n ret['changes'] = {}\n after_toggle_disable_status = __salt__['service.disabled'](name)\n # on upstart, certain services like apparmor will always return\n # False, even if correctly activated\n # do not trigger a change\n if before_toggle_disable_status != after_toggle_disable_status:\n ret['changes'][name] = True\n if started is True:\n ret['comment'] = ('Service {0} has been disabled,'\n ' and is running').format(name)\n elif started is None:\n ret['comment'] = ('Service {0} has been disabled,'\n ' and is in the desired state').format(name)\n else:\n ret['comment'] = ('Service {0} has been disabled,'\n ' and is dead').format(name)\n return ret\n\n # Service failed to be disabled\n ret['result'] = False\n if started is True:\n ret['comment'] = ('Failed when setting service {0} to not start'\n ' at boot, and is running').format(name)\n elif started is None:\n ret['comment'] = ('Failed when setting service {0} to not start'\n ' at boot, but the service was already running'\n ).format(name)\n else:\n ret['comment'] = ('Failed when setting service {0} to not start'\n ' at boot, and the service is dead').format(name)\n return ret\n",
"def is_true(value=None):\n '''\n Returns a boolean value representing the \"truth\" of the value passed. The\n rules for what is a \"True\" value are:\n\n 1. Integer/float values greater than 0\n 2. The string values \"True\" and \"true\"\n 3. Any object for which bool(obj) returns True\n '''\n # First, try int/float conversion\n try:\n value = int(value)\n except (ValueError, TypeError):\n pass\n try:\n value = float(value)\n except (ValueError, TypeError):\n pass\n\n # Now check for truthiness\n if isinstance(value, (six.integer_types, float)):\n return value > 0\n elif isinstance(value, six.string_types):\n return six.text_type(value).lower() == 'true'\n else:\n return bool(value)\n",
"def _available(name, ret):\n '''\n Check if the service is available\n '''\n avail = False\n if 'service.available' in __salt__:\n avail = __salt__['service.available'](name)\n elif 'service.get_all' in __salt__:\n avail = name in __salt__['service.get_all']()\n if not avail:\n ret['result'] = False\n ret['comment'] = 'The named service {0} is not available'.format(name)\n return avail\n",
"def unmasked(name, runtime=False):\n '''\n .. versionadded:: 2017.7.0\n\n .. note::\n This state is only available on minions which use systemd_.\n\n Ensures that the named service is unmasked\n\n name\n Name of the service to unmask\n\n runtime : False\n By default, this state will manage an indefinite mask for the named\n service. Set this argument to ``True`` to ensure that the service is\n runtime masked.\n\n .. note::\n It is possible for a service to have both indefinite and runtime masks\n set for it. Therefore, this state will manage a runtime or indefinite\n mask independently of each other. This means that if the service is\n indefinitely masked, running this state with ``runtime`` set to\n ``True`` will _not_ remove the indefinite mask.\n\n .. _systemd: https://freedesktop.org/wiki/Software/systemd/\n\n '''\n ret = {'name': name,\n 'changes': {},\n 'result': True,\n 'comment': ''}\n\n if 'service.masked' not in __salt__:\n ret['comment'] = 'Service masking not available on this minion'\n ret['result'] = False\n return ret\n\n mask_type = 'runtime masked' if runtime else 'masked'\n action = 'runtime unmasked' if runtime else 'unmasked'\n expected_changes = {mask_type: {'old': True, 'new': False}}\n\n try:\n if not __salt__['service.masked'](name, runtime):\n ret['comment'] = 'Service {0} was already {1}'.format(name, action)\n return ret\n\n if __opts__['test']:\n ret['result'] = None\n ret['changes'] = expected_changes\n ret['comment'] = 'Service {0} would be {1}'.format(name, action)\n return ret\n\n __salt__['service.unmask'](name, runtime)\n\n if not __salt__['service.masked'](name, runtime):\n ret['changes'] = expected_changes\n ret['comment'] = 'Service {0} was {1}'.format(name, action)\n else:\n ret['comment'] = 'Failed to unmask service {0}'.format(name)\n return ret\n\n except CommandExecutionError as exc:\n ret['result'] = False\n ret['comment'] = exc.strerror\n return ret\n",
"def _enable(name, started, result=True, skip_verify=False, **kwargs):\n '''\n Enable the service\n '''\n ret = {}\n\n if not skip_verify:\n # is service available?\n try:\n if not _available(name, ret):\n return ret\n except CommandExecutionError as exc:\n ret['result'] = False\n ret['comment'] = exc.strerror\n return ret\n\n # Set default expected result\n ret['result'] = result\n\n # Check to see if this minion supports enable\n if 'service.enable' not in __salt__ or 'service.enabled' not in __salt__:\n if started is True:\n ret['comment'] = ('Enable is not available on this minion,'\n ' service {0} started').format(name)\n elif started is None:\n ret['comment'] = ('Enable is not available on this minion,'\n ' service {0} is in the desired state'\n ).format(name)\n else:\n ret['comment'] = ('Enable is not available on this minion,'\n ' service {0} is dead').format(name)\n return ret\n\n # Service can be enabled\n before_toggle_enable_status = __salt__['service.enabled'](name, **kwargs)\n if before_toggle_enable_status:\n # Service is enabled\n if started is True:\n ret['comment'] = ('Service {0} is already enabled,'\n ' and is running').format(name)\n elif started is None:\n # always be sure in this case to reset the changes dict\n ret['changes'] = {}\n ret['comment'] = ('Service {0} is already enabled,'\n ' and is in the desired state').format(name)\n else:\n ret['comment'] = ('Service {0} is already enabled,'\n ' and is dead').format(name)\n return ret\n\n # Service needs to be enabled\n if __opts__['test']:\n ret['result'] = None\n ret['comment'] = 'Service {0} set to be enabled'.format(name)\n return ret\n\n try:\n if __salt__['service.enable'](name, **kwargs):\n # Service has been enabled\n ret['changes'] = {}\n after_toggle_enable_status = __salt__['service.enabled'](\n name,\n **kwargs)\n # on upstart, certain services like apparmor will always return\n # False, even if correctly activated\n # do not trigger a change\n if before_toggle_enable_status != after_toggle_enable_status:\n ret['changes'][name] = True\n if started is True:\n ret['comment'] = ('Service {0} has been enabled,'\n ' and is running').format(name)\n elif started is None:\n ret['comment'] = ('Service {0} has been enabled,'\n ' and is in the desired state').format(name)\n else:\n ret['comment'] = ('Service {0} has been enabled,'\n ' and is dead').format(name)\n return ret\n except CommandExecutionError as exc:\n enable_error = exc.strerror\n else:\n enable_error = False\n\n # Service failed to be enabled\n ret['result'] = False\n if started is True:\n ret['comment'] = ('Failed when setting service {0} to start at boot,'\n ' but the service is running').format(name)\n elif started is None:\n ret['comment'] = ('Failed when setting service {0} to start at boot,'\n ' but the service was already running').format(name)\n else:\n ret['comment'] = ('Failed when setting service {0} to start at boot,'\n ' and the service is dead').format(name)\n\n if enable_error:\n ret['comment'] += '. Additional information follows:\\n\\n{0}'.format(\n enable_error\n )\n\n return ret\n",
"def _get_systemd_only(func, kwargs):\n ret = {}\n warnings = []\n valid_args = _argspec(func).args\n for systemd_arg in SYSTEMD_ONLY:\n arg_val = kwargs.get(systemd_arg, False)\n if arg_val:\n if systemd_arg in valid_args:\n ret[systemd_arg] = arg_val\n else:\n warnings.append(\n 'The \\'{0}\\' argument is not supported by this '\n 'platform/action'.format(systemd_arg)\n )\n return ret, warnings\n",
"def _enabled_used_error(ret):\n '''\n Warn of potential typo.\n '''\n ret['result'] = False\n ret['comment'] = (\n 'Service {0} uses non-existent option \"enabled\". ' +\n 'Perhaps \"enable\" option was intended?'\n ).format(ret['name'])\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Starting or restarting of services and daemons
==============================================
Services are defined as system daemons and are typically launched using system
init or rc scripts. This service state uses whichever service module is loaded
on the minion with the virtualname of ``service``. Services can be defined as
either running or dead.
If you need to know if your init system is supported, see the list of supported
:mod:`service modules <salt.modules.service.py>` for your desired init system
(systemd, sysvinit, launchctl, etc.).
Note that Salt's service execution module, and therefore this service state,
uses OS grains to ascertain which service module should be loaded and used to
execute service functions. As existing distributions change init systems or
new distributions are created, OS detection can sometimes be incomplete.
If your service states are running into trouble with init system detection,
please see the :ref:`Overriding Virtual Module Providers <module-provider-override>`
section of Salt's module documentation to work around possible errors.
.. note::
The current status of a service is determined by the return code of the init/rc
script status command. A status return code of 0 it is considered running. Any
other return code is considered dead.
.. code-block:: yaml
httpd:
service.running: []
The service can also be set to start at runtime via the enable option:
.. code-block:: yaml
openvpn:
service.running:
- enable: True
By default if a service is triggered to refresh due to a watch statement the
service is restarted. If the desired behavior is to reload the service, then
set the reload value to True:
.. code-block:: yaml
redis:
service.running:
- enable: True
- reload: True
- watch:
- pkg: redis
.. note::
More details regarding ``watch`` can be found in the
:ref:`Requisites <requisites>` documentation.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
# Import Salt libs
import salt.utils.data
import salt.utils.platform
from salt.utils.args import get_function_argspec as _argspec
from salt.exceptions import CommandExecutionError
from salt.state import _gen_tag
# Import 3rd-party libs
from salt.ext import six
SYSTEMD_ONLY = ('no_block', 'unmask', 'unmask_runtime')
__virtualname__ = 'service'
def __virtual__():
'''
Only make these states available if a service provider has been detected or
assigned for this minion
'''
if 'service.start' in __salt__:
return __virtualname__
else:
return (False, 'No service execution module loaded: '
'check support for service management on {0} '
''.format(__grains__.get('osfinger', __grains__['os']))
)
# Double-asterisk deliberately not used here
def _get_systemd_only(func, kwargs):
ret = {}
warnings = []
valid_args = _argspec(func).args
for systemd_arg in SYSTEMD_ONLY:
arg_val = kwargs.get(systemd_arg, False)
if arg_val:
if systemd_arg in valid_args:
ret[systemd_arg] = arg_val
else:
warnings.append(
'The \'{0}\' argument is not supported by this '
'platform/action'.format(systemd_arg)
)
return ret, warnings
def _enabled_used_error(ret):
'''
Warn of potential typo.
'''
ret['result'] = False
ret['comment'] = (
'Service {0} uses non-existent option "enabled". ' +
'Perhaps "enable" option was intended?'
).format(ret['name'])
return ret
def _enable(name, started, result=True, skip_verify=False, **kwargs):
'''
Enable the service
'''
ret = {}
if not skip_verify:
# is service available?
try:
if not _available(name, ret):
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# Set default expected result
ret['result'] = result
# Check to see if this minion supports enable
if 'service.enable' not in __salt__ or 'service.enabled' not in __salt__:
if started is True:
ret['comment'] = ('Enable is not available on this minion,'
' service {0} started').format(name)
elif started is None:
ret['comment'] = ('Enable is not available on this minion,'
' service {0} is in the desired state'
).format(name)
else:
ret['comment'] = ('Enable is not available on this minion,'
' service {0} is dead').format(name)
return ret
# Service can be enabled
before_toggle_enable_status = __salt__['service.enabled'](name, **kwargs)
if before_toggle_enable_status:
# Service is enabled
if started is True:
ret['comment'] = ('Service {0} is already enabled,'
' and is running').format(name)
elif started is None:
# always be sure in this case to reset the changes dict
ret['changes'] = {}
ret['comment'] = ('Service {0} is already enabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} is already enabled,'
' and is dead').format(name)
return ret
# Service needs to be enabled
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service {0} set to be enabled'.format(name)
return ret
try:
if __salt__['service.enable'](name, **kwargs):
# Service has been enabled
ret['changes'] = {}
after_toggle_enable_status = __salt__['service.enabled'](
name,
**kwargs)
# on upstart, certain services like apparmor will always return
# False, even if correctly activated
# do not trigger a change
if before_toggle_enable_status != after_toggle_enable_status:
ret['changes'][name] = True
if started is True:
ret['comment'] = ('Service {0} has been enabled,'
' and is running').format(name)
elif started is None:
ret['comment'] = ('Service {0} has been enabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} has been enabled,'
' and is dead').format(name)
return ret
except CommandExecutionError as exc:
enable_error = exc.strerror
else:
enable_error = False
# Service failed to be enabled
ret['result'] = False
if started is True:
ret['comment'] = ('Failed when setting service {0} to start at boot,'
' but the service is running').format(name)
elif started is None:
ret['comment'] = ('Failed when setting service {0} to start at boot,'
' but the service was already running').format(name)
else:
ret['comment'] = ('Failed when setting service {0} to start at boot,'
' and the service is dead').format(name)
if enable_error:
ret['comment'] += '. Additional information follows:\n\n{0}'.format(
enable_error
)
return ret
def _disable(name, started, result=True, skip_verify=False, **kwargs):
'''
Disable the service
'''
ret = {}
if not skip_verify:
# is service available?
try:
if not _available(name, ret):
ret['result'] = True
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# Set default expected result
ret['result'] = result
# is enable/disable available?
if 'service.disable' not in __salt__ or 'service.disabled' not in __salt__:
if started is True:
ret['comment'] = ('Disable is not available on this minion,'
' service {0} started').format(name)
elif started is None:
ret['comment'] = ('Disable is not available on this minion,'
' service {0} is in the desired state'
).format(name)
else:
ret['comment'] = ('Disable is not available on this minion,'
' service {0} is dead').format(name)
return ret
# Service can be disabled
if salt.utils.platform.is_windows():
# service.disabled in Windows returns True for services that are set to
# Manual start, so we need to check specifically for Disabled
before_toggle_disable_status = __salt__['service.info'](name)['StartType'] in ['Disabled']
else:
before_toggle_disable_status = __salt__['service.disabled'](name)
if before_toggle_disable_status:
# Service is disabled
if started is True:
ret['comment'] = ('Service {0} is already disabled,'
' and is running').format(name)
elif started is None:
# always be sure in this case to reset the changes dict
ret['changes'] = {}
ret['comment'] = ('Service {0} is already disabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} is already disabled,'
' and is dead').format(name)
return ret
# Service needs to be disabled
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service {0} set to be disabled'.format(name)
return ret
if __salt__['service.disable'](name, **kwargs):
# Service has been disabled
ret['changes'] = {}
after_toggle_disable_status = __salt__['service.disabled'](name)
# on upstart, certain services like apparmor will always return
# False, even if correctly activated
# do not trigger a change
if before_toggle_disable_status != after_toggle_disable_status:
ret['changes'][name] = True
if started is True:
ret['comment'] = ('Service {0} has been disabled,'
' and is running').format(name)
elif started is None:
ret['comment'] = ('Service {0} has been disabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} has been disabled,'
' and is dead').format(name)
return ret
# Service failed to be disabled
ret['result'] = False
if started is True:
ret['comment'] = ('Failed when setting service {0} to not start'
' at boot, and is running').format(name)
elif started is None:
ret['comment'] = ('Failed when setting service {0} to not start'
' at boot, but the service was already running'
).format(name)
else:
ret['comment'] = ('Failed when setting service {0} to not start'
' at boot, and the service is dead').format(name)
return ret
def _available(name, ret):
'''
Check if the service is available
'''
avail = False
if 'service.available' in __salt__:
avail = __salt__['service.available'](name)
elif 'service.get_all' in __salt__:
avail = name in __salt__['service.get_all']()
if not avail:
ret['result'] = False
ret['comment'] = 'The named service {0} is not available'.format(name)
return avail
def dead(name,
enable=None,
sig=None,
init_delay=None,
**kwargs):
'''
Ensure that the named service is dead by stopping the service if it is running
name
The name of the init or rc script used to manage the service
enable
Set the service to be enabled at boot time, ``True`` sets the service
to be enabled, ``False`` sets the named service to be disabled. The
default is ``None``, which does not enable or disable anything.
sig
The string to search for when looking for the service process with ps
init_delay
Add a sleep command (in seconds) before the check to make sure service
is killed.
.. versionadded:: 2017.7.0
no_block : False
**For systemd minions only.** Stops the service using ``--no-block``.
.. versionadded:: 2017.7.0
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
# Check for common error: using enabled option instead of enable
if 'enabled' in kwargs:
return _enabled_used_error(ret)
# Convert enable to boolean in case user passed a string value
if isinstance(enable, six.string_types):
enable = salt.utils.data.is_true(enable)
# Check if the service is available
try:
if not _available(name, ret):
if __opts__.get('test'):
ret['result'] = None
ret['comment'] = 'Service {0} not present; if created in this state run, it would have been stopped'.format(name)
else:
# A non-available service is OK here, don't let the state fail
# because of it.
ret['result'] = True
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# lot of custom init script won't or mis implement the status
# command, so it is just an indicator but can not be fully trusted
before_toggle_status = __salt__['service.status'](name, sig)
if 'service.enabled' in __salt__:
if salt.utils.platform.is_windows():
# service.enabled in Windows returns True for services that are set
# to Auto start, but services set to Manual can also be disabled
before_toggle_enable_status = __salt__['service.info'](name)['StartType'] in ['Auto', 'Manual']
else:
before_toggle_enable_status = __salt__['service.enabled'](name)
else:
before_toggle_enable_status = True
# See if the service is already dead
if not before_toggle_status:
ret['comment'] = 'The service {0} is already dead'.format(name)
if enable is True and not before_toggle_enable_status:
ret.update(_enable(name, None, skip_verify=False, **kwargs))
elif enable is False and before_toggle_enable_status:
ret.update(_disable(name, None, skip_verify=False, **kwargs))
return ret
# Run the tests
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service {0} is set to be killed'.format(name)
return ret
# Conditionally add systemd-specific args to call to service.start
stop_kwargs, warnings = _get_systemd_only(__salt__['service.stop'], kwargs)
if warnings:
ret.setdefault('warnings', []).extend(warnings)
if salt.utils.platform.is_windows():
for arg in ['timeout', 'with_deps', 'with_parents']:
if kwargs.get(arg, False):
stop_kwargs.update({arg: kwargs.get(arg)})
func_ret = __salt__['service.stop'](name, **stop_kwargs)
if not func_ret:
ret['result'] = False
ret['comment'] = 'Service {0} failed to die'.format(name)
if enable is True:
ret.update(_enable(name, True, result=False, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, True, result=False, skip_verify=False, **kwargs))
return ret
if init_delay:
time.sleep(init_delay)
# only force a change state if we have explicitly detected them
after_toggle_status = __salt__['service.status'](name)
if 'service.enabled' in __salt__:
after_toggle_enable_status = __salt__['service.enabled'](name)
else:
after_toggle_enable_status = True
if (
(before_toggle_enable_status != after_toggle_enable_status) or
(before_toggle_status != after_toggle_status)
) and not ret.get('changes', {}):
ret['changes'][name] = after_toggle_status
# be sure to stop, in case we mis detected in the check
if after_toggle_status:
ret['result'] = False
ret['comment'] = 'Service {0} failed to die'.format(name)
else:
ret['comment'] = 'Service {0} was killed'.format(name)
if enable is True:
ret.update(_enable(name, after_toggle_status, result=not after_toggle_status, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, after_toggle_status, result=not after_toggle_status, skip_verify=False, **kwargs))
return ret
def enabled(name,
skip_verify=False,
**kwargs):
'''
Ensure that the service is enabled on boot, only use this state if you
don't want to manage the running process, remember that if you want to
enable a running service to use the enable: True option for the running
or dead function.
name
The name of the init or rc script used to manage the service
skip_verify
Skip verifying that the service is available before enabling it.
``True`` will skip the verification. The default is ``False``,
which will ensure the service is available before enabling it.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
ret.update(_enable(name, None, skip_verify=skip_verify, **kwargs))
return ret
def disabled(name,
skip_verify=False,
**kwargs):
'''
Ensure that the service is disabled on boot, only use this state if you
don't want to manage the running process, remember that if you want to
disable a service to use the enable: False option for the running or dead
function.
name
The name of the init or rc script used to manage the service
skip_verify
Skip verifying that the service is available before disabling it.
``True`` will skip the verification. The default is ``False``,
which will ensure the service is available before disabling it.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
ret.update(_disable(name, None, skip_verify=skip_verify, **kwargs))
return ret
def masked(name, runtime=False):
'''
.. versionadded:: 2017.7.0
.. note::
This state is only available on minions which use systemd_.
Ensures that the named service is masked (i.e. prevented from being
started).
name
Name of the service to mask
runtime : False
By default, this state will manage an indefinite mask for the named
service. Set this argument to ``True`` to runtime mask the service.
.. note::
It is possible for a service to have both indefinite and runtime masks
set for it. Therefore, this state will manage a runtime or indefinite
mask independently of each other. This means that if the service is
already indefinitely masked, running this state with ``runtime`` set to
``True`` will _not_ remove the indefinite mask before setting a runtime
mask. In these cases, if it is desirable to ensure that the service is
runtime masked and not indefinitely masked, pair this state with a
:py:func:`service.unmasked <salt.states.service.unmasked>` state, like
so:
.. code-block:: yaml
mask_runtime_foo:
service.masked:
- name: foo
- runtime: True
unmask_indefinite_foo:
service.unmasked:
- name: foo
- runtime: False
.. _systemd: https://freedesktop.org/wiki/Software/systemd/
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if 'service.masked' not in __salt__:
ret['comment'] = 'Service masking not available on this minion'
ret['result'] = False
return ret
mask_type = 'runtime masked' if runtime else 'masked'
expected_changes = {mask_type: {'old': False, 'new': True}}
try:
if __salt__['service.masked'](name, runtime):
ret['comment'] = 'Service {0} is already {1}'.format(
name,
mask_type,
)
return ret
if __opts__['test']:
ret['result'] = None
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} would be {1}'.format(name, mask_type)
return ret
__salt__['service.mask'](name, runtime)
if __salt__['service.masked'](name, runtime):
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} was {1}'.format(name, mask_type)
else:
ret['comment'] = 'Failed to mask service {0}'.format(name)
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
def unmasked(name, runtime=False):
'''
.. versionadded:: 2017.7.0
.. note::
This state is only available on minions which use systemd_.
Ensures that the named service is unmasked
name
Name of the service to unmask
runtime : False
By default, this state will manage an indefinite mask for the named
service. Set this argument to ``True`` to ensure that the service is
runtime masked.
.. note::
It is possible for a service to have both indefinite and runtime masks
set for it. Therefore, this state will manage a runtime or indefinite
mask independently of each other. This means that if the service is
indefinitely masked, running this state with ``runtime`` set to
``True`` will _not_ remove the indefinite mask.
.. _systemd: https://freedesktop.org/wiki/Software/systemd/
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if 'service.masked' not in __salt__:
ret['comment'] = 'Service masking not available on this minion'
ret['result'] = False
return ret
mask_type = 'runtime masked' if runtime else 'masked'
action = 'runtime unmasked' if runtime else 'unmasked'
expected_changes = {mask_type: {'old': True, 'new': False}}
try:
if not __salt__['service.masked'](name, runtime):
ret['comment'] = 'Service {0} was already {1}'.format(name, action)
return ret
if __opts__['test']:
ret['result'] = None
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} would be {1}'.format(name, action)
return ret
__salt__['service.unmask'](name, runtime)
if not __salt__['service.masked'](name, runtime):
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} was {1}'.format(name, action)
else:
ret['comment'] = 'Failed to unmask service {0}'.format(name)
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
def mod_watch(name,
sfun=None,
sig=None,
full_restart=False,
init_delay=None,
force=False,
**kwargs):
'''
The service watcher, called to invoke the watch command.
When called, it will restart or reload the named service.
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the watching service.
(i.e. ``service.running``)
name
The name of the init or rc script used to manage the service
sfun
The original function which triggered the mod_watch call
(`service.running`, for example).
sig
The string to search for when looking for the service process with ps
reload
If True use reload instead of the default restart. If value is a list of
requisites; reload only if all watched changes are contained in the reload list.
Otherwise watch will restart.
full_restart
Use service.full_restart instead of restart.
When set, reload the service instead of restarting it.
(i.e. ``service nginx reload``)
full_restart
Perform a full stop/start of a service by passing ``--full-restart``.
This option is ignored if ``reload`` is set and is supported by only a few
:py:func:`service modules <salt.modules.service>`.
force
Use service.force_reload instead of reload (needs reload to be set to True)
init_delay
Add a sleep command (in seconds) before the service is restarted/reloaded
'''
reload_ = kwargs.pop('reload', False)
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
past_participle = None
if sfun == 'dead':
verb = 'stop'
past_participle = verb + 'ped'
if __salt__['service.status'](name, sig):
func = __salt__['service.stop']
else:
ret['result'] = True
ret['comment'] = 'Service is already {0}'.format(past_participle)
return ret
elif sfun == 'running':
if __salt__['service.status'](name, sig):
if 'service.reload' in __salt__ and reload_:
if isinstance(reload_, list):
only_reload_needed = True
for watch_item in kwargs['__reqs__']['watch']:
if __running__[_gen_tag(watch_item)]['changes']:
match_found = False
for this_reload in reload_:
for state, id_ in six.iteritems(this_reload):
if state == watch_item['state'] \
and id_ == watch_item['__id__']:
match_found = True
if not match_found:
only_reload_needed = False
if only_reload_needed:
if 'service.force_reload' in __salt__ and force:
func = __salt__['service.force_reload']
verb = 'forcefully reload'
else:
func = __salt__['service.reload']
verb = 'reload'
else:
if 'service.full_restart' in __salt__ and full_restart:
func = __salt__['service.full_restart']
verb = 'fully restart'
else:
func = __salt__['service.restart']
verb = 'restart'
else:
if 'service.force_reload' in __salt__ and force:
func = __salt__['service.force_reload']
verb = 'forcefully reload'
else:
func = __salt__['service.reload']
verb = 'reload'
elif 'service.full_restart' in __salt__ and full_restart:
func = __salt__['service.full_restart']
verb = 'fully restart'
else:
func = __salt__['service.restart']
verb = 'restart'
else:
func = __salt__['service.start']
verb = 'start'
if not past_participle:
past_participle = verb + 'ed'
else:
ret['comment'] = 'Unable to trigger watch for service.{0}'.format(sfun)
ret['result'] = False
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service is set to be {0}'.format(past_participle)
return ret
if verb == 'start' and 'service.stop' in __salt__:
# stop service before start
__salt__['service.stop'](name)
func_kwargs, warnings = _get_systemd_only(func, kwargs)
if warnings:
ret.setdefault('warnings', []).extend(warnings)
try:
result = func(name, **func_kwargs)
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
if init_delay:
time.sleep(init_delay)
ret['changes'] = {name: result}
ret['result'] = result
ret['comment'] = 'Service {0}'.format(past_participle) if result else \
'Failed to {0} the service'.format(verb)
return ret
|
saltstack/salt
|
salt/states/service.py
|
dead
|
python
|
def dead(name,
enable=None,
sig=None,
init_delay=None,
**kwargs):
'''
Ensure that the named service is dead by stopping the service if it is running
name
The name of the init or rc script used to manage the service
enable
Set the service to be enabled at boot time, ``True`` sets the service
to be enabled, ``False`` sets the named service to be disabled. The
default is ``None``, which does not enable or disable anything.
sig
The string to search for when looking for the service process with ps
init_delay
Add a sleep command (in seconds) before the check to make sure service
is killed.
.. versionadded:: 2017.7.0
no_block : False
**For systemd minions only.** Stops the service using ``--no-block``.
.. versionadded:: 2017.7.0
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
# Check for common error: using enabled option instead of enable
if 'enabled' in kwargs:
return _enabled_used_error(ret)
# Convert enable to boolean in case user passed a string value
if isinstance(enable, six.string_types):
enable = salt.utils.data.is_true(enable)
# Check if the service is available
try:
if not _available(name, ret):
if __opts__.get('test'):
ret['result'] = None
ret['comment'] = 'Service {0} not present; if created in this state run, it would have been stopped'.format(name)
else:
# A non-available service is OK here, don't let the state fail
# because of it.
ret['result'] = True
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# lot of custom init script won't or mis implement the status
# command, so it is just an indicator but can not be fully trusted
before_toggle_status = __salt__['service.status'](name, sig)
if 'service.enabled' in __salt__:
if salt.utils.platform.is_windows():
# service.enabled in Windows returns True for services that are set
# to Auto start, but services set to Manual can also be disabled
before_toggle_enable_status = __salt__['service.info'](name)['StartType'] in ['Auto', 'Manual']
else:
before_toggle_enable_status = __salt__['service.enabled'](name)
else:
before_toggle_enable_status = True
# See if the service is already dead
if not before_toggle_status:
ret['comment'] = 'The service {0} is already dead'.format(name)
if enable is True and not before_toggle_enable_status:
ret.update(_enable(name, None, skip_verify=False, **kwargs))
elif enable is False and before_toggle_enable_status:
ret.update(_disable(name, None, skip_verify=False, **kwargs))
return ret
# Run the tests
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service {0} is set to be killed'.format(name)
return ret
# Conditionally add systemd-specific args to call to service.start
stop_kwargs, warnings = _get_systemd_only(__salt__['service.stop'], kwargs)
if warnings:
ret.setdefault('warnings', []).extend(warnings)
if salt.utils.platform.is_windows():
for arg in ['timeout', 'with_deps', 'with_parents']:
if kwargs.get(arg, False):
stop_kwargs.update({arg: kwargs.get(arg)})
func_ret = __salt__['service.stop'](name, **stop_kwargs)
if not func_ret:
ret['result'] = False
ret['comment'] = 'Service {0} failed to die'.format(name)
if enable is True:
ret.update(_enable(name, True, result=False, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, True, result=False, skip_verify=False, **kwargs))
return ret
if init_delay:
time.sleep(init_delay)
# only force a change state if we have explicitly detected them
after_toggle_status = __salt__['service.status'](name)
if 'service.enabled' in __salt__:
after_toggle_enable_status = __salt__['service.enabled'](name)
else:
after_toggle_enable_status = True
if (
(before_toggle_enable_status != after_toggle_enable_status) or
(before_toggle_status != after_toggle_status)
) and not ret.get('changes', {}):
ret['changes'][name] = after_toggle_status
# be sure to stop, in case we mis detected in the check
if after_toggle_status:
ret['result'] = False
ret['comment'] = 'Service {0} failed to die'.format(name)
else:
ret['comment'] = 'Service {0} was killed'.format(name)
if enable is True:
ret.update(_enable(name, after_toggle_status, result=not after_toggle_status, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, after_toggle_status, result=not after_toggle_status, skip_verify=False, **kwargs))
return ret
|
Ensure that the named service is dead by stopping the service if it is running
name
The name of the init or rc script used to manage the service
enable
Set the service to be enabled at boot time, ``True`` sets the service
to be enabled, ``False`` sets the named service to be disabled. The
default is ``None``, which does not enable or disable anything.
sig
The string to search for when looking for the service process with ps
init_delay
Add a sleep command (in seconds) before the check to make sure service
is killed.
.. versionadded:: 2017.7.0
no_block : False
**For systemd minions only.** Stops the service using ``--no-block``.
.. versionadded:: 2017.7.0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/service.py#L517-L651
|
[
"def _disable(name, started, result=True, skip_verify=False, **kwargs):\n '''\n Disable the service\n '''\n ret = {}\n\n if not skip_verify:\n # is service available?\n try:\n if not _available(name, ret):\n ret['result'] = True\n return ret\n except CommandExecutionError as exc:\n ret['result'] = False\n ret['comment'] = exc.strerror\n return ret\n\n # Set default expected result\n ret['result'] = result\n\n # is enable/disable available?\n if 'service.disable' not in __salt__ or 'service.disabled' not in __salt__:\n if started is True:\n ret['comment'] = ('Disable is not available on this minion,'\n ' service {0} started').format(name)\n elif started is None:\n ret['comment'] = ('Disable is not available on this minion,'\n ' service {0} is in the desired state'\n ).format(name)\n else:\n ret['comment'] = ('Disable is not available on this minion,'\n ' service {0} is dead').format(name)\n return ret\n\n # Service can be disabled\n if salt.utils.platform.is_windows():\n # service.disabled in Windows returns True for services that are set to\n # Manual start, so we need to check specifically for Disabled\n before_toggle_disable_status = __salt__['service.info'](name)['StartType'] in ['Disabled']\n else:\n before_toggle_disable_status = __salt__['service.disabled'](name)\n if before_toggle_disable_status:\n # Service is disabled\n if started is True:\n ret['comment'] = ('Service {0} is already disabled,'\n ' and is running').format(name)\n elif started is None:\n # always be sure in this case to reset the changes dict\n ret['changes'] = {}\n ret['comment'] = ('Service {0} is already disabled,'\n ' and is in the desired state').format(name)\n else:\n ret['comment'] = ('Service {0} is already disabled,'\n ' and is dead').format(name)\n return ret\n\n # Service needs to be disabled\n if __opts__['test']:\n ret['result'] = None\n ret['comment'] = 'Service {0} set to be disabled'.format(name)\n return ret\n\n if __salt__['service.disable'](name, **kwargs):\n # Service has been disabled\n ret['changes'] = {}\n after_toggle_disable_status = __salt__['service.disabled'](name)\n # on upstart, certain services like apparmor will always return\n # False, even if correctly activated\n # do not trigger a change\n if before_toggle_disable_status != after_toggle_disable_status:\n ret['changes'][name] = True\n if started is True:\n ret['comment'] = ('Service {0} has been disabled,'\n ' and is running').format(name)\n elif started is None:\n ret['comment'] = ('Service {0} has been disabled,'\n ' and is in the desired state').format(name)\n else:\n ret['comment'] = ('Service {0} has been disabled,'\n ' and is dead').format(name)\n return ret\n\n # Service failed to be disabled\n ret['result'] = False\n if started is True:\n ret['comment'] = ('Failed when setting service {0} to not start'\n ' at boot, and is running').format(name)\n elif started is None:\n ret['comment'] = ('Failed when setting service {0} to not start'\n ' at boot, but the service was already running'\n ).format(name)\n else:\n ret['comment'] = ('Failed when setting service {0} to not start'\n ' at boot, and the service is dead').format(name)\n return ret\n",
"def is_true(value=None):\n '''\n Returns a boolean value representing the \"truth\" of the value passed. The\n rules for what is a \"True\" value are:\n\n 1. Integer/float values greater than 0\n 2. The string values \"True\" and \"true\"\n 3. Any object for which bool(obj) returns True\n '''\n # First, try int/float conversion\n try:\n value = int(value)\n except (ValueError, TypeError):\n pass\n try:\n value = float(value)\n except (ValueError, TypeError):\n pass\n\n # Now check for truthiness\n if isinstance(value, (six.integer_types, float)):\n return value > 0\n elif isinstance(value, six.string_types):\n return six.text_type(value).lower() == 'true'\n else:\n return bool(value)\n",
"def _available(name, ret):\n '''\n Check if the service is available\n '''\n avail = False\n if 'service.available' in __salt__:\n avail = __salt__['service.available'](name)\n elif 'service.get_all' in __salt__:\n avail = name in __salt__['service.get_all']()\n if not avail:\n ret['result'] = False\n ret['comment'] = 'The named service {0} is not available'.format(name)\n return avail\n",
"def _enable(name, started, result=True, skip_verify=False, **kwargs):\n '''\n Enable the service\n '''\n ret = {}\n\n if not skip_verify:\n # is service available?\n try:\n if not _available(name, ret):\n return ret\n except CommandExecutionError as exc:\n ret['result'] = False\n ret['comment'] = exc.strerror\n return ret\n\n # Set default expected result\n ret['result'] = result\n\n # Check to see if this minion supports enable\n if 'service.enable' not in __salt__ or 'service.enabled' not in __salt__:\n if started is True:\n ret['comment'] = ('Enable is not available on this minion,'\n ' service {0} started').format(name)\n elif started is None:\n ret['comment'] = ('Enable is not available on this minion,'\n ' service {0} is in the desired state'\n ).format(name)\n else:\n ret['comment'] = ('Enable is not available on this minion,'\n ' service {0} is dead').format(name)\n return ret\n\n # Service can be enabled\n before_toggle_enable_status = __salt__['service.enabled'](name, **kwargs)\n if before_toggle_enable_status:\n # Service is enabled\n if started is True:\n ret['comment'] = ('Service {0} is already enabled,'\n ' and is running').format(name)\n elif started is None:\n # always be sure in this case to reset the changes dict\n ret['changes'] = {}\n ret['comment'] = ('Service {0} is already enabled,'\n ' and is in the desired state').format(name)\n else:\n ret['comment'] = ('Service {0} is already enabled,'\n ' and is dead').format(name)\n return ret\n\n # Service needs to be enabled\n if __opts__['test']:\n ret['result'] = None\n ret['comment'] = 'Service {0} set to be enabled'.format(name)\n return ret\n\n try:\n if __salt__['service.enable'](name, **kwargs):\n # Service has been enabled\n ret['changes'] = {}\n after_toggle_enable_status = __salt__['service.enabled'](\n name,\n **kwargs)\n # on upstart, certain services like apparmor will always return\n # False, even if correctly activated\n # do not trigger a change\n if before_toggle_enable_status != after_toggle_enable_status:\n ret['changes'][name] = True\n if started is True:\n ret['comment'] = ('Service {0} has been enabled,'\n ' and is running').format(name)\n elif started is None:\n ret['comment'] = ('Service {0} has been enabled,'\n ' and is in the desired state').format(name)\n else:\n ret['comment'] = ('Service {0} has been enabled,'\n ' and is dead').format(name)\n return ret\n except CommandExecutionError as exc:\n enable_error = exc.strerror\n else:\n enable_error = False\n\n # Service failed to be enabled\n ret['result'] = False\n if started is True:\n ret['comment'] = ('Failed when setting service {0} to start at boot,'\n ' but the service is running').format(name)\n elif started is None:\n ret['comment'] = ('Failed when setting service {0} to start at boot,'\n ' but the service was already running').format(name)\n else:\n ret['comment'] = ('Failed when setting service {0} to start at boot,'\n ' and the service is dead').format(name)\n\n if enable_error:\n ret['comment'] += '. Additional information follows:\\n\\n{0}'.format(\n enable_error\n )\n\n return ret\n",
"def _get_systemd_only(func, kwargs):\n ret = {}\n warnings = []\n valid_args = _argspec(func).args\n for systemd_arg in SYSTEMD_ONLY:\n arg_val = kwargs.get(systemd_arg, False)\n if arg_val:\n if systemd_arg in valid_args:\n ret[systemd_arg] = arg_val\n else:\n warnings.append(\n 'The \\'{0}\\' argument is not supported by this '\n 'platform/action'.format(systemd_arg)\n )\n return ret, warnings\n",
"def _enabled_used_error(ret):\n '''\n Warn of potential typo.\n '''\n ret['result'] = False\n ret['comment'] = (\n 'Service {0} uses non-existent option \"enabled\". ' +\n 'Perhaps \"enable\" option was intended?'\n ).format(ret['name'])\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Starting or restarting of services and daemons
==============================================
Services are defined as system daemons and are typically launched using system
init or rc scripts. This service state uses whichever service module is loaded
on the minion with the virtualname of ``service``. Services can be defined as
either running or dead.
If you need to know if your init system is supported, see the list of supported
:mod:`service modules <salt.modules.service.py>` for your desired init system
(systemd, sysvinit, launchctl, etc.).
Note that Salt's service execution module, and therefore this service state,
uses OS grains to ascertain which service module should be loaded and used to
execute service functions. As existing distributions change init systems or
new distributions are created, OS detection can sometimes be incomplete.
If your service states are running into trouble with init system detection,
please see the :ref:`Overriding Virtual Module Providers <module-provider-override>`
section of Salt's module documentation to work around possible errors.
.. note::
The current status of a service is determined by the return code of the init/rc
script status command. A status return code of 0 it is considered running. Any
other return code is considered dead.
.. code-block:: yaml
httpd:
service.running: []
The service can also be set to start at runtime via the enable option:
.. code-block:: yaml
openvpn:
service.running:
- enable: True
By default if a service is triggered to refresh due to a watch statement the
service is restarted. If the desired behavior is to reload the service, then
set the reload value to True:
.. code-block:: yaml
redis:
service.running:
- enable: True
- reload: True
- watch:
- pkg: redis
.. note::
More details regarding ``watch`` can be found in the
:ref:`Requisites <requisites>` documentation.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
# Import Salt libs
import salt.utils.data
import salt.utils.platform
from salt.utils.args import get_function_argspec as _argspec
from salt.exceptions import CommandExecutionError
from salt.state import _gen_tag
# Import 3rd-party libs
from salt.ext import six
SYSTEMD_ONLY = ('no_block', 'unmask', 'unmask_runtime')
__virtualname__ = 'service'
def __virtual__():
'''
Only make these states available if a service provider has been detected or
assigned for this minion
'''
if 'service.start' in __salt__:
return __virtualname__
else:
return (False, 'No service execution module loaded: '
'check support for service management on {0} '
''.format(__grains__.get('osfinger', __grains__['os']))
)
# Double-asterisk deliberately not used here
def _get_systemd_only(func, kwargs):
ret = {}
warnings = []
valid_args = _argspec(func).args
for systemd_arg in SYSTEMD_ONLY:
arg_val = kwargs.get(systemd_arg, False)
if arg_val:
if systemd_arg in valid_args:
ret[systemd_arg] = arg_val
else:
warnings.append(
'The \'{0}\' argument is not supported by this '
'platform/action'.format(systemd_arg)
)
return ret, warnings
def _enabled_used_error(ret):
'''
Warn of potential typo.
'''
ret['result'] = False
ret['comment'] = (
'Service {0} uses non-existent option "enabled". ' +
'Perhaps "enable" option was intended?'
).format(ret['name'])
return ret
def _enable(name, started, result=True, skip_verify=False, **kwargs):
'''
Enable the service
'''
ret = {}
if not skip_verify:
# is service available?
try:
if not _available(name, ret):
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# Set default expected result
ret['result'] = result
# Check to see if this minion supports enable
if 'service.enable' not in __salt__ or 'service.enabled' not in __salt__:
if started is True:
ret['comment'] = ('Enable is not available on this minion,'
' service {0} started').format(name)
elif started is None:
ret['comment'] = ('Enable is not available on this minion,'
' service {0} is in the desired state'
).format(name)
else:
ret['comment'] = ('Enable is not available on this minion,'
' service {0} is dead').format(name)
return ret
# Service can be enabled
before_toggle_enable_status = __salt__['service.enabled'](name, **kwargs)
if before_toggle_enable_status:
# Service is enabled
if started is True:
ret['comment'] = ('Service {0} is already enabled,'
' and is running').format(name)
elif started is None:
# always be sure in this case to reset the changes dict
ret['changes'] = {}
ret['comment'] = ('Service {0} is already enabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} is already enabled,'
' and is dead').format(name)
return ret
# Service needs to be enabled
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service {0} set to be enabled'.format(name)
return ret
try:
if __salt__['service.enable'](name, **kwargs):
# Service has been enabled
ret['changes'] = {}
after_toggle_enable_status = __salt__['service.enabled'](
name,
**kwargs)
# on upstart, certain services like apparmor will always return
# False, even if correctly activated
# do not trigger a change
if before_toggle_enable_status != after_toggle_enable_status:
ret['changes'][name] = True
if started is True:
ret['comment'] = ('Service {0} has been enabled,'
' and is running').format(name)
elif started is None:
ret['comment'] = ('Service {0} has been enabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} has been enabled,'
' and is dead').format(name)
return ret
except CommandExecutionError as exc:
enable_error = exc.strerror
else:
enable_error = False
# Service failed to be enabled
ret['result'] = False
if started is True:
ret['comment'] = ('Failed when setting service {0} to start at boot,'
' but the service is running').format(name)
elif started is None:
ret['comment'] = ('Failed when setting service {0} to start at boot,'
' but the service was already running').format(name)
else:
ret['comment'] = ('Failed when setting service {0} to start at boot,'
' and the service is dead').format(name)
if enable_error:
ret['comment'] += '. Additional information follows:\n\n{0}'.format(
enable_error
)
return ret
def _disable(name, started, result=True, skip_verify=False, **kwargs):
'''
Disable the service
'''
ret = {}
if not skip_verify:
# is service available?
try:
if not _available(name, ret):
ret['result'] = True
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# Set default expected result
ret['result'] = result
# is enable/disable available?
if 'service.disable' not in __salt__ or 'service.disabled' not in __salt__:
if started is True:
ret['comment'] = ('Disable is not available on this minion,'
' service {0} started').format(name)
elif started is None:
ret['comment'] = ('Disable is not available on this minion,'
' service {0} is in the desired state'
).format(name)
else:
ret['comment'] = ('Disable is not available on this minion,'
' service {0} is dead').format(name)
return ret
# Service can be disabled
if salt.utils.platform.is_windows():
# service.disabled in Windows returns True for services that are set to
# Manual start, so we need to check specifically for Disabled
before_toggle_disable_status = __salt__['service.info'](name)['StartType'] in ['Disabled']
else:
before_toggle_disable_status = __salt__['service.disabled'](name)
if before_toggle_disable_status:
# Service is disabled
if started is True:
ret['comment'] = ('Service {0} is already disabled,'
' and is running').format(name)
elif started is None:
# always be sure in this case to reset the changes dict
ret['changes'] = {}
ret['comment'] = ('Service {0} is already disabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} is already disabled,'
' and is dead').format(name)
return ret
# Service needs to be disabled
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service {0} set to be disabled'.format(name)
return ret
if __salt__['service.disable'](name, **kwargs):
# Service has been disabled
ret['changes'] = {}
after_toggle_disable_status = __salt__['service.disabled'](name)
# on upstart, certain services like apparmor will always return
# False, even if correctly activated
# do not trigger a change
if before_toggle_disable_status != after_toggle_disable_status:
ret['changes'][name] = True
if started is True:
ret['comment'] = ('Service {0} has been disabled,'
' and is running').format(name)
elif started is None:
ret['comment'] = ('Service {0} has been disabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} has been disabled,'
' and is dead').format(name)
return ret
# Service failed to be disabled
ret['result'] = False
if started is True:
ret['comment'] = ('Failed when setting service {0} to not start'
' at boot, and is running').format(name)
elif started is None:
ret['comment'] = ('Failed when setting service {0} to not start'
' at boot, but the service was already running'
).format(name)
else:
ret['comment'] = ('Failed when setting service {0} to not start'
' at boot, and the service is dead').format(name)
return ret
def _available(name, ret):
'''
Check if the service is available
'''
avail = False
if 'service.available' in __salt__:
avail = __salt__['service.available'](name)
elif 'service.get_all' in __salt__:
avail = name in __salt__['service.get_all']()
if not avail:
ret['result'] = False
ret['comment'] = 'The named service {0} is not available'.format(name)
return avail
def running(name,
enable=None,
sig=None,
init_delay=None,
no_block=False,
unmask=False,
unmask_runtime=False,
**kwargs):
'''
Ensure that the service is running
name
The name of the init or rc script used to manage the service
enable
Set the service to be enabled at boot time, ``True`` sets the service
to be enabled, ``False`` sets the named service to be disabled. The
default is ``None``, which does not enable or disable anything.
sig
The string to search for when looking for the service process with ps
init_delay
Some services may not be truly available for a short period after their
startup script indicates to the system that they are. Provide an
'init_delay' to specify that this state should wait an additional given
number of seconds after a service has started before returning. Useful
for requisite states wherein a dependent state might assume a service
has started but is not yet fully initialized.
no_block : False
**For systemd minions only.** Starts the service using ``--no-block``.
.. versionadded:: 2017.7.0
unmask : False
**For systemd minions only.** Set to ``True`` to remove an indefinite
mask before attempting to start the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
making any changes. This behavior is no longer the default.
unmask_runtime : False
**For systemd minions only.** Set to ``True`` to remove a runtime mask
before attempting to start the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
making any changes. This behavior is no longer the default.
.. note::
``watch`` can be used with service.running to restart a service when
another state changes ( example: a file.managed state that creates the
service's config file ). More details regarding ``watch`` can be found
in the :ref:`Requisites <requisites>` documentation.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
# Check for common error: using enabled option instead of enable
if 'enabled' in kwargs:
return _enabled_used_error(ret)
# Convert enable to boolean in case user passed a string value
if isinstance(enable, six.string_types):
enable = salt.utils.data.is_true(enable)
# Check if the service is available
try:
if not _available(name, ret):
if __opts__.get('test'):
ret['result'] = None
ret['comment'] = 'Service {0} not present; if created in this state run, it would have been started'.format(name)
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# lot of custom init script won't or mis implement the status
# command, so it is just an indicator but can not be fully trusted
before_toggle_status = __salt__['service.status'](name, sig)
if 'service.enabled' in __salt__:
before_toggle_enable_status = __salt__['service.enabled'](name)
else:
before_toggle_enable_status = True
unmask_ret = {'comment': ''}
if unmask:
unmask_ret = unmasked(name, unmask_runtime)
# See if the service is already running
if before_toggle_status:
ret['comment'] = '\n'.join(
[_f for _f in ['The service {0} is already running'.format(name),
unmask_ret['comment']] if _f]
)
if enable is True and not before_toggle_enable_status:
ret.update(_enable(name, None, skip_verify=False, **kwargs))
elif enable is False and before_toggle_enable_status:
ret.update(_disable(name, None, skip_verify=False, **kwargs))
return ret
# Run the tests
if __opts__['test']:
ret['result'] = None
ret['comment'] = '\n'.join(
[_f for _f in ['Service {0} is set to start'.format(name),
unmask_ret['comment']] if _f])
return ret
# Conditionally add systemd-specific args to call to service.start
start_kwargs, warnings = \
_get_systemd_only(__salt__['service.start'], locals())
if warnings:
ret.setdefault('warnings', []).extend(warnings)
if salt.utils.platform.is_windows():
for arg in ['timeout', 'with_deps', 'with_parents']:
if kwargs.get(arg, False):
start_kwargs.update({arg: kwargs.get(arg)})
try:
func_ret = __salt__['service.start'](name, **start_kwargs)
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
if not func_ret:
ret['result'] = False
ret['comment'] = 'Service {0} failed to start'.format(name)
if enable is True:
ret.update(_enable(name, False, result=False, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, False, result=False, skip_verify=False, **kwargs))
return ret
if init_delay:
time.sleep(init_delay)
# only force a change state if we have explicitly detected them
after_toggle_status = __salt__['service.status'](name, sig)
if 'service.enabled' in __salt__:
after_toggle_enable_status = __salt__['service.enabled'](name)
else:
after_toggle_enable_status = True
if (
(before_toggle_enable_status != after_toggle_enable_status) or
(before_toggle_status != after_toggle_status)
) and not ret.get('changes', {}):
ret['changes'][name] = after_toggle_status
if after_toggle_status:
ret['comment'] = 'Started Service {0}'.format(name)
else:
ret['comment'] = 'Service {0} failed to start'.format(name)
ret['result'] = False
if enable is True:
ret.update(_enable(name, after_toggle_status, result=after_toggle_status, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, after_toggle_status, result=after_toggle_status, skip_verify=False, **kwargs))
if init_delay:
ret['comment'] = (
'{0}\nDelayed return for {1} seconds'
.format(ret['comment'], init_delay)
)
if unmask:
ret['comment'] = '\n'.join([ret['comment'], unmask_ret['comment']])
return ret
def enabled(name,
skip_verify=False,
**kwargs):
'''
Ensure that the service is enabled on boot, only use this state if you
don't want to manage the running process, remember that if you want to
enable a running service to use the enable: True option for the running
or dead function.
name
The name of the init or rc script used to manage the service
skip_verify
Skip verifying that the service is available before enabling it.
``True`` will skip the verification. The default is ``False``,
which will ensure the service is available before enabling it.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
ret.update(_enable(name, None, skip_verify=skip_verify, **kwargs))
return ret
def disabled(name,
skip_verify=False,
**kwargs):
'''
Ensure that the service is disabled on boot, only use this state if you
don't want to manage the running process, remember that if you want to
disable a service to use the enable: False option for the running or dead
function.
name
The name of the init or rc script used to manage the service
skip_verify
Skip verifying that the service is available before disabling it.
``True`` will skip the verification. The default is ``False``,
which will ensure the service is available before disabling it.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
ret.update(_disable(name, None, skip_verify=skip_verify, **kwargs))
return ret
def masked(name, runtime=False):
'''
.. versionadded:: 2017.7.0
.. note::
This state is only available on minions which use systemd_.
Ensures that the named service is masked (i.e. prevented from being
started).
name
Name of the service to mask
runtime : False
By default, this state will manage an indefinite mask for the named
service. Set this argument to ``True`` to runtime mask the service.
.. note::
It is possible for a service to have both indefinite and runtime masks
set for it. Therefore, this state will manage a runtime or indefinite
mask independently of each other. This means that if the service is
already indefinitely masked, running this state with ``runtime`` set to
``True`` will _not_ remove the indefinite mask before setting a runtime
mask. In these cases, if it is desirable to ensure that the service is
runtime masked and not indefinitely masked, pair this state with a
:py:func:`service.unmasked <salt.states.service.unmasked>` state, like
so:
.. code-block:: yaml
mask_runtime_foo:
service.masked:
- name: foo
- runtime: True
unmask_indefinite_foo:
service.unmasked:
- name: foo
- runtime: False
.. _systemd: https://freedesktop.org/wiki/Software/systemd/
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if 'service.masked' not in __salt__:
ret['comment'] = 'Service masking not available on this minion'
ret['result'] = False
return ret
mask_type = 'runtime masked' if runtime else 'masked'
expected_changes = {mask_type: {'old': False, 'new': True}}
try:
if __salt__['service.masked'](name, runtime):
ret['comment'] = 'Service {0} is already {1}'.format(
name,
mask_type,
)
return ret
if __opts__['test']:
ret['result'] = None
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} would be {1}'.format(name, mask_type)
return ret
__salt__['service.mask'](name, runtime)
if __salt__['service.masked'](name, runtime):
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} was {1}'.format(name, mask_type)
else:
ret['comment'] = 'Failed to mask service {0}'.format(name)
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
def unmasked(name, runtime=False):
'''
.. versionadded:: 2017.7.0
.. note::
This state is only available on minions which use systemd_.
Ensures that the named service is unmasked
name
Name of the service to unmask
runtime : False
By default, this state will manage an indefinite mask for the named
service. Set this argument to ``True`` to ensure that the service is
runtime masked.
.. note::
It is possible for a service to have both indefinite and runtime masks
set for it. Therefore, this state will manage a runtime or indefinite
mask independently of each other. This means that if the service is
indefinitely masked, running this state with ``runtime`` set to
``True`` will _not_ remove the indefinite mask.
.. _systemd: https://freedesktop.org/wiki/Software/systemd/
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if 'service.masked' not in __salt__:
ret['comment'] = 'Service masking not available on this minion'
ret['result'] = False
return ret
mask_type = 'runtime masked' if runtime else 'masked'
action = 'runtime unmasked' if runtime else 'unmasked'
expected_changes = {mask_type: {'old': True, 'new': False}}
try:
if not __salt__['service.masked'](name, runtime):
ret['comment'] = 'Service {0} was already {1}'.format(name, action)
return ret
if __opts__['test']:
ret['result'] = None
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} would be {1}'.format(name, action)
return ret
__salt__['service.unmask'](name, runtime)
if not __salt__['service.masked'](name, runtime):
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} was {1}'.format(name, action)
else:
ret['comment'] = 'Failed to unmask service {0}'.format(name)
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
def mod_watch(name,
sfun=None,
sig=None,
full_restart=False,
init_delay=None,
force=False,
**kwargs):
'''
The service watcher, called to invoke the watch command.
When called, it will restart or reload the named service.
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the watching service.
(i.e. ``service.running``)
name
The name of the init or rc script used to manage the service
sfun
The original function which triggered the mod_watch call
(`service.running`, for example).
sig
The string to search for when looking for the service process with ps
reload
If True use reload instead of the default restart. If value is a list of
requisites; reload only if all watched changes are contained in the reload list.
Otherwise watch will restart.
full_restart
Use service.full_restart instead of restart.
When set, reload the service instead of restarting it.
(i.e. ``service nginx reload``)
full_restart
Perform a full stop/start of a service by passing ``--full-restart``.
This option is ignored if ``reload`` is set and is supported by only a few
:py:func:`service modules <salt.modules.service>`.
force
Use service.force_reload instead of reload (needs reload to be set to True)
init_delay
Add a sleep command (in seconds) before the service is restarted/reloaded
'''
reload_ = kwargs.pop('reload', False)
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
past_participle = None
if sfun == 'dead':
verb = 'stop'
past_participle = verb + 'ped'
if __salt__['service.status'](name, sig):
func = __salt__['service.stop']
else:
ret['result'] = True
ret['comment'] = 'Service is already {0}'.format(past_participle)
return ret
elif sfun == 'running':
if __salt__['service.status'](name, sig):
if 'service.reload' in __salt__ and reload_:
if isinstance(reload_, list):
only_reload_needed = True
for watch_item in kwargs['__reqs__']['watch']:
if __running__[_gen_tag(watch_item)]['changes']:
match_found = False
for this_reload in reload_:
for state, id_ in six.iteritems(this_reload):
if state == watch_item['state'] \
and id_ == watch_item['__id__']:
match_found = True
if not match_found:
only_reload_needed = False
if only_reload_needed:
if 'service.force_reload' in __salt__ and force:
func = __salt__['service.force_reload']
verb = 'forcefully reload'
else:
func = __salt__['service.reload']
verb = 'reload'
else:
if 'service.full_restart' in __salt__ and full_restart:
func = __salt__['service.full_restart']
verb = 'fully restart'
else:
func = __salt__['service.restart']
verb = 'restart'
else:
if 'service.force_reload' in __salt__ and force:
func = __salt__['service.force_reload']
verb = 'forcefully reload'
else:
func = __salt__['service.reload']
verb = 'reload'
elif 'service.full_restart' in __salt__ and full_restart:
func = __salt__['service.full_restart']
verb = 'fully restart'
else:
func = __salt__['service.restart']
verb = 'restart'
else:
func = __salt__['service.start']
verb = 'start'
if not past_participle:
past_participle = verb + 'ed'
else:
ret['comment'] = 'Unable to trigger watch for service.{0}'.format(sfun)
ret['result'] = False
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service is set to be {0}'.format(past_participle)
return ret
if verb == 'start' and 'service.stop' in __salt__:
# stop service before start
__salt__['service.stop'](name)
func_kwargs, warnings = _get_systemd_only(func, kwargs)
if warnings:
ret.setdefault('warnings', []).extend(warnings)
try:
result = func(name, **func_kwargs)
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
if init_delay:
time.sleep(init_delay)
ret['changes'] = {name: result}
ret['result'] = result
ret['comment'] = 'Service {0}'.format(past_participle) if result else \
'Failed to {0} the service'.format(verb)
return ret
|
saltstack/salt
|
salt/states/service.py
|
enabled
|
python
|
def enabled(name,
skip_verify=False,
**kwargs):
'''
Ensure that the service is enabled on boot, only use this state if you
don't want to manage the running process, remember that if you want to
enable a running service to use the enable: True option for the running
or dead function.
name
The name of the init or rc script used to manage the service
skip_verify
Skip verifying that the service is available before enabling it.
``True`` will skip the verification. The default is ``False``,
which will ensure the service is available before enabling it.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
ret.update(_enable(name, None, skip_verify=skip_verify, **kwargs))
return ret
|
Ensure that the service is enabled on boot, only use this state if you
don't want to manage the running process, remember that if you want to
enable a running service to use the enable: True option for the running
or dead function.
name
The name of the init or rc script used to manage the service
skip_verify
Skip verifying that the service is available before enabling it.
``True`` will skip the verification. The default is ``False``,
which will ensure the service is available before enabling it.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/service.py#L654-L677
|
[
"def _enable(name, started, result=True, skip_verify=False, **kwargs):\n '''\n Enable the service\n '''\n ret = {}\n\n if not skip_verify:\n # is service available?\n try:\n if not _available(name, ret):\n return ret\n except CommandExecutionError as exc:\n ret['result'] = False\n ret['comment'] = exc.strerror\n return ret\n\n # Set default expected result\n ret['result'] = result\n\n # Check to see if this minion supports enable\n if 'service.enable' not in __salt__ or 'service.enabled' not in __salt__:\n if started is True:\n ret['comment'] = ('Enable is not available on this minion,'\n ' service {0} started').format(name)\n elif started is None:\n ret['comment'] = ('Enable is not available on this minion,'\n ' service {0} is in the desired state'\n ).format(name)\n else:\n ret['comment'] = ('Enable is not available on this minion,'\n ' service {0} is dead').format(name)\n return ret\n\n # Service can be enabled\n before_toggle_enable_status = __salt__['service.enabled'](name, **kwargs)\n if before_toggle_enable_status:\n # Service is enabled\n if started is True:\n ret['comment'] = ('Service {0} is already enabled,'\n ' and is running').format(name)\n elif started is None:\n # always be sure in this case to reset the changes dict\n ret['changes'] = {}\n ret['comment'] = ('Service {0} is already enabled,'\n ' and is in the desired state').format(name)\n else:\n ret['comment'] = ('Service {0} is already enabled,'\n ' and is dead').format(name)\n return ret\n\n # Service needs to be enabled\n if __opts__['test']:\n ret['result'] = None\n ret['comment'] = 'Service {0} set to be enabled'.format(name)\n return ret\n\n try:\n if __salt__['service.enable'](name, **kwargs):\n # Service has been enabled\n ret['changes'] = {}\n after_toggle_enable_status = __salt__['service.enabled'](\n name,\n **kwargs)\n # on upstart, certain services like apparmor will always return\n # False, even if correctly activated\n # do not trigger a change\n if before_toggle_enable_status != after_toggle_enable_status:\n ret['changes'][name] = True\n if started is True:\n ret['comment'] = ('Service {0} has been enabled,'\n ' and is running').format(name)\n elif started is None:\n ret['comment'] = ('Service {0} has been enabled,'\n ' and is in the desired state').format(name)\n else:\n ret['comment'] = ('Service {0} has been enabled,'\n ' and is dead').format(name)\n return ret\n except CommandExecutionError as exc:\n enable_error = exc.strerror\n else:\n enable_error = False\n\n # Service failed to be enabled\n ret['result'] = False\n if started is True:\n ret['comment'] = ('Failed when setting service {0} to start at boot,'\n ' but the service is running').format(name)\n elif started is None:\n ret['comment'] = ('Failed when setting service {0} to start at boot,'\n ' but the service was already running').format(name)\n else:\n ret['comment'] = ('Failed when setting service {0} to start at boot,'\n ' and the service is dead').format(name)\n\n if enable_error:\n ret['comment'] += '. Additional information follows:\\n\\n{0}'.format(\n enable_error\n )\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Starting or restarting of services and daemons
==============================================
Services are defined as system daemons and are typically launched using system
init or rc scripts. This service state uses whichever service module is loaded
on the minion with the virtualname of ``service``. Services can be defined as
either running or dead.
If you need to know if your init system is supported, see the list of supported
:mod:`service modules <salt.modules.service.py>` for your desired init system
(systemd, sysvinit, launchctl, etc.).
Note that Salt's service execution module, and therefore this service state,
uses OS grains to ascertain which service module should be loaded and used to
execute service functions. As existing distributions change init systems or
new distributions are created, OS detection can sometimes be incomplete.
If your service states are running into trouble with init system detection,
please see the :ref:`Overriding Virtual Module Providers <module-provider-override>`
section of Salt's module documentation to work around possible errors.
.. note::
The current status of a service is determined by the return code of the init/rc
script status command. A status return code of 0 it is considered running. Any
other return code is considered dead.
.. code-block:: yaml
httpd:
service.running: []
The service can also be set to start at runtime via the enable option:
.. code-block:: yaml
openvpn:
service.running:
- enable: True
By default if a service is triggered to refresh due to a watch statement the
service is restarted. If the desired behavior is to reload the service, then
set the reload value to True:
.. code-block:: yaml
redis:
service.running:
- enable: True
- reload: True
- watch:
- pkg: redis
.. note::
More details regarding ``watch`` can be found in the
:ref:`Requisites <requisites>` documentation.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
# Import Salt libs
import salt.utils.data
import salt.utils.platform
from salt.utils.args import get_function_argspec as _argspec
from salt.exceptions import CommandExecutionError
from salt.state import _gen_tag
# Import 3rd-party libs
from salt.ext import six
SYSTEMD_ONLY = ('no_block', 'unmask', 'unmask_runtime')
__virtualname__ = 'service'
def __virtual__():
'''
Only make these states available if a service provider has been detected or
assigned for this minion
'''
if 'service.start' in __salt__:
return __virtualname__
else:
return (False, 'No service execution module loaded: '
'check support for service management on {0} '
''.format(__grains__.get('osfinger', __grains__['os']))
)
# Double-asterisk deliberately not used here
def _get_systemd_only(func, kwargs):
ret = {}
warnings = []
valid_args = _argspec(func).args
for systemd_arg in SYSTEMD_ONLY:
arg_val = kwargs.get(systemd_arg, False)
if arg_val:
if systemd_arg in valid_args:
ret[systemd_arg] = arg_val
else:
warnings.append(
'The \'{0}\' argument is not supported by this '
'platform/action'.format(systemd_arg)
)
return ret, warnings
def _enabled_used_error(ret):
'''
Warn of potential typo.
'''
ret['result'] = False
ret['comment'] = (
'Service {0} uses non-existent option "enabled". ' +
'Perhaps "enable" option was intended?'
).format(ret['name'])
return ret
def _enable(name, started, result=True, skip_verify=False, **kwargs):
'''
Enable the service
'''
ret = {}
if not skip_verify:
# is service available?
try:
if not _available(name, ret):
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# Set default expected result
ret['result'] = result
# Check to see if this minion supports enable
if 'service.enable' not in __salt__ or 'service.enabled' not in __salt__:
if started is True:
ret['comment'] = ('Enable is not available on this minion,'
' service {0} started').format(name)
elif started is None:
ret['comment'] = ('Enable is not available on this minion,'
' service {0} is in the desired state'
).format(name)
else:
ret['comment'] = ('Enable is not available on this minion,'
' service {0} is dead').format(name)
return ret
# Service can be enabled
before_toggle_enable_status = __salt__['service.enabled'](name, **kwargs)
if before_toggle_enable_status:
# Service is enabled
if started is True:
ret['comment'] = ('Service {0} is already enabled,'
' and is running').format(name)
elif started is None:
# always be sure in this case to reset the changes dict
ret['changes'] = {}
ret['comment'] = ('Service {0} is already enabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} is already enabled,'
' and is dead').format(name)
return ret
# Service needs to be enabled
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service {0} set to be enabled'.format(name)
return ret
try:
if __salt__['service.enable'](name, **kwargs):
# Service has been enabled
ret['changes'] = {}
after_toggle_enable_status = __salt__['service.enabled'](
name,
**kwargs)
# on upstart, certain services like apparmor will always return
# False, even if correctly activated
# do not trigger a change
if before_toggle_enable_status != after_toggle_enable_status:
ret['changes'][name] = True
if started is True:
ret['comment'] = ('Service {0} has been enabled,'
' and is running').format(name)
elif started is None:
ret['comment'] = ('Service {0} has been enabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} has been enabled,'
' and is dead').format(name)
return ret
except CommandExecutionError as exc:
enable_error = exc.strerror
else:
enable_error = False
# Service failed to be enabled
ret['result'] = False
if started is True:
ret['comment'] = ('Failed when setting service {0} to start at boot,'
' but the service is running').format(name)
elif started is None:
ret['comment'] = ('Failed when setting service {0} to start at boot,'
' but the service was already running').format(name)
else:
ret['comment'] = ('Failed when setting service {0} to start at boot,'
' and the service is dead').format(name)
if enable_error:
ret['comment'] += '. Additional information follows:\n\n{0}'.format(
enable_error
)
return ret
def _disable(name, started, result=True, skip_verify=False, **kwargs):
'''
Disable the service
'''
ret = {}
if not skip_verify:
# is service available?
try:
if not _available(name, ret):
ret['result'] = True
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# Set default expected result
ret['result'] = result
# is enable/disable available?
if 'service.disable' not in __salt__ or 'service.disabled' not in __salt__:
if started is True:
ret['comment'] = ('Disable is not available on this minion,'
' service {0} started').format(name)
elif started is None:
ret['comment'] = ('Disable is not available on this minion,'
' service {0} is in the desired state'
).format(name)
else:
ret['comment'] = ('Disable is not available on this minion,'
' service {0} is dead').format(name)
return ret
# Service can be disabled
if salt.utils.platform.is_windows():
# service.disabled in Windows returns True for services that are set to
# Manual start, so we need to check specifically for Disabled
before_toggle_disable_status = __salt__['service.info'](name)['StartType'] in ['Disabled']
else:
before_toggle_disable_status = __salt__['service.disabled'](name)
if before_toggle_disable_status:
# Service is disabled
if started is True:
ret['comment'] = ('Service {0} is already disabled,'
' and is running').format(name)
elif started is None:
# always be sure in this case to reset the changes dict
ret['changes'] = {}
ret['comment'] = ('Service {0} is already disabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} is already disabled,'
' and is dead').format(name)
return ret
# Service needs to be disabled
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service {0} set to be disabled'.format(name)
return ret
if __salt__['service.disable'](name, **kwargs):
# Service has been disabled
ret['changes'] = {}
after_toggle_disable_status = __salt__['service.disabled'](name)
# on upstart, certain services like apparmor will always return
# False, even if correctly activated
# do not trigger a change
if before_toggle_disable_status != after_toggle_disable_status:
ret['changes'][name] = True
if started is True:
ret['comment'] = ('Service {0} has been disabled,'
' and is running').format(name)
elif started is None:
ret['comment'] = ('Service {0} has been disabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} has been disabled,'
' and is dead').format(name)
return ret
# Service failed to be disabled
ret['result'] = False
if started is True:
ret['comment'] = ('Failed when setting service {0} to not start'
' at boot, and is running').format(name)
elif started is None:
ret['comment'] = ('Failed when setting service {0} to not start'
' at boot, but the service was already running'
).format(name)
else:
ret['comment'] = ('Failed when setting service {0} to not start'
' at boot, and the service is dead').format(name)
return ret
def _available(name, ret):
'''
Check if the service is available
'''
avail = False
if 'service.available' in __salt__:
avail = __salt__['service.available'](name)
elif 'service.get_all' in __salt__:
avail = name in __salt__['service.get_all']()
if not avail:
ret['result'] = False
ret['comment'] = 'The named service {0} is not available'.format(name)
return avail
def running(name,
enable=None,
sig=None,
init_delay=None,
no_block=False,
unmask=False,
unmask_runtime=False,
**kwargs):
'''
Ensure that the service is running
name
The name of the init or rc script used to manage the service
enable
Set the service to be enabled at boot time, ``True`` sets the service
to be enabled, ``False`` sets the named service to be disabled. The
default is ``None``, which does not enable or disable anything.
sig
The string to search for when looking for the service process with ps
init_delay
Some services may not be truly available for a short period after their
startup script indicates to the system that they are. Provide an
'init_delay' to specify that this state should wait an additional given
number of seconds after a service has started before returning. Useful
for requisite states wherein a dependent state might assume a service
has started but is not yet fully initialized.
no_block : False
**For systemd minions only.** Starts the service using ``--no-block``.
.. versionadded:: 2017.7.0
unmask : False
**For systemd minions only.** Set to ``True`` to remove an indefinite
mask before attempting to start the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
making any changes. This behavior is no longer the default.
unmask_runtime : False
**For systemd minions only.** Set to ``True`` to remove a runtime mask
before attempting to start the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
making any changes. This behavior is no longer the default.
.. note::
``watch`` can be used with service.running to restart a service when
another state changes ( example: a file.managed state that creates the
service's config file ). More details regarding ``watch`` can be found
in the :ref:`Requisites <requisites>` documentation.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
# Check for common error: using enabled option instead of enable
if 'enabled' in kwargs:
return _enabled_used_error(ret)
# Convert enable to boolean in case user passed a string value
if isinstance(enable, six.string_types):
enable = salt.utils.data.is_true(enable)
# Check if the service is available
try:
if not _available(name, ret):
if __opts__.get('test'):
ret['result'] = None
ret['comment'] = 'Service {0} not present; if created in this state run, it would have been started'.format(name)
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# lot of custom init script won't or mis implement the status
# command, so it is just an indicator but can not be fully trusted
before_toggle_status = __salt__['service.status'](name, sig)
if 'service.enabled' in __salt__:
before_toggle_enable_status = __salt__['service.enabled'](name)
else:
before_toggle_enable_status = True
unmask_ret = {'comment': ''}
if unmask:
unmask_ret = unmasked(name, unmask_runtime)
# See if the service is already running
if before_toggle_status:
ret['comment'] = '\n'.join(
[_f for _f in ['The service {0} is already running'.format(name),
unmask_ret['comment']] if _f]
)
if enable is True and not before_toggle_enable_status:
ret.update(_enable(name, None, skip_verify=False, **kwargs))
elif enable is False and before_toggle_enable_status:
ret.update(_disable(name, None, skip_verify=False, **kwargs))
return ret
# Run the tests
if __opts__['test']:
ret['result'] = None
ret['comment'] = '\n'.join(
[_f for _f in ['Service {0} is set to start'.format(name),
unmask_ret['comment']] if _f])
return ret
# Conditionally add systemd-specific args to call to service.start
start_kwargs, warnings = \
_get_systemd_only(__salt__['service.start'], locals())
if warnings:
ret.setdefault('warnings', []).extend(warnings)
if salt.utils.platform.is_windows():
for arg in ['timeout', 'with_deps', 'with_parents']:
if kwargs.get(arg, False):
start_kwargs.update({arg: kwargs.get(arg)})
try:
func_ret = __salt__['service.start'](name, **start_kwargs)
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
if not func_ret:
ret['result'] = False
ret['comment'] = 'Service {0} failed to start'.format(name)
if enable is True:
ret.update(_enable(name, False, result=False, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, False, result=False, skip_verify=False, **kwargs))
return ret
if init_delay:
time.sleep(init_delay)
# only force a change state if we have explicitly detected them
after_toggle_status = __salt__['service.status'](name, sig)
if 'service.enabled' in __salt__:
after_toggle_enable_status = __salt__['service.enabled'](name)
else:
after_toggle_enable_status = True
if (
(before_toggle_enable_status != after_toggle_enable_status) or
(before_toggle_status != after_toggle_status)
) and not ret.get('changes', {}):
ret['changes'][name] = after_toggle_status
if after_toggle_status:
ret['comment'] = 'Started Service {0}'.format(name)
else:
ret['comment'] = 'Service {0} failed to start'.format(name)
ret['result'] = False
if enable is True:
ret.update(_enable(name, after_toggle_status, result=after_toggle_status, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, after_toggle_status, result=after_toggle_status, skip_verify=False, **kwargs))
if init_delay:
ret['comment'] = (
'{0}\nDelayed return for {1} seconds'
.format(ret['comment'], init_delay)
)
if unmask:
ret['comment'] = '\n'.join([ret['comment'], unmask_ret['comment']])
return ret
def dead(name,
enable=None,
sig=None,
init_delay=None,
**kwargs):
'''
Ensure that the named service is dead by stopping the service if it is running
name
The name of the init or rc script used to manage the service
enable
Set the service to be enabled at boot time, ``True`` sets the service
to be enabled, ``False`` sets the named service to be disabled. The
default is ``None``, which does not enable or disable anything.
sig
The string to search for when looking for the service process with ps
init_delay
Add a sleep command (in seconds) before the check to make sure service
is killed.
.. versionadded:: 2017.7.0
no_block : False
**For systemd minions only.** Stops the service using ``--no-block``.
.. versionadded:: 2017.7.0
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
# Check for common error: using enabled option instead of enable
if 'enabled' in kwargs:
return _enabled_used_error(ret)
# Convert enable to boolean in case user passed a string value
if isinstance(enable, six.string_types):
enable = salt.utils.data.is_true(enable)
# Check if the service is available
try:
if not _available(name, ret):
if __opts__.get('test'):
ret['result'] = None
ret['comment'] = 'Service {0} not present; if created in this state run, it would have been stopped'.format(name)
else:
# A non-available service is OK here, don't let the state fail
# because of it.
ret['result'] = True
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# lot of custom init script won't or mis implement the status
# command, so it is just an indicator but can not be fully trusted
before_toggle_status = __salt__['service.status'](name, sig)
if 'service.enabled' in __salt__:
if salt.utils.platform.is_windows():
# service.enabled in Windows returns True for services that are set
# to Auto start, but services set to Manual can also be disabled
before_toggle_enable_status = __salt__['service.info'](name)['StartType'] in ['Auto', 'Manual']
else:
before_toggle_enable_status = __salt__['service.enabled'](name)
else:
before_toggle_enable_status = True
# See if the service is already dead
if not before_toggle_status:
ret['comment'] = 'The service {0} is already dead'.format(name)
if enable is True and not before_toggle_enable_status:
ret.update(_enable(name, None, skip_verify=False, **kwargs))
elif enable is False and before_toggle_enable_status:
ret.update(_disable(name, None, skip_verify=False, **kwargs))
return ret
# Run the tests
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service {0} is set to be killed'.format(name)
return ret
# Conditionally add systemd-specific args to call to service.start
stop_kwargs, warnings = _get_systemd_only(__salt__['service.stop'], kwargs)
if warnings:
ret.setdefault('warnings', []).extend(warnings)
if salt.utils.platform.is_windows():
for arg in ['timeout', 'with_deps', 'with_parents']:
if kwargs.get(arg, False):
stop_kwargs.update({arg: kwargs.get(arg)})
func_ret = __salt__['service.stop'](name, **stop_kwargs)
if not func_ret:
ret['result'] = False
ret['comment'] = 'Service {0} failed to die'.format(name)
if enable is True:
ret.update(_enable(name, True, result=False, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, True, result=False, skip_verify=False, **kwargs))
return ret
if init_delay:
time.sleep(init_delay)
# only force a change state if we have explicitly detected them
after_toggle_status = __salt__['service.status'](name)
if 'service.enabled' in __salt__:
after_toggle_enable_status = __salt__['service.enabled'](name)
else:
after_toggle_enable_status = True
if (
(before_toggle_enable_status != after_toggle_enable_status) or
(before_toggle_status != after_toggle_status)
) and not ret.get('changes', {}):
ret['changes'][name] = after_toggle_status
# be sure to stop, in case we mis detected in the check
if after_toggle_status:
ret['result'] = False
ret['comment'] = 'Service {0} failed to die'.format(name)
else:
ret['comment'] = 'Service {0} was killed'.format(name)
if enable is True:
ret.update(_enable(name, after_toggle_status, result=not after_toggle_status, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, after_toggle_status, result=not after_toggle_status, skip_verify=False, **kwargs))
return ret
def disabled(name,
skip_verify=False,
**kwargs):
'''
Ensure that the service is disabled on boot, only use this state if you
don't want to manage the running process, remember that if you want to
disable a service to use the enable: False option for the running or dead
function.
name
The name of the init or rc script used to manage the service
skip_verify
Skip verifying that the service is available before disabling it.
``True`` will skip the verification. The default is ``False``,
which will ensure the service is available before disabling it.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
ret.update(_disable(name, None, skip_verify=skip_verify, **kwargs))
return ret
def masked(name, runtime=False):
'''
.. versionadded:: 2017.7.0
.. note::
This state is only available on minions which use systemd_.
Ensures that the named service is masked (i.e. prevented from being
started).
name
Name of the service to mask
runtime : False
By default, this state will manage an indefinite mask for the named
service. Set this argument to ``True`` to runtime mask the service.
.. note::
It is possible for a service to have both indefinite and runtime masks
set for it. Therefore, this state will manage a runtime or indefinite
mask independently of each other. This means that if the service is
already indefinitely masked, running this state with ``runtime`` set to
``True`` will _not_ remove the indefinite mask before setting a runtime
mask. In these cases, if it is desirable to ensure that the service is
runtime masked and not indefinitely masked, pair this state with a
:py:func:`service.unmasked <salt.states.service.unmasked>` state, like
so:
.. code-block:: yaml
mask_runtime_foo:
service.masked:
- name: foo
- runtime: True
unmask_indefinite_foo:
service.unmasked:
- name: foo
- runtime: False
.. _systemd: https://freedesktop.org/wiki/Software/systemd/
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if 'service.masked' not in __salt__:
ret['comment'] = 'Service masking not available on this minion'
ret['result'] = False
return ret
mask_type = 'runtime masked' if runtime else 'masked'
expected_changes = {mask_type: {'old': False, 'new': True}}
try:
if __salt__['service.masked'](name, runtime):
ret['comment'] = 'Service {0} is already {1}'.format(
name,
mask_type,
)
return ret
if __opts__['test']:
ret['result'] = None
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} would be {1}'.format(name, mask_type)
return ret
__salt__['service.mask'](name, runtime)
if __salt__['service.masked'](name, runtime):
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} was {1}'.format(name, mask_type)
else:
ret['comment'] = 'Failed to mask service {0}'.format(name)
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
def unmasked(name, runtime=False):
'''
.. versionadded:: 2017.7.0
.. note::
This state is only available on minions which use systemd_.
Ensures that the named service is unmasked
name
Name of the service to unmask
runtime : False
By default, this state will manage an indefinite mask for the named
service. Set this argument to ``True`` to ensure that the service is
runtime masked.
.. note::
It is possible for a service to have both indefinite and runtime masks
set for it. Therefore, this state will manage a runtime or indefinite
mask independently of each other. This means that if the service is
indefinitely masked, running this state with ``runtime`` set to
``True`` will _not_ remove the indefinite mask.
.. _systemd: https://freedesktop.org/wiki/Software/systemd/
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if 'service.masked' not in __salt__:
ret['comment'] = 'Service masking not available on this minion'
ret['result'] = False
return ret
mask_type = 'runtime masked' if runtime else 'masked'
action = 'runtime unmasked' if runtime else 'unmasked'
expected_changes = {mask_type: {'old': True, 'new': False}}
try:
if not __salt__['service.masked'](name, runtime):
ret['comment'] = 'Service {0} was already {1}'.format(name, action)
return ret
if __opts__['test']:
ret['result'] = None
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} would be {1}'.format(name, action)
return ret
__salt__['service.unmask'](name, runtime)
if not __salt__['service.masked'](name, runtime):
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} was {1}'.format(name, action)
else:
ret['comment'] = 'Failed to unmask service {0}'.format(name)
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
def mod_watch(name,
sfun=None,
sig=None,
full_restart=False,
init_delay=None,
force=False,
**kwargs):
'''
The service watcher, called to invoke the watch command.
When called, it will restart or reload the named service.
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the watching service.
(i.e. ``service.running``)
name
The name of the init or rc script used to manage the service
sfun
The original function which triggered the mod_watch call
(`service.running`, for example).
sig
The string to search for when looking for the service process with ps
reload
If True use reload instead of the default restart. If value is a list of
requisites; reload only if all watched changes are contained in the reload list.
Otherwise watch will restart.
full_restart
Use service.full_restart instead of restart.
When set, reload the service instead of restarting it.
(i.e. ``service nginx reload``)
full_restart
Perform a full stop/start of a service by passing ``--full-restart``.
This option is ignored if ``reload`` is set and is supported by only a few
:py:func:`service modules <salt.modules.service>`.
force
Use service.force_reload instead of reload (needs reload to be set to True)
init_delay
Add a sleep command (in seconds) before the service is restarted/reloaded
'''
reload_ = kwargs.pop('reload', False)
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
past_participle = None
if sfun == 'dead':
verb = 'stop'
past_participle = verb + 'ped'
if __salt__['service.status'](name, sig):
func = __salt__['service.stop']
else:
ret['result'] = True
ret['comment'] = 'Service is already {0}'.format(past_participle)
return ret
elif sfun == 'running':
if __salt__['service.status'](name, sig):
if 'service.reload' in __salt__ and reload_:
if isinstance(reload_, list):
only_reload_needed = True
for watch_item in kwargs['__reqs__']['watch']:
if __running__[_gen_tag(watch_item)]['changes']:
match_found = False
for this_reload in reload_:
for state, id_ in six.iteritems(this_reload):
if state == watch_item['state'] \
and id_ == watch_item['__id__']:
match_found = True
if not match_found:
only_reload_needed = False
if only_reload_needed:
if 'service.force_reload' in __salt__ and force:
func = __salt__['service.force_reload']
verb = 'forcefully reload'
else:
func = __salt__['service.reload']
verb = 'reload'
else:
if 'service.full_restart' in __salt__ and full_restart:
func = __salt__['service.full_restart']
verb = 'fully restart'
else:
func = __salt__['service.restart']
verb = 'restart'
else:
if 'service.force_reload' in __salt__ and force:
func = __salt__['service.force_reload']
verb = 'forcefully reload'
else:
func = __salt__['service.reload']
verb = 'reload'
elif 'service.full_restart' in __salt__ and full_restart:
func = __salt__['service.full_restart']
verb = 'fully restart'
else:
func = __salt__['service.restart']
verb = 'restart'
else:
func = __salt__['service.start']
verb = 'start'
if not past_participle:
past_participle = verb + 'ed'
else:
ret['comment'] = 'Unable to trigger watch for service.{0}'.format(sfun)
ret['result'] = False
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service is set to be {0}'.format(past_participle)
return ret
if verb == 'start' and 'service.stop' in __salt__:
# stop service before start
__salt__['service.stop'](name)
func_kwargs, warnings = _get_systemd_only(func, kwargs)
if warnings:
ret.setdefault('warnings', []).extend(warnings)
try:
result = func(name, **func_kwargs)
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
if init_delay:
time.sleep(init_delay)
ret['changes'] = {name: result}
ret['result'] = result
ret['comment'] = 'Service {0}'.format(past_participle) if result else \
'Failed to {0} the service'.format(verb)
return ret
|
saltstack/salt
|
salt/states/service.py
|
disabled
|
python
|
def disabled(name,
skip_verify=False,
**kwargs):
'''
Ensure that the service is disabled on boot, only use this state if you
don't want to manage the running process, remember that if you want to
disable a service to use the enable: False option for the running or dead
function.
name
The name of the init or rc script used to manage the service
skip_verify
Skip verifying that the service is available before disabling it.
``True`` will skip the verification. The default is ``False``,
which will ensure the service is available before disabling it.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
ret.update(_disable(name, None, skip_verify=skip_verify, **kwargs))
return ret
|
Ensure that the service is disabled on boot, only use this state if you
don't want to manage the running process, remember that if you want to
disable a service to use the enable: False option for the running or dead
function.
name
The name of the init or rc script used to manage the service
skip_verify
Skip verifying that the service is available before disabling it.
``True`` will skip the verification. The default is ``False``,
which will ensure the service is available before disabling it.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/service.py#L680-L703
|
[
"def _disable(name, started, result=True, skip_verify=False, **kwargs):\n '''\n Disable the service\n '''\n ret = {}\n\n if not skip_verify:\n # is service available?\n try:\n if not _available(name, ret):\n ret['result'] = True\n return ret\n except CommandExecutionError as exc:\n ret['result'] = False\n ret['comment'] = exc.strerror\n return ret\n\n # Set default expected result\n ret['result'] = result\n\n # is enable/disable available?\n if 'service.disable' not in __salt__ or 'service.disabled' not in __salt__:\n if started is True:\n ret['comment'] = ('Disable is not available on this minion,'\n ' service {0} started').format(name)\n elif started is None:\n ret['comment'] = ('Disable is not available on this minion,'\n ' service {0} is in the desired state'\n ).format(name)\n else:\n ret['comment'] = ('Disable is not available on this minion,'\n ' service {0} is dead').format(name)\n return ret\n\n # Service can be disabled\n if salt.utils.platform.is_windows():\n # service.disabled in Windows returns True for services that are set to\n # Manual start, so we need to check specifically for Disabled\n before_toggle_disable_status = __salt__['service.info'](name)['StartType'] in ['Disabled']\n else:\n before_toggle_disable_status = __salt__['service.disabled'](name)\n if before_toggle_disable_status:\n # Service is disabled\n if started is True:\n ret['comment'] = ('Service {0} is already disabled,'\n ' and is running').format(name)\n elif started is None:\n # always be sure in this case to reset the changes dict\n ret['changes'] = {}\n ret['comment'] = ('Service {0} is already disabled,'\n ' and is in the desired state').format(name)\n else:\n ret['comment'] = ('Service {0} is already disabled,'\n ' and is dead').format(name)\n return ret\n\n # Service needs to be disabled\n if __opts__['test']:\n ret['result'] = None\n ret['comment'] = 'Service {0} set to be disabled'.format(name)\n return ret\n\n if __salt__['service.disable'](name, **kwargs):\n # Service has been disabled\n ret['changes'] = {}\n after_toggle_disable_status = __salt__['service.disabled'](name)\n # on upstart, certain services like apparmor will always return\n # False, even if correctly activated\n # do not trigger a change\n if before_toggle_disable_status != after_toggle_disable_status:\n ret['changes'][name] = True\n if started is True:\n ret['comment'] = ('Service {0} has been disabled,'\n ' and is running').format(name)\n elif started is None:\n ret['comment'] = ('Service {0} has been disabled,'\n ' and is in the desired state').format(name)\n else:\n ret['comment'] = ('Service {0} has been disabled,'\n ' and is dead').format(name)\n return ret\n\n # Service failed to be disabled\n ret['result'] = False\n if started is True:\n ret['comment'] = ('Failed when setting service {0} to not start'\n ' at boot, and is running').format(name)\n elif started is None:\n ret['comment'] = ('Failed when setting service {0} to not start'\n ' at boot, but the service was already running'\n ).format(name)\n else:\n ret['comment'] = ('Failed when setting service {0} to not start'\n ' at boot, and the service is dead').format(name)\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Starting or restarting of services and daemons
==============================================
Services are defined as system daemons and are typically launched using system
init or rc scripts. This service state uses whichever service module is loaded
on the minion with the virtualname of ``service``. Services can be defined as
either running or dead.
If you need to know if your init system is supported, see the list of supported
:mod:`service modules <salt.modules.service.py>` for your desired init system
(systemd, sysvinit, launchctl, etc.).
Note that Salt's service execution module, and therefore this service state,
uses OS grains to ascertain which service module should be loaded and used to
execute service functions. As existing distributions change init systems or
new distributions are created, OS detection can sometimes be incomplete.
If your service states are running into trouble with init system detection,
please see the :ref:`Overriding Virtual Module Providers <module-provider-override>`
section of Salt's module documentation to work around possible errors.
.. note::
The current status of a service is determined by the return code of the init/rc
script status command. A status return code of 0 it is considered running. Any
other return code is considered dead.
.. code-block:: yaml
httpd:
service.running: []
The service can also be set to start at runtime via the enable option:
.. code-block:: yaml
openvpn:
service.running:
- enable: True
By default if a service is triggered to refresh due to a watch statement the
service is restarted. If the desired behavior is to reload the service, then
set the reload value to True:
.. code-block:: yaml
redis:
service.running:
- enable: True
- reload: True
- watch:
- pkg: redis
.. note::
More details regarding ``watch`` can be found in the
:ref:`Requisites <requisites>` documentation.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
# Import Salt libs
import salt.utils.data
import salt.utils.platform
from salt.utils.args import get_function_argspec as _argspec
from salt.exceptions import CommandExecutionError
from salt.state import _gen_tag
# Import 3rd-party libs
from salt.ext import six
SYSTEMD_ONLY = ('no_block', 'unmask', 'unmask_runtime')
__virtualname__ = 'service'
def __virtual__():
'''
Only make these states available if a service provider has been detected or
assigned for this minion
'''
if 'service.start' in __salt__:
return __virtualname__
else:
return (False, 'No service execution module loaded: '
'check support for service management on {0} '
''.format(__grains__.get('osfinger', __grains__['os']))
)
# Double-asterisk deliberately not used here
def _get_systemd_only(func, kwargs):
ret = {}
warnings = []
valid_args = _argspec(func).args
for systemd_arg in SYSTEMD_ONLY:
arg_val = kwargs.get(systemd_arg, False)
if arg_val:
if systemd_arg in valid_args:
ret[systemd_arg] = arg_val
else:
warnings.append(
'The \'{0}\' argument is not supported by this '
'platform/action'.format(systemd_arg)
)
return ret, warnings
def _enabled_used_error(ret):
'''
Warn of potential typo.
'''
ret['result'] = False
ret['comment'] = (
'Service {0} uses non-existent option "enabled". ' +
'Perhaps "enable" option was intended?'
).format(ret['name'])
return ret
def _enable(name, started, result=True, skip_verify=False, **kwargs):
'''
Enable the service
'''
ret = {}
if not skip_verify:
# is service available?
try:
if not _available(name, ret):
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# Set default expected result
ret['result'] = result
# Check to see if this minion supports enable
if 'service.enable' not in __salt__ or 'service.enabled' not in __salt__:
if started is True:
ret['comment'] = ('Enable is not available on this minion,'
' service {0} started').format(name)
elif started is None:
ret['comment'] = ('Enable is not available on this minion,'
' service {0} is in the desired state'
).format(name)
else:
ret['comment'] = ('Enable is not available on this minion,'
' service {0} is dead').format(name)
return ret
# Service can be enabled
before_toggle_enable_status = __salt__['service.enabled'](name, **kwargs)
if before_toggle_enable_status:
# Service is enabled
if started is True:
ret['comment'] = ('Service {0} is already enabled,'
' and is running').format(name)
elif started is None:
# always be sure in this case to reset the changes dict
ret['changes'] = {}
ret['comment'] = ('Service {0} is already enabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} is already enabled,'
' and is dead').format(name)
return ret
# Service needs to be enabled
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service {0} set to be enabled'.format(name)
return ret
try:
if __salt__['service.enable'](name, **kwargs):
# Service has been enabled
ret['changes'] = {}
after_toggle_enable_status = __salt__['service.enabled'](
name,
**kwargs)
# on upstart, certain services like apparmor will always return
# False, even if correctly activated
# do not trigger a change
if before_toggle_enable_status != after_toggle_enable_status:
ret['changes'][name] = True
if started is True:
ret['comment'] = ('Service {0} has been enabled,'
' and is running').format(name)
elif started is None:
ret['comment'] = ('Service {0} has been enabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} has been enabled,'
' and is dead').format(name)
return ret
except CommandExecutionError as exc:
enable_error = exc.strerror
else:
enable_error = False
# Service failed to be enabled
ret['result'] = False
if started is True:
ret['comment'] = ('Failed when setting service {0} to start at boot,'
' but the service is running').format(name)
elif started is None:
ret['comment'] = ('Failed when setting service {0} to start at boot,'
' but the service was already running').format(name)
else:
ret['comment'] = ('Failed when setting service {0} to start at boot,'
' and the service is dead').format(name)
if enable_error:
ret['comment'] += '. Additional information follows:\n\n{0}'.format(
enable_error
)
return ret
def _disable(name, started, result=True, skip_verify=False, **kwargs):
'''
Disable the service
'''
ret = {}
if not skip_verify:
# is service available?
try:
if not _available(name, ret):
ret['result'] = True
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# Set default expected result
ret['result'] = result
# is enable/disable available?
if 'service.disable' not in __salt__ or 'service.disabled' not in __salt__:
if started is True:
ret['comment'] = ('Disable is not available on this minion,'
' service {0} started').format(name)
elif started is None:
ret['comment'] = ('Disable is not available on this minion,'
' service {0} is in the desired state'
).format(name)
else:
ret['comment'] = ('Disable is not available on this minion,'
' service {0} is dead').format(name)
return ret
# Service can be disabled
if salt.utils.platform.is_windows():
# service.disabled in Windows returns True for services that are set to
# Manual start, so we need to check specifically for Disabled
before_toggle_disable_status = __salt__['service.info'](name)['StartType'] in ['Disabled']
else:
before_toggle_disable_status = __salt__['service.disabled'](name)
if before_toggle_disable_status:
# Service is disabled
if started is True:
ret['comment'] = ('Service {0} is already disabled,'
' and is running').format(name)
elif started is None:
# always be sure in this case to reset the changes dict
ret['changes'] = {}
ret['comment'] = ('Service {0} is already disabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} is already disabled,'
' and is dead').format(name)
return ret
# Service needs to be disabled
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service {0} set to be disabled'.format(name)
return ret
if __salt__['service.disable'](name, **kwargs):
# Service has been disabled
ret['changes'] = {}
after_toggle_disable_status = __salt__['service.disabled'](name)
# on upstart, certain services like apparmor will always return
# False, even if correctly activated
# do not trigger a change
if before_toggle_disable_status != after_toggle_disable_status:
ret['changes'][name] = True
if started is True:
ret['comment'] = ('Service {0} has been disabled,'
' and is running').format(name)
elif started is None:
ret['comment'] = ('Service {0} has been disabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} has been disabled,'
' and is dead').format(name)
return ret
# Service failed to be disabled
ret['result'] = False
if started is True:
ret['comment'] = ('Failed when setting service {0} to not start'
' at boot, and is running').format(name)
elif started is None:
ret['comment'] = ('Failed when setting service {0} to not start'
' at boot, but the service was already running'
).format(name)
else:
ret['comment'] = ('Failed when setting service {0} to not start'
' at boot, and the service is dead').format(name)
return ret
def _available(name, ret):
'''
Check if the service is available
'''
avail = False
if 'service.available' in __salt__:
avail = __salt__['service.available'](name)
elif 'service.get_all' in __salt__:
avail = name in __salt__['service.get_all']()
if not avail:
ret['result'] = False
ret['comment'] = 'The named service {0} is not available'.format(name)
return avail
def running(name,
enable=None,
sig=None,
init_delay=None,
no_block=False,
unmask=False,
unmask_runtime=False,
**kwargs):
'''
Ensure that the service is running
name
The name of the init or rc script used to manage the service
enable
Set the service to be enabled at boot time, ``True`` sets the service
to be enabled, ``False`` sets the named service to be disabled. The
default is ``None``, which does not enable or disable anything.
sig
The string to search for when looking for the service process with ps
init_delay
Some services may not be truly available for a short period after their
startup script indicates to the system that they are. Provide an
'init_delay' to specify that this state should wait an additional given
number of seconds after a service has started before returning. Useful
for requisite states wherein a dependent state might assume a service
has started but is not yet fully initialized.
no_block : False
**For systemd minions only.** Starts the service using ``--no-block``.
.. versionadded:: 2017.7.0
unmask : False
**For systemd minions only.** Set to ``True`` to remove an indefinite
mask before attempting to start the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
making any changes. This behavior is no longer the default.
unmask_runtime : False
**For systemd minions only.** Set to ``True`` to remove a runtime mask
before attempting to start the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
making any changes. This behavior is no longer the default.
.. note::
``watch`` can be used with service.running to restart a service when
another state changes ( example: a file.managed state that creates the
service's config file ). More details regarding ``watch`` can be found
in the :ref:`Requisites <requisites>` documentation.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
# Check for common error: using enabled option instead of enable
if 'enabled' in kwargs:
return _enabled_used_error(ret)
# Convert enable to boolean in case user passed a string value
if isinstance(enable, six.string_types):
enable = salt.utils.data.is_true(enable)
# Check if the service is available
try:
if not _available(name, ret):
if __opts__.get('test'):
ret['result'] = None
ret['comment'] = 'Service {0} not present; if created in this state run, it would have been started'.format(name)
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# lot of custom init script won't or mis implement the status
# command, so it is just an indicator but can not be fully trusted
before_toggle_status = __salt__['service.status'](name, sig)
if 'service.enabled' in __salt__:
before_toggle_enable_status = __salt__['service.enabled'](name)
else:
before_toggle_enable_status = True
unmask_ret = {'comment': ''}
if unmask:
unmask_ret = unmasked(name, unmask_runtime)
# See if the service is already running
if before_toggle_status:
ret['comment'] = '\n'.join(
[_f for _f in ['The service {0} is already running'.format(name),
unmask_ret['comment']] if _f]
)
if enable is True and not before_toggle_enable_status:
ret.update(_enable(name, None, skip_verify=False, **kwargs))
elif enable is False and before_toggle_enable_status:
ret.update(_disable(name, None, skip_verify=False, **kwargs))
return ret
# Run the tests
if __opts__['test']:
ret['result'] = None
ret['comment'] = '\n'.join(
[_f for _f in ['Service {0} is set to start'.format(name),
unmask_ret['comment']] if _f])
return ret
# Conditionally add systemd-specific args to call to service.start
start_kwargs, warnings = \
_get_systemd_only(__salt__['service.start'], locals())
if warnings:
ret.setdefault('warnings', []).extend(warnings)
if salt.utils.platform.is_windows():
for arg in ['timeout', 'with_deps', 'with_parents']:
if kwargs.get(arg, False):
start_kwargs.update({arg: kwargs.get(arg)})
try:
func_ret = __salt__['service.start'](name, **start_kwargs)
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
if not func_ret:
ret['result'] = False
ret['comment'] = 'Service {0} failed to start'.format(name)
if enable is True:
ret.update(_enable(name, False, result=False, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, False, result=False, skip_verify=False, **kwargs))
return ret
if init_delay:
time.sleep(init_delay)
# only force a change state if we have explicitly detected them
after_toggle_status = __salt__['service.status'](name, sig)
if 'service.enabled' in __salt__:
after_toggle_enable_status = __salt__['service.enabled'](name)
else:
after_toggle_enable_status = True
if (
(before_toggle_enable_status != after_toggle_enable_status) or
(before_toggle_status != after_toggle_status)
) and not ret.get('changes', {}):
ret['changes'][name] = after_toggle_status
if after_toggle_status:
ret['comment'] = 'Started Service {0}'.format(name)
else:
ret['comment'] = 'Service {0} failed to start'.format(name)
ret['result'] = False
if enable is True:
ret.update(_enable(name, after_toggle_status, result=after_toggle_status, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, after_toggle_status, result=after_toggle_status, skip_verify=False, **kwargs))
if init_delay:
ret['comment'] = (
'{0}\nDelayed return for {1} seconds'
.format(ret['comment'], init_delay)
)
if unmask:
ret['comment'] = '\n'.join([ret['comment'], unmask_ret['comment']])
return ret
def dead(name,
enable=None,
sig=None,
init_delay=None,
**kwargs):
'''
Ensure that the named service is dead by stopping the service if it is running
name
The name of the init or rc script used to manage the service
enable
Set the service to be enabled at boot time, ``True`` sets the service
to be enabled, ``False`` sets the named service to be disabled. The
default is ``None``, which does not enable or disable anything.
sig
The string to search for when looking for the service process with ps
init_delay
Add a sleep command (in seconds) before the check to make sure service
is killed.
.. versionadded:: 2017.7.0
no_block : False
**For systemd minions only.** Stops the service using ``--no-block``.
.. versionadded:: 2017.7.0
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
# Check for common error: using enabled option instead of enable
if 'enabled' in kwargs:
return _enabled_used_error(ret)
# Convert enable to boolean in case user passed a string value
if isinstance(enable, six.string_types):
enable = salt.utils.data.is_true(enable)
# Check if the service is available
try:
if not _available(name, ret):
if __opts__.get('test'):
ret['result'] = None
ret['comment'] = 'Service {0} not present; if created in this state run, it would have been stopped'.format(name)
else:
# A non-available service is OK here, don't let the state fail
# because of it.
ret['result'] = True
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# lot of custom init script won't or mis implement the status
# command, so it is just an indicator but can not be fully trusted
before_toggle_status = __salt__['service.status'](name, sig)
if 'service.enabled' in __salt__:
if salt.utils.platform.is_windows():
# service.enabled in Windows returns True for services that are set
# to Auto start, but services set to Manual can also be disabled
before_toggle_enable_status = __salt__['service.info'](name)['StartType'] in ['Auto', 'Manual']
else:
before_toggle_enable_status = __salt__['service.enabled'](name)
else:
before_toggle_enable_status = True
# See if the service is already dead
if not before_toggle_status:
ret['comment'] = 'The service {0} is already dead'.format(name)
if enable is True and not before_toggle_enable_status:
ret.update(_enable(name, None, skip_verify=False, **kwargs))
elif enable is False and before_toggle_enable_status:
ret.update(_disable(name, None, skip_verify=False, **kwargs))
return ret
# Run the tests
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service {0} is set to be killed'.format(name)
return ret
# Conditionally add systemd-specific args to call to service.start
stop_kwargs, warnings = _get_systemd_only(__salt__['service.stop'], kwargs)
if warnings:
ret.setdefault('warnings', []).extend(warnings)
if salt.utils.platform.is_windows():
for arg in ['timeout', 'with_deps', 'with_parents']:
if kwargs.get(arg, False):
stop_kwargs.update({arg: kwargs.get(arg)})
func_ret = __salt__['service.stop'](name, **stop_kwargs)
if not func_ret:
ret['result'] = False
ret['comment'] = 'Service {0} failed to die'.format(name)
if enable is True:
ret.update(_enable(name, True, result=False, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, True, result=False, skip_verify=False, **kwargs))
return ret
if init_delay:
time.sleep(init_delay)
# only force a change state if we have explicitly detected them
after_toggle_status = __salt__['service.status'](name)
if 'service.enabled' in __salt__:
after_toggle_enable_status = __salt__['service.enabled'](name)
else:
after_toggle_enable_status = True
if (
(before_toggle_enable_status != after_toggle_enable_status) or
(before_toggle_status != after_toggle_status)
) and not ret.get('changes', {}):
ret['changes'][name] = after_toggle_status
# be sure to stop, in case we mis detected in the check
if after_toggle_status:
ret['result'] = False
ret['comment'] = 'Service {0} failed to die'.format(name)
else:
ret['comment'] = 'Service {0} was killed'.format(name)
if enable is True:
ret.update(_enable(name, after_toggle_status, result=not after_toggle_status, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, after_toggle_status, result=not after_toggle_status, skip_verify=False, **kwargs))
return ret
def enabled(name,
skip_verify=False,
**kwargs):
'''
Ensure that the service is enabled on boot, only use this state if you
don't want to manage the running process, remember that if you want to
enable a running service to use the enable: True option for the running
or dead function.
name
The name of the init or rc script used to manage the service
skip_verify
Skip verifying that the service is available before enabling it.
``True`` will skip the verification. The default is ``False``,
which will ensure the service is available before enabling it.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
ret.update(_enable(name, None, skip_verify=skip_verify, **kwargs))
return ret
def masked(name, runtime=False):
'''
.. versionadded:: 2017.7.0
.. note::
This state is only available on minions which use systemd_.
Ensures that the named service is masked (i.e. prevented from being
started).
name
Name of the service to mask
runtime : False
By default, this state will manage an indefinite mask for the named
service. Set this argument to ``True`` to runtime mask the service.
.. note::
It is possible for a service to have both indefinite and runtime masks
set for it. Therefore, this state will manage a runtime or indefinite
mask independently of each other. This means that if the service is
already indefinitely masked, running this state with ``runtime`` set to
``True`` will _not_ remove the indefinite mask before setting a runtime
mask. In these cases, if it is desirable to ensure that the service is
runtime masked and not indefinitely masked, pair this state with a
:py:func:`service.unmasked <salt.states.service.unmasked>` state, like
so:
.. code-block:: yaml
mask_runtime_foo:
service.masked:
- name: foo
- runtime: True
unmask_indefinite_foo:
service.unmasked:
- name: foo
- runtime: False
.. _systemd: https://freedesktop.org/wiki/Software/systemd/
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if 'service.masked' not in __salt__:
ret['comment'] = 'Service masking not available on this minion'
ret['result'] = False
return ret
mask_type = 'runtime masked' if runtime else 'masked'
expected_changes = {mask_type: {'old': False, 'new': True}}
try:
if __salt__['service.masked'](name, runtime):
ret['comment'] = 'Service {0} is already {1}'.format(
name,
mask_type,
)
return ret
if __opts__['test']:
ret['result'] = None
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} would be {1}'.format(name, mask_type)
return ret
__salt__['service.mask'](name, runtime)
if __salt__['service.masked'](name, runtime):
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} was {1}'.format(name, mask_type)
else:
ret['comment'] = 'Failed to mask service {0}'.format(name)
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
def unmasked(name, runtime=False):
'''
.. versionadded:: 2017.7.0
.. note::
This state is only available on minions which use systemd_.
Ensures that the named service is unmasked
name
Name of the service to unmask
runtime : False
By default, this state will manage an indefinite mask for the named
service. Set this argument to ``True`` to ensure that the service is
runtime masked.
.. note::
It is possible for a service to have both indefinite and runtime masks
set for it. Therefore, this state will manage a runtime or indefinite
mask independently of each other. This means that if the service is
indefinitely masked, running this state with ``runtime`` set to
``True`` will _not_ remove the indefinite mask.
.. _systemd: https://freedesktop.org/wiki/Software/systemd/
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if 'service.masked' not in __salt__:
ret['comment'] = 'Service masking not available on this minion'
ret['result'] = False
return ret
mask_type = 'runtime masked' if runtime else 'masked'
action = 'runtime unmasked' if runtime else 'unmasked'
expected_changes = {mask_type: {'old': True, 'new': False}}
try:
if not __salt__['service.masked'](name, runtime):
ret['comment'] = 'Service {0} was already {1}'.format(name, action)
return ret
if __opts__['test']:
ret['result'] = None
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} would be {1}'.format(name, action)
return ret
__salt__['service.unmask'](name, runtime)
if not __salt__['service.masked'](name, runtime):
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} was {1}'.format(name, action)
else:
ret['comment'] = 'Failed to unmask service {0}'.format(name)
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
def mod_watch(name,
sfun=None,
sig=None,
full_restart=False,
init_delay=None,
force=False,
**kwargs):
'''
The service watcher, called to invoke the watch command.
When called, it will restart or reload the named service.
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the watching service.
(i.e. ``service.running``)
name
The name of the init or rc script used to manage the service
sfun
The original function which triggered the mod_watch call
(`service.running`, for example).
sig
The string to search for when looking for the service process with ps
reload
If True use reload instead of the default restart. If value is a list of
requisites; reload only if all watched changes are contained in the reload list.
Otherwise watch will restart.
full_restart
Use service.full_restart instead of restart.
When set, reload the service instead of restarting it.
(i.e. ``service nginx reload``)
full_restart
Perform a full stop/start of a service by passing ``--full-restart``.
This option is ignored if ``reload`` is set and is supported by only a few
:py:func:`service modules <salt.modules.service>`.
force
Use service.force_reload instead of reload (needs reload to be set to True)
init_delay
Add a sleep command (in seconds) before the service is restarted/reloaded
'''
reload_ = kwargs.pop('reload', False)
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
past_participle = None
if sfun == 'dead':
verb = 'stop'
past_participle = verb + 'ped'
if __salt__['service.status'](name, sig):
func = __salt__['service.stop']
else:
ret['result'] = True
ret['comment'] = 'Service is already {0}'.format(past_participle)
return ret
elif sfun == 'running':
if __salt__['service.status'](name, sig):
if 'service.reload' in __salt__ and reload_:
if isinstance(reload_, list):
only_reload_needed = True
for watch_item in kwargs['__reqs__']['watch']:
if __running__[_gen_tag(watch_item)]['changes']:
match_found = False
for this_reload in reload_:
for state, id_ in six.iteritems(this_reload):
if state == watch_item['state'] \
and id_ == watch_item['__id__']:
match_found = True
if not match_found:
only_reload_needed = False
if only_reload_needed:
if 'service.force_reload' in __salt__ and force:
func = __salt__['service.force_reload']
verb = 'forcefully reload'
else:
func = __salt__['service.reload']
verb = 'reload'
else:
if 'service.full_restart' in __salt__ and full_restart:
func = __salt__['service.full_restart']
verb = 'fully restart'
else:
func = __salt__['service.restart']
verb = 'restart'
else:
if 'service.force_reload' in __salt__ and force:
func = __salt__['service.force_reload']
verb = 'forcefully reload'
else:
func = __salt__['service.reload']
verb = 'reload'
elif 'service.full_restart' in __salt__ and full_restart:
func = __salt__['service.full_restart']
verb = 'fully restart'
else:
func = __salt__['service.restart']
verb = 'restart'
else:
func = __salt__['service.start']
verb = 'start'
if not past_participle:
past_participle = verb + 'ed'
else:
ret['comment'] = 'Unable to trigger watch for service.{0}'.format(sfun)
ret['result'] = False
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service is set to be {0}'.format(past_participle)
return ret
if verb == 'start' and 'service.stop' in __salt__:
# stop service before start
__salt__['service.stop'](name)
func_kwargs, warnings = _get_systemd_only(func, kwargs)
if warnings:
ret.setdefault('warnings', []).extend(warnings)
try:
result = func(name, **func_kwargs)
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
if init_delay:
time.sleep(init_delay)
ret['changes'] = {name: result}
ret['result'] = result
ret['comment'] = 'Service {0}'.format(past_participle) if result else \
'Failed to {0} the service'.format(verb)
return ret
|
saltstack/salt
|
salt/states/service.py
|
masked
|
python
|
def masked(name, runtime=False):
'''
.. versionadded:: 2017.7.0
.. note::
This state is only available on minions which use systemd_.
Ensures that the named service is masked (i.e. prevented from being
started).
name
Name of the service to mask
runtime : False
By default, this state will manage an indefinite mask for the named
service. Set this argument to ``True`` to runtime mask the service.
.. note::
It is possible for a service to have both indefinite and runtime masks
set for it. Therefore, this state will manage a runtime or indefinite
mask independently of each other. This means that if the service is
already indefinitely masked, running this state with ``runtime`` set to
``True`` will _not_ remove the indefinite mask before setting a runtime
mask. In these cases, if it is desirable to ensure that the service is
runtime masked and not indefinitely masked, pair this state with a
:py:func:`service.unmasked <salt.states.service.unmasked>` state, like
so:
.. code-block:: yaml
mask_runtime_foo:
service.masked:
- name: foo
- runtime: True
unmask_indefinite_foo:
service.unmasked:
- name: foo
- runtime: False
.. _systemd: https://freedesktop.org/wiki/Software/systemd/
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if 'service.masked' not in __salt__:
ret['comment'] = 'Service masking not available on this minion'
ret['result'] = False
return ret
mask_type = 'runtime masked' if runtime else 'masked'
expected_changes = {mask_type: {'old': False, 'new': True}}
try:
if __salt__['service.masked'](name, runtime):
ret['comment'] = 'Service {0} is already {1}'.format(
name,
mask_type,
)
return ret
if __opts__['test']:
ret['result'] = None
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} would be {1}'.format(name, mask_type)
return ret
__salt__['service.mask'](name, runtime)
if __salt__['service.masked'](name, runtime):
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} was {1}'.format(name, mask_type)
else:
ret['comment'] = 'Failed to mask service {0}'.format(name)
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
|
.. versionadded:: 2017.7.0
.. note::
This state is only available on minions which use systemd_.
Ensures that the named service is masked (i.e. prevented from being
started).
name
Name of the service to mask
runtime : False
By default, this state will manage an indefinite mask for the named
service. Set this argument to ``True`` to runtime mask the service.
.. note::
It is possible for a service to have both indefinite and runtime masks
set for it. Therefore, this state will manage a runtime or indefinite
mask independently of each other. This means that if the service is
already indefinitely masked, running this state with ``runtime`` set to
``True`` will _not_ remove the indefinite mask before setting a runtime
mask. In these cases, if it is desirable to ensure that the service is
runtime masked and not indefinitely masked, pair this state with a
:py:func:`service.unmasked <salt.states.service.unmasked>` state, like
so:
.. code-block:: yaml
mask_runtime_foo:
service.masked:
- name: foo
- runtime: True
unmask_indefinite_foo:
service.unmasked:
- name: foo
- runtime: False
.. _systemd: https://freedesktop.org/wiki/Software/systemd/
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/service.py#L706-L788
| null |
# -*- coding: utf-8 -*-
'''
Starting or restarting of services and daemons
==============================================
Services are defined as system daemons and are typically launched using system
init or rc scripts. This service state uses whichever service module is loaded
on the minion with the virtualname of ``service``. Services can be defined as
either running or dead.
If you need to know if your init system is supported, see the list of supported
:mod:`service modules <salt.modules.service.py>` for your desired init system
(systemd, sysvinit, launchctl, etc.).
Note that Salt's service execution module, and therefore this service state,
uses OS grains to ascertain which service module should be loaded and used to
execute service functions. As existing distributions change init systems or
new distributions are created, OS detection can sometimes be incomplete.
If your service states are running into trouble with init system detection,
please see the :ref:`Overriding Virtual Module Providers <module-provider-override>`
section of Salt's module documentation to work around possible errors.
.. note::
The current status of a service is determined by the return code of the init/rc
script status command. A status return code of 0 it is considered running. Any
other return code is considered dead.
.. code-block:: yaml
httpd:
service.running: []
The service can also be set to start at runtime via the enable option:
.. code-block:: yaml
openvpn:
service.running:
- enable: True
By default if a service is triggered to refresh due to a watch statement the
service is restarted. If the desired behavior is to reload the service, then
set the reload value to True:
.. code-block:: yaml
redis:
service.running:
- enable: True
- reload: True
- watch:
- pkg: redis
.. note::
More details regarding ``watch`` can be found in the
:ref:`Requisites <requisites>` documentation.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
# Import Salt libs
import salt.utils.data
import salt.utils.platform
from salt.utils.args import get_function_argspec as _argspec
from salt.exceptions import CommandExecutionError
from salt.state import _gen_tag
# Import 3rd-party libs
from salt.ext import six
SYSTEMD_ONLY = ('no_block', 'unmask', 'unmask_runtime')
__virtualname__ = 'service'
def __virtual__():
'''
Only make these states available if a service provider has been detected or
assigned for this minion
'''
if 'service.start' in __salt__:
return __virtualname__
else:
return (False, 'No service execution module loaded: '
'check support for service management on {0} '
''.format(__grains__.get('osfinger', __grains__['os']))
)
# Double-asterisk deliberately not used here
def _get_systemd_only(func, kwargs):
ret = {}
warnings = []
valid_args = _argspec(func).args
for systemd_arg in SYSTEMD_ONLY:
arg_val = kwargs.get(systemd_arg, False)
if arg_val:
if systemd_arg in valid_args:
ret[systemd_arg] = arg_val
else:
warnings.append(
'The \'{0}\' argument is not supported by this '
'platform/action'.format(systemd_arg)
)
return ret, warnings
def _enabled_used_error(ret):
'''
Warn of potential typo.
'''
ret['result'] = False
ret['comment'] = (
'Service {0} uses non-existent option "enabled". ' +
'Perhaps "enable" option was intended?'
).format(ret['name'])
return ret
def _enable(name, started, result=True, skip_verify=False, **kwargs):
'''
Enable the service
'''
ret = {}
if not skip_verify:
# is service available?
try:
if not _available(name, ret):
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# Set default expected result
ret['result'] = result
# Check to see if this minion supports enable
if 'service.enable' not in __salt__ or 'service.enabled' not in __salt__:
if started is True:
ret['comment'] = ('Enable is not available on this minion,'
' service {0} started').format(name)
elif started is None:
ret['comment'] = ('Enable is not available on this minion,'
' service {0} is in the desired state'
).format(name)
else:
ret['comment'] = ('Enable is not available on this minion,'
' service {0} is dead').format(name)
return ret
# Service can be enabled
before_toggle_enable_status = __salt__['service.enabled'](name, **kwargs)
if before_toggle_enable_status:
# Service is enabled
if started is True:
ret['comment'] = ('Service {0} is already enabled,'
' and is running').format(name)
elif started is None:
# always be sure in this case to reset the changes dict
ret['changes'] = {}
ret['comment'] = ('Service {0} is already enabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} is already enabled,'
' and is dead').format(name)
return ret
# Service needs to be enabled
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service {0} set to be enabled'.format(name)
return ret
try:
if __salt__['service.enable'](name, **kwargs):
# Service has been enabled
ret['changes'] = {}
after_toggle_enable_status = __salt__['service.enabled'](
name,
**kwargs)
# on upstart, certain services like apparmor will always return
# False, even if correctly activated
# do not trigger a change
if before_toggle_enable_status != after_toggle_enable_status:
ret['changes'][name] = True
if started is True:
ret['comment'] = ('Service {0} has been enabled,'
' and is running').format(name)
elif started is None:
ret['comment'] = ('Service {0} has been enabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} has been enabled,'
' and is dead').format(name)
return ret
except CommandExecutionError as exc:
enable_error = exc.strerror
else:
enable_error = False
# Service failed to be enabled
ret['result'] = False
if started is True:
ret['comment'] = ('Failed when setting service {0} to start at boot,'
' but the service is running').format(name)
elif started is None:
ret['comment'] = ('Failed when setting service {0} to start at boot,'
' but the service was already running').format(name)
else:
ret['comment'] = ('Failed when setting service {0} to start at boot,'
' and the service is dead').format(name)
if enable_error:
ret['comment'] += '. Additional information follows:\n\n{0}'.format(
enable_error
)
return ret
def _disable(name, started, result=True, skip_verify=False, **kwargs):
'''
Disable the service
'''
ret = {}
if not skip_verify:
# is service available?
try:
if not _available(name, ret):
ret['result'] = True
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# Set default expected result
ret['result'] = result
# is enable/disable available?
if 'service.disable' not in __salt__ or 'service.disabled' not in __salt__:
if started is True:
ret['comment'] = ('Disable is not available on this minion,'
' service {0} started').format(name)
elif started is None:
ret['comment'] = ('Disable is not available on this minion,'
' service {0} is in the desired state'
).format(name)
else:
ret['comment'] = ('Disable is not available on this minion,'
' service {0} is dead').format(name)
return ret
# Service can be disabled
if salt.utils.platform.is_windows():
# service.disabled in Windows returns True for services that are set to
# Manual start, so we need to check specifically for Disabled
before_toggle_disable_status = __salt__['service.info'](name)['StartType'] in ['Disabled']
else:
before_toggle_disable_status = __salt__['service.disabled'](name)
if before_toggle_disable_status:
# Service is disabled
if started is True:
ret['comment'] = ('Service {0} is already disabled,'
' and is running').format(name)
elif started is None:
# always be sure in this case to reset the changes dict
ret['changes'] = {}
ret['comment'] = ('Service {0} is already disabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} is already disabled,'
' and is dead').format(name)
return ret
# Service needs to be disabled
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service {0} set to be disabled'.format(name)
return ret
if __salt__['service.disable'](name, **kwargs):
# Service has been disabled
ret['changes'] = {}
after_toggle_disable_status = __salt__['service.disabled'](name)
# on upstart, certain services like apparmor will always return
# False, even if correctly activated
# do not trigger a change
if before_toggle_disable_status != after_toggle_disable_status:
ret['changes'][name] = True
if started is True:
ret['comment'] = ('Service {0} has been disabled,'
' and is running').format(name)
elif started is None:
ret['comment'] = ('Service {0} has been disabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} has been disabled,'
' and is dead').format(name)
return ret
# Service failed to be disabled
ret['result'] = False
if started is True:
ret['comment'] = ('Failed when setting service {0} to not start'
' at boot, and is running').format(name)
elif started is None:
ret['comment'] = ('Failed when setting service {0} to not start'
' at boot, but the service was already running'
).format(name)
else:
ret['comment'] = ('Failed when setting service {0} to not start'
' at boot, and the service is dead').format(name)
return ret
def _available(name, ret):
'''
Check if the service is available
'''
avail = False
if 'service.available' in __salt__:
avail = __salt__['service.available'](name)
elif 'service.get_all' in __salt__:
avail = name in __salt__['service.get_all']()
if not avail:
ret['result'] = False
ret['comment'] = 'The named service {0} is not available'.format(name)
return avail
def running(name,
enable=None,
sig=None,
init_delay=None,
no_block=False,
unmask=False,
unmask_runtime=False,
**kwargs):
'''
Ensure that the service is running
name
The name of the init or rc script used to manage the service
enable
Set the service to be enabled at boot time, ``True`` sets the service
to be enabled, ``False`` sets the named service to be disabled. The
default is ``None``, which does not enable or disable anything.
sig
The string to search for when looking for the service process with ps
init_delay
Some services may not be truly available for a short period after their
startup script indicates to the system that they are. Provide an
'init_delay' to specify that this state should wait an additional given
number of seconds after a service has started before returning. Useful
for requisite states wherein a dependent state might assume a service
has started but is not yet fully initialized.
no_block : False
**For systemd minions only.** Starts the service using ``--no-block``.
.. versionadded:: 2017.7.0
unmask : False
**For systemd minions only.** Set to ``True`` to remove an indefinite
mask before attempting to start the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
making any changes. This behavior is no longer the default.
unmask_runtime : False
**For systemd minions only.** Set to ``True`` to remove a runtime mask
before attempting to start the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
making any changes. This behavior is no longer the default.
.. note::
``watch`` can be used with service.running to restart a service when
another state changes ( example: a file.managed state that creates the
service's config file ). More details regarding ``watch`` can be found
in the :ref:`Requisites <requisites>` documentation.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
# Check for common error: using enabled option instead of enable
if 'enabled' in kwargs:
return _enabled_used_error(ret)
# Convert enable to boolean in case user passed a string value
if isinstance(enable, six.string_types):
enable = salt.utils.data.is_true(enable)
# Check if the service is available
try:
if not _available(name, ret):
if __opts__.get('test'):
ret['result'] = None
ret['comment'] = 'Service {0} not present; if created in this state run, it would have been started'.format(name)
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# lot of custom init script won't or mis implement the status
# command, so it is just an indicator but can not be fully trusted
before_toggle_status = __salt__['service.status'](name, sig)
if 'service.enabled' in __salt__:
before_toggle_enable_status = __salt__['service.enabled'](name)
else:
before_toggle_enable_status = True
unmask_ret = {'comment': ''}
if unmask:
unmask_ret = unmasked(name, unmask_runtime)
# See if the service is already running
if before_toggle_status:
ret['comment'] = '\n'.join(
[_f for _f in ['The service {0} is already running'.format(name),
unmask_ret['comment']] if _f]
)
if enable is True and not before_toggle_enable_status:
ret.update(_enable(name, None, skip_verify=False, **kwargs))
elif enable is False and before_toggle_enable_status:
ret.update(_disable(name, None, skip_verify=False, **kwargs))
return ret
# Run the tests
if __opts__['test']:
ret['result'] = None
ret['comment'] = '\n'.join(
[_f for _f in ['Service {0} is set to start'.format(name),
unmask_ret['comment']] if _f])
return ret
# Conditionally add systemd-specific args to call to service.start
start_kwargs, warnings = \
_get_systemd_only(__salt__['service.start'], locals())
if warnings:
ret.setdefault('warnings', []).extend(warnings)
if salt.utils.platform.is_windows():
for arg in ['timeout', 'with_deps', 'with_parents']:
if kwargs.get(arg, False):
start_kwargs.update({arg: kwargs.get(arg)})
try:
func_ret = __salt__['service.start'](name, **start_kwargs)
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
if not func_ret:
ret['result'] = False
ret['comment'] = 'Service {0} failed to start'.format(name)
if enable is True:
ret.update(_enable(name, False, result=False, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, False, result=False, skip_verify=False, **kwargs))
return ret
if init_delay:
time.sleep(init_delay)
# only force a change state if we have explicitly detected them
after_toggle_status = __salt__['service.status'](name, sig)
if 'service.enabled' in __salt__:
after_toggle_enable_status = __salt__['service.enabled'](name)
else:
after_toggle_enable_status = True
if (
(before_toggle_enable_status != after_toggle_enable_status) or
(before_toggle_status != after_toggle_status)
) and not ret.get('changes', {}):
ret['changes'][name] = after_toggle_status
if after_toggle_status:
ret['comment'] = 'Started Service {0}'.format(name)
else:
ret['comment'] = 'Service {0} failed to start'.format(name)
ret['result'] = False
if enable is True:
ret.update(_enable(name, after_toggle_status, result=after_toggle_status, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, after_toggle_status, result=after_toggle_status, skip_verify=False, **kwargs))
if init_delay:
ret['comment'] = (
'{0}\nDelayed return for {1} seconds'
.format(ret['comment'], init_delay)
)
if unmask:
ret['comment'] = '\n'.join([ret['comment'], unmask_ret['comment']])
return ret
def dead(name,
enable=None,
sig=None,
init_delay=None,
**kwargs):
'''
Ensure that the named service is dead by stopping the service if it is running
name
The name of the init or rc script used to manage the service
enable
Set the service to be enabled at boot time, ``True`` sets the service
to be enabled, ``False`` sets the named service to be disabled. The
default is ``None``, which does not enable or disable anything.
sig
The string to search for when looking for the service process with ps
init_delay
Add a sleep command (in seconds) before the check to make sure service
is killed.
.. versionadded:: 2017.7.0
no_block : False
**For systemd minions only.** Stops the service using ``--no-block``.
.. versionadded:: 2017.7.0
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
# Check for common error: using enabled option instead of enable
if 'enabled' in kwargs:
return _enabled_used_error(ret)
# Convert enable to boolean in case user passed a string value
if isinstance(enable, six.string_types):
enable = salt.utils.data.is_true(enable)
# Check if the service is available
try:
if not _available(name, ret):
if __opts__.get('test'):
ret['result'] = None
ret['comment'] = 'Service {0} not present; if created in this state run, it would have been stopped'.format(name)
else:
# A non-available service is OK here, don't let the state fail
# because of it.
ret['result'] = True
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# lot of custom init script won't or mis implement the status
# command, so it is just an indicator but can not be fully trusted
before_toggle_status = __salt__['service.status'](name, sig)
if 'service.enabled' in __salt__:
if salt.utils.platform.is_windows():
# service.enabled in Windows returns True for services that are set
# to Auto start, but services set to Manual can also be disabled
before_toggle_enable_status = __salt__['service.info'](name)['StartType'] in ['Auto', 'Manual']
else:
before_toggle_enable_status = __salt__['service.enabled'](name)
else:
before_toggle_enable_status = True
# See if the service is already dead
if not before_toggle_status:
ret['comment'] = 'The service {0} is already dead'.format(name)
if enable is True and not before_toggle_enable_status:
ret.update(_enable(name, None, skip_verify=False, **kwargs))
elif enable is False and before_toggle_enable_status:
ret.update(_disable(name, None, skip_verify=False, **kwargs))
return ret
# Run the tests
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service {0} is set to be killed'.format(name)
return ret
# Conditionally add systemd-specific args to call to service.start
stop_kwargs, warnings = _get_systemd_only(__salt__['service.stop'], kwargs)
if warnings:
ret.setdefault('warnings', []).extend(warnings)
if salt.utils.platform.is_windows():
for arg in ['timeout', 'with_deps', 'with_parents']:
if kwargs.get(arg, False):
stop_kwargs.update({arg: kwargs.get(arg)})
func_ret = __salt__['service.stop'](name, **stop_kwargs)
if not func_ret:
ret['result'] = False
ret['comment'] = 'Service {0} failed to die'.format(name)
if enable is True:
ret.update(_enable(name, True, result=False, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, True, result=False, skip_verify=False, **kwargs))
return ret
if init_delay:
time.sleep(init_delay)
# only force a change state if we have explicitly detected them
after_toggle_status = __salt__['service.status'](name)
if 'service.enabled' in __salt__:
after_toggle_enable_status = __salt__['service.enabled'](name)
else:
after_toggle_enable_status = True
if (
(before_toggle_enable_status != after_toggle_enable_status) or
(before_toggle_status != after_toggle_status)
) and not ret.get('changes', {}):
ret['changes'][name] = after_toggle_status
# be sure to stop, in case we mis detected in the check
if after_toggle_status:
ret['result'] = False
ret['comment'] = 'Service {0} failed to die'.format(name)
else:
ret['comment'] = 'Service {0} was killed'.format(name)
if enable is True:
ret.update(_enable(name, after_toggle_status, result=not after_toggle_status, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, after_toggle_status, result=not after_toggle_status, skip_verify=False, **kwargs))
return ret
def enabled(name,
skip_verify=False,
**kwargs):
'''
Ensure that the service is enabled on boot, only use this state if you
don't want to manage the running process, remember that if you want to
enable a running service to use the enable: True option for the running
or dead function.
name
The name of the init or rc script used to manage the service
skip_verify
Skip verifying that the service is available before enabling it.
``True`` will skip the verification. The default is ``False``,
which will ensure the service is available before enabling it.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
ret.update(_enable(name, None, skip_verify=skip_verify, **kwargs))
return ret
def disabled(name,
skip_verify=False,
**kwargs):
'''
Ensure that the service is disabled on boot, only use this state if you
don't want to manage the running process, remember that if you want to
disable a service to use the enable: False option for the running or dead
function.
name
The name of the init or rc script used to manage the service
skip_verify
Skip verifying that the service is available before disabling it.
``True`` will skip the verification. The default is ``False``,
which will ensure the service is available before disabling it.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
ret.update(_disable(name, None, skip_verify=skip_verify, **kwargs))
return ret
def unmasked(name, runtime=False):
'''
.. versionadded:: 2017.7.0
.. note::
This state is only available on minions which use systemd_.
Ensures that the named service is unmasked
name
Name of the service to unmask
runtime : False
By default, this state will manage an indefinite mask for the named
service. Set this argument to ``True`` to ensure that the service is
runtime masked.
.. note::
It is possible for a service to have both indefinite and runtime masks
set for it. Therefore, this state will manage a runtime or indefinite
mask independently of each other. This means that if the service is
indefinitely masked, running this state with ``runtime`` set to
``True`` will _not_ remove the indefinite mask.
.. _systemd: https://freedesktop.org/wiki/Software/systemd/
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if 'service.masked' not in __salt__:
ret['comment'] = 'Service masking not available on this minion'
ret['result'] = False
return ret
mask_type = 'runtime masked' if runtime else 'masked'
action = 'runtime unmasked' if runtime else 'unmasked'
expected_changes = {mask_type: {'old': True, 'new': False}}
try:
if not __salt__['service.masked'](name, runtime):
ret['comment'] = 'Service {0} was already {1}'.format(name, action)
return ret
if __opts__['test']:
ret['result'] = None
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} would be {1}'.format(name, action)
return ret
__salt__['service.unmask'](name, runtime)
if not __salt__['service.masked'](name, runtime):
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} was {1}'.format(name, action)
else:
ret['comment'] = 'Failed to unmask service {0}'.format(name)
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
def mod_watch(name,
sfun=None,
sig=None,
full_restart=False,
init_delay=None,
force=False,
**kwargs):
'''
The service watcher, called to invoke the watch command.
When called, it will restart or reload the named service.
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the watching service.
(i.e. ``service.running``)
name
The name of the init or rc script used to manage the service
sfun
The original function which triggered the mod_watch call
(`service.running`, for example).
sig
The string to search for when looking for the service process with ps
reload
If True use reload instead of the default restart. If value is a list of
requisites; reload only if all watched changes are contained in the reload list.
Otherwise watch will restart.
full_restart
Use service.full_restart instead of restart.
When set, reload the service instead of restarting it.
(i.e. ``service nginx reload``)
full_restart
Perform a full stop/start of a service by passing ``--full-restart``.
This option is ignored if ``reload`` is set and is supported by only a few
:py:func:`service modules <salt.modules.service>`.
force
Use service.force_reload instead of reload (needs reload to be set to True)
init_delay
Add a sleep command (in seconds) before the service is restarted/reloaded
'''
reload_ = kwargs.pop('reload', False)
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
past_participle = None
if sfun == 'dead':
verb = 'stop'
past_participle = verb + 'ped'
if __salt__['service.status'](name, sig):
func = __salt__['service.stop']
else:
ret['result'] = True
ret['comment'] = 'Service is already {0}'.format(past_participle)
return ret
elif sfun == 'running':
if __salt__['service.status'](name, sig):
if 'service.reload' in __salt__ and reload_:
if isinstance(reload_, list):
only_reload_needed = True
for watch_item in kwargs['__reqs__']['watch']:
if __running__[_gen_tag(watch_item)]['changes']:
match_found = False
for this_reload in reload_:
for state, id_ in six.iteritems(this_reload):
if state == watch_item['state'] \
and id_ == watch_item['__id__']:
match_found = True
if not match_found:
only_reload_needed = False
if only_reload_needed:
if 'service.force_reload' in __salt__ and force:
func = __salt__['service.force_reload']
verb = 'forcefully reload'
else:
func = __salt__['service.reload']
verb = 'reload'
else:
if 'service.full_restart' in __salt__ and full_restart:
func = __salt__['service.full_restart']
verb = 'fully restart'
else:
func = __salt__['service.restart']
verb = 'restart'
else:
if 'service.force_reload' in __salt__ and force:
func = __salt__['service.force_reload']
verb = 'forcefully reload'
else:
func = __salt__['service.reload']
verb = 'reload'
elif 'service.full_restart' in __salt__ and full_restart:
func = __salt__['service.full_restart']
verb = 'fully restart'
else:
func = __salt__['service.restart']
verb = 'restart'
else:
func = __salt__['service.start']
verb = 'start'
if not past_participle:
past_participle = verb + 'ed'
else:
ret['comment'] = 'Unable to trigger watch for service.{0}'.format(sfun)
ret['result'] = False
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service is set to be {0}'.format(past_participle)
return ret
if verb == 'start' and 'service.stop' in __salt__:
# stop service before start
__salt__['service.stop'](name)
func_kwargs, warnings = _get_systemd_only(func, kwargs)
if warnings:
ret.setdefault('warnings', []).extend(warnings)
try:
result = func(name, **func_kwargs)
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
if init_delay:
time.sleep(init_delay)
ret['changes'] = {name: result}
ret['result'] = result
ret['comment'] = 'Service {0}'.format(past_participle) if result else \
'Failed to {0} the service'.format(verb)
return ret
|
saltstack/salt
|
salt/states/service.py
|
mod_watch
|
python
|
def mod_watch(name,
sfun=None,
sig=None,
full_restart=False,
init_delay=None,
force=False,
**kwargs):
'''
The service watcher, called to invoke the watch command.
When called, it will restart or reload the named service.
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the watching service.
(i.e. ``service.running``)
name
The name of the init or rc script used to manage the service
sfun
The original function which triggered the mod_watch call
(`service.running`, for example).
sig
The string to search for when looking for the service process with ps
reload
If True use reload instead of the default restart. If value is a list of
requisites; reload only if all watched changes are contained in the reload list.
Otherwise watch will restart.
full_restart
Use service.full_restart instead of restart.
When set, reload the service instead of restarting it.
(i.e. ``service nginx reload``)
full_restart
Perform a full stop/start of a service by passing ``--full-restart``.
This option is ignored if ``reload`` is set and is supported by only a few
:py:func:`service modules <salt.modules.service>`.
force
Use service.force_reload instead of reload (needs reload to be set to True)
init_delay
Add a sleep command (in seconds) before the service is restarted/reloaded
'''
reload_ = kwargs.pop('reload', False)
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
past_participle = None
if sfun == 'dead':
verb = 'stop'
past_participle = verb + 'ped'
if __salt__['service.status'](name, sig):
func = __salt__['service.stop']
else:
ret['result'] = True
ret['comment'] = 'Service is already {0}'.format(past_participle)
return ret
elif sfun == 'running':
if __salt__['service.status'](name, sig):
if 'service.reload' in __salt__ and reload_:
if isinstance(reload_, list):
only_reload_needed = True
for watch_item in kwargs['__reqs__']['watch']:
if __running__[_gen_tag(watch_item)]['changes']:
match_found = False
for this_reload in reload_:
for state, id_ in six.iteritems(this_reload):
if state == watch_item['state'] \
and id_ == watch_item['__id__']:
match_found = True
if not match_found:
only_reload_needed = False
if only_reload_needed:
if 'service.force_reload' in __salt__ and force:
func = __salt__['service.force_reload']
verb = 'forcefully reload'
else:
func = __salt__['service.reload']
verb = 'reload'
else:
if 'service.full_restart' in __salt__ and full_restart:
func = __salt__['service.full_restart']
verb = 'fully restart'
else:
func = __salt__['service.restart']
verb = 'restart'
else:
if 'service.force_reload' in __salt__ and force:
func = __salt__['service.force_reload']
verb = 'forcefully reload'
else:
func = __salt__['service.reload']
verb = 'reload'
elif 'service.full_restart' in __salt__ and full_restart:
func = __salt__['service.full_restart']
verb = 'fully restart'
else:
func = __salt__['service.restart']
verb = 'restart'
else:
func = __salt__['service.start']
verb = 'start'
if not past_participle:
past_participle = verb + 'ed'
else:
ret['comment'] = 'Unable to trigger watch for service.{0}'.format(sfun)
ret['result'] = False
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service is set to be {0}'.format(past_participle)
return ret
if verb == 'start' and 'service.stop' in __salt__:
# stop service before start
__salt__['service.stop'](name)
func_kwargs, warnings = _get_systemd_only(func, kwargs)
if warnings:
ret.setdefault('warnings', []).extend(warnings)
try:
result = func(name, **func_kwargs)
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
if init_delay:
time.sleep(init_delay)
ret['changes'] = {name: result}
ret['result'] = result
ret['comment'] = 'Service {0}'.format(past_participle) if result else \
'Failed to {0} the service'.format(verb)
return ret
|
The service watcher, called to invoke the watch command.
When called, it will restart or reload the named service.
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the watching service.
(i.e. ``service.running``)
name
The name of the init or rc script used to manage the service
sfun
The original function which triggered the mod_watch call
(`service.running`, for example).
sig
The string to search for when looking for the service process with ps
reload
If True use reload instead of the default restart. If value is a list of
requisites; reload only if all watched changes are contained in the reload list.
Otherwise watch will restart.
full_restart
Use service.full_restart instead of restart.
When set, reload the service instead of restarting it.
(i.e. ``service nginx reload``)
full_restart
Perform a full stop/start of a service by passing ``--full-restart``.
This option is ignored if ``reload`` is set and is supported by only a few
:py:func:`service modules <salt.modules.service>`.
force
Use service.force_reload instead of reload (needs reload to be set to True)
init_delay
Add a sleep command (in seconds) before the service is restarted/reloaded
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/service.py#L858-L1002
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def _gen_tag(low):\n '''\n Generate the running dict tag string from the low data structure\n '''\n return '{0[state]}_|-{0[__id__]}_|-{0[name]}_|-{0[fun]}'.format(low)\n",
"def _get_systemd_only(func, kwargs):\n ret = {}\n warnings = []\n valid_args = _argspec(func).args\n for systemd_arg in SYSTEMD_ONLY:\n arg_val = kwargs.get(systemd_arg, False)\n if arg_val:\n if systemd_arg in valid_args:\n ret[systemd_arg] = arg_val\n else:\n warnings.append(\n 'The \\'{0}\\' argument is not supported by this '\n 'platform/action'.format(systemd_arg)\n )\n return ret, warnings\n"
] |
# -*- coding: utf-8 -*-
'''
Starting or restarting of services and daemons
==============================================
Services are defined as system daemons and are typically launched using system
init or rc scripts. This service state uses whichever service module is loaded
on the minion with the virtualname of ``service``. Services can be defined as
either running or dead.
If you need to know if your init system is supported, see the list of supported
:mod:`service modules <salt.modules.service.py>` for your desired init system
(systemd, sysvinit, launchctl, etc.).
Note that Salt's service execution module, and therefore this service state,
uses OS grains to ascertain which service module should be loaded and used to
execute service functions. As existing distributions change init systems or
new distributions are created, OS detection can sometimes be incomplete.
If your service states are running into trouble with init system detection,
please see the :ref:`Overriding Virtual Module Providers <module-provider-override>`
section of Salt's module documentation to work around possible errors.
.. note::
The current status of a service is determined by the return code of the init/rc
script status command. A status return code of 0 it is considered running. Any
other return code is considered dead.
.. code-block:: yaml
httpd:
service.running: []
The service can also be set to start at runtime via the enable option:
.. code-block:: yaml
openvpn:
service.running:
- enable: True
By default if a service is triggered to refresh due to a watch statement the
service is restarted. If the desired behavior is to reload the service, then
set the reload value to True:
.. code-block:: yaml
redis:
service.running:
- enable: True
- reload: True
- watch:
- pkg: redis
.. note::
More details regarding ``watch`` can be found in the
:ref:`Requisites <requisites>` documentation.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
# Import Salt libs
import salt.utils.data
import salt.utils.platform
from salt.utils.args import get_function_argspec as _argspec
from salt.exceptions import CommandExecutionError
from salt.state import _gen_tag
# Import 3rd-party libs
from salt.ext import six
SYSTEMD_ONLY = ('no_block', 'unmask', 'unmask_runtime')
__virtualname__ = 'service'
def __virtual__():
'''
Only make these states available if a service provider has been detected or
assigned for this minion
'''
if 'service.start' in __salt__:
return __virtualname__
else:
return (False, 'No service execution module loaded: '
'check support for service management on {0} '
''.format(__grains__.get('osfinger', __grains__['os']))
)
# Double-asterisk deliberately not used here
def _get_systemd_only(func, kwargs):
ret = {}
warnings = []
valid_args = _argspec(func).args
for systemd_arg in SYSTEMD_ONLY:
arg_val = kwargs.get(systemd_arg, False)
if arg_val:
if systemd_arg in valid_args:
ret[systemd_arg] = arg_val
else:
warnings.append(
'The \'{0}\' argument is not supported by this '
'platform/action'.format(systemd_arg)
)
return ret, warnings
def _enabled_used_error(ret):
'''
Warn of potential typo.
'''
ret['result'] = False
ret['comment'] = (
'Service {0} uses non-existent option "enabled". ' +
'Perhaps "enable" option was intended?'
).format(ret['name'])
return ret
def _enable(name, started, result=True, skip_verify=False, **kwargs):
'''
Enable the service
'''
ret = {}
if not skip_verify:
# is service available?
try:
if not _available(name, ret):
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# Set default expected result
ret['result'] = result
# Check to see if this minion supports enable
if 'service.enable' not in __salt__ or 'service.enabled' not in __salt__:
if started is True:
ret['comment'] = ('Enable is not available on this minion,'
' service {0} started').format(name)
elif started is None:
ret['comment'] = ('Enable is not available on this minion,'
' service {0} is in the desired state'
).format(name)
else:
ret['comment'] = ('Enable is not available on this minion,'
' service {0} is dead').format(name)
return ret
# Service can be enabled
before_toggle_enable_status = __salt__['service.enabled'](name, **kwargs)
if before_toggle_enable_status:
# Service is enabled
if started is True:
ret['comment'] = ('Service {0} is already enabled,'
' and is running').format(name)
elif started is None:
# always be sure in this case to reset the changes dict
ret['changes'] = {}
ret['comment'] = ('Service {0} is already enabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} is already enabled,'
' and is dead').format(name)
return ret
# Service needs to be enabled
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service {0} set to be enabled'.format(name)
return ret
try:
if __salt__['service.enable'](name, **kwargs):
# Service has been enabled
ret['changes'] = {}
after_toggle_enable_status = __salt__['service.enabled'](
name,
**kwargs)
# on upstart, certain services like apparmor will always return
# False, even if correctly activated
# do not trigger a change
if before_toggle_enable_status != after_toggle_enable_status:
ret['changes'][name] = True
if started is True:
ret['comment'] = ('Service {0} has been enabled,'
' and is running').format(name)
elif started is None:
ret['comment'] = ('Service {0} has been enabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} has been enabled,'
' and is dead').format(name)
return ret
except CommandExecutionError as exc:
enable_error = exc.strerror
else:
enable_error = False
# Service failed to be enabled
ret['result'] = False
if started is True:
ret['comment'] = ('Failed when setting service {0} to start at boot,'
' but the service is running').format(name)
elif started is None:
ret['comment'] = ('Failed when setting service {0} to start at boot,'
' but the service was already running').format(name)
else:
ret['comment'] = ('Failed when setting service {0} to start at boot,'
' and the service is dead').format(name)
if enable_error:
ret['comment'] += '. Additional information follows:\n\n{0}'.format(
enable_error
)
return ret
def _disable(name, started, result=True, skip_verify=False, **kwargs):
'''
Disable the service
'''
ret = {}
if not skip_verify:
# is service available?
try:
if not _available(name, ret):
ret['result'] = True
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# Set default expected result
ret['result'] = result
# is enable/disable available?
if 'service.disable' not in __salt__ or 'service.disabled' not in __salt__:
if started is True:
ret['comment'] = ('Disable is not available on this minion,'
' service {0} started').format(name)
elif started is None:
ret['comment'] = ('Disable is not available on this minion,'
' service {0} is in the desired state'
).format(name)
else:
ret['comment'] = ('Disable is not available on this minion,'
' service {0} is dead').format(name)
return ret
# Service can be disabled
if salt.utils.platform.is_windows():
# service.disabled in Windows returns True for services that are set to
# Manual start, so we need to check specifically for Disabled
before_toggle_disable_status = __salt__['service.info'](name)['StartType'] in ['Disabled']
else:
before_toggle_disable_status = __salt__['service.disabled'](name)
if before_toggle_disable_status:
# Service is disabled
if started is True:
ret['comment'] = ('Service {0} is already disabled,'
' and is running').format(name)
elif started is None:
# always be sure in this case to reset the changes dict
ret['changes'] = {}
ret['comment'] = ('Service {0} is already disabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} is already disabled,'
' and is dead').format(name)
return ret
# Service needs to be disabled
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service {0} set to be disabled'.format(name)
return ret
if __salt__['service.disable'](name, **kwargs):
# Service has been disabled
ret['changes'] = {}
after_toggle_disable_status = __salt__['service.disabled'](name)
# on upstart, certain services like apparmor will always return
# False, even if correctly activated
# do not trigger a change
if before_toggle_disable_status != after_toggle_disable_status:
ret['changes'][name] = True
if started is True:
ret['comment'] = ('Service {0} has been disabled,'
' and is running').format(name)
elif started is None:
ret['comment'] = ('Service {0} has been disabled,'
' and is in the desired state').format(name)
else:
ret['comment'] = ('Service {0} has been disabled,'
' and is dead').format(name)
return ret
# Service failed to be disabled
ret['result'] = False
if started is True:
ret['comment'] = ('Failed when setting service {0} to not start'
' at boot, and is running').format(name)
elif started is None:
ret['comment'] = ('Failed when setting service {0} to not start'
' at boot, but the service was already running'
).format(name)
else:
ret['comment'] = ('Failed when setting service {0} to not start'
' at boot, and the service is dead').format(name)
return ret
def _available(name, ret):
'''
Check if the service is available
'''
avail = False
if 'service.available' in __salt__:
avail = __salt__['service.available'](name)
elif 'service.get_all' in __salt__:
avail = name in __salt__['service.get_all']()
if not avail:
ret['result'] = False
ret['comment'] = 'The named service {0} is not available'.format(name)
return avail
def running(name,
enable=None,
sig=None,
init_delay=None,
no_block=False,
unmask=False,
unmask_runtime=False,
**kwargs):
'''
Ensure that the service is running
name
The name of the init or rc script used to manage the service
enable
Set the service to be enabled at boot time, ``True`` sets the service
to be enabled, ``False`` sets the named service to be disabled. The
default is ``None``, which does not enable or disable anything.
sig
The string to search for when looking for the service process with ps
init_delay
Some services may not be truly available for a short period after their
startup script indicates to the system that they are. Provide an
'init_delay' to specify that this state should wait an additional given
number of seconds after a service has started before returning. Useful
for requisite states wherein a dependent state might assume a service
has started but is not yet fully initialized.
no_block : False
**For systemd minions only.** Starts the service using ``--no-block``.
.. versionadded:: 2017.7.0
unmask : False
**For systemd minions only.** Set to ``True`` to remove an indefinite
mask before attempting to start the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
making any changes. This behavior is no longer the default.
unmask_runtime : False
**For systemd minions only.** Set to ``True`` to remove a runtime mask
before attempting to start the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
making any changes. This behavior is no longer the default.
.. note::
``watch`` can be used with service.running to restart a service when
another state changes ( example: a file.managed state that creates the
service's config file ). More details regarding ``watch`` can be found
in the :ref:`Requisites <requisites>` documentation.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
# Check for common error: using enabled option instead of enable
if 'enabled' in kwargs:
return _enabled_used_error(ret)
# Convert enable to boolean in case user passed a string value
if isinstance(enable, six.string_types):
enable = salt.utils.data.is_true(enable)
# Check if the service is available
try:
if not _available(name, ret):
if __opts__.get('test'):
ret['result'] = None
ret['comment'] = 'Service {0} not present; if created in this state run, it would have been started'.format(name)
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# lot of custom init script won't or mis implement the status
# command, so it is just an indicator but can not be fully trusted
before_toggle_status = __salt__['service.status'](name, sig)
if 'service.enabled' in __salt__:
before_toggle_enable_status = __salt__['service.enabled'](name)
else:
before_toggle_enable_status = True
unmask_ret = {'comment': ''}
if unmask:
unmask_ret = unmasked(name, unmask_runtime)
# See if the service is already running
if before_toggle_status:
ret['comment'] = '\n'.join(
[_f for _f in ['The service {0} is already running'.format(name),
unmask_ret['comment']] if _f]
)
if enable is True and not before_toggle_enable_status:
ret.update(_enable(name, None, skip_verify=False, **kwargs))
elif enable is False and before_toggle_enable_status:
ret.update(_disable(name, None, skip_verify=False, **kwargs))
return ret
# Run the tests
if __opts__['test']:
ret['result'] = None
ret['comment'] = '\n'.join(
[_f for _f in ['Service {0} is set to start'.format(name),
unmask_ret['comment']] if _f])
return ret
# Conditionally add systemd-specific args to call to service.start
start_kwargs, warnings = \
_get_systemd_only(__salt__['service.start'], locals())
if warnings:
ret.setdefault('warnings', []).extend(warnings)
if salt.utils.platform.is_windows():
for arg in ['timeout', 'with_deps', 'with_parents']:
if kwargs.get(arg, False):
start_kwargs.update({arg: kwargs.get(arg)})
try:
func_ret = __salt__['service.start'](name, **start_kwargs)
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
if not func_ret:
ret['result'] = False
ret['comment'] = 'Service {0} failed to start'.format(name)
if enable is True:
ret.update(_enable(name, False, result=False, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, False, result=False, skip_verify=False, **kwargs))
return ret
if init_delay:
time.sleep(init_delay)
# only force a change state if we have explicitly detected them
after_toggle_status = __salt__['service.status'](name, sig)
if 'service.enabled' in __salt__:
after_toggle_enable_status = __salt__['service.enabled'](name)
else:
after_toggle_enable_status = True
if (
(before_toggle_enable_status != after_toggle_enable_status) or
(before_toggle_status != after_toggle_status)
) and not ret.get('changes', {}):
ret['changes'][name] = after_toggle_status
if after_toggle_status:
ret['comment'] = 'Started Service {0}'.format(name)
else:
ret['comment'] = 'Service {0} failed to start'.format(name)
ret['result'] = False
if enable is True:
ret.update(_enable(name, after_toggle_status, result=after_toggle_status, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, after_toggle_status, result=after_toggle_status, skip_verify=False, **kwargs))
if init_delay:
ret['comment'] = (
'{0}\nDelayed return for {1} seconds'
.format(ret['comment'], init_delay)
)
if unmask:
ret['comment'] = '\n'.join([ret['comment'], unmask_ret['comment']])
return ret
def dead(name,
enable=None,
sig=None,
init_delay=None,
**kwargs):
'''
Ensure that the named service is dead by stopping the service if it is running
name
The name of the init or rc script used to manage the service
enable
Set the service to be enabled at boot time, ``True`` sets the service
to be enabled, ``False`` sets the named service to be disabled. The
default is ``None``, which does not enable or disable anything.
sig
The string to search for when looking for the service process with ps
init_delay
Add a sleep command (in seconds) before the check to make sure service
is killed.
.. versionadded:: 2017.7.0
no_block : False
**For systemd minions only.** Stops the service using ``--no-block``.
.. versionadded:: 2017.7.0
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
# Check for common error: using enabled option instead of enable
if 'enabled' in kwargs:
return _enabled_used_error(ret)
# Convert enable to boolean in case user passed a string value
if isinstance(enable, six.string_types):
enable = salt.utils.data.is_true(enable)
# Check if the service is available
try:
if not _available(name, ret):
if __opts__.get('test'):
ret['result'] = None
ret['comment'] = 'Service {0} not present; if created in this state run, it would have been stopped'.format(name)
else:
# A non-available service is OK here, don't let the state fail
# because of it.
ret['result'] = True
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
# lot of custom init script won't or mis implement the status
# command, so it is just an indicator but can not be fully trusted
before_toggle_status = __salt__['service.status'](name, sig)
if 'service.enabled' in __salt__:
if salt.utils.platform.is_windows():
# service.enabled in Windows returns True for services that are set
# to Auto start, but services set to Manual can also be disabled
before_toggle_enable_status = __salt__['service.info'](name)['StartType'] in ['Auto', 'Manual']
else:
before_toggle_enable_status = __salt__['service.enabled'](name)
else:
before_toggle_enable_status = True
# See if the service is already dead
if not before_toggle_status:
ret['comment'] = 'The service {0} is already dead'.format(name)
if enable is True and not before_toggle_enable_status:
ret.update(_enable(name, None, skip_verify=False, **kwargs))
elif enable is False and before_toggle_enable_status:
ret.update(_disable(name, None, skip_verify=False, **kwargs))
return ret
# Run the tests
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Service {0} is set to be killed'.format(name)
return ret
# Conditionally add systemd-specific args to call to service.start
stop_kwargs, warnings = _get_systemd_only(__salt__['service.stop'], kwargs)
if warnings:
ret.setdefault('warnings', []).extend(warnings)
if salt.utils.platform.is_windows():
for arg in ['timeout', 'with_deps', 'with_parents']:
if kwargs.get(arg, False):
stop_kwargs.update({arg: kwargs.get(arg)})
func_ret = __salt__['service.stop'](name, **stop_kwargs)
if not func_ret:
ret['result'] = False
ret['comment'] = 'Service {0} failed to die'.format(name)
if enable is True:
ret.update(_enable(name, True, result=False, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, True, result=False, skip_verify=False, **kwargs))
return ret
if init_delay:
time.sleep(init_delay)
# only force a change state if we have explicitly detected them
after_toggle_status = __salt__['service.status'](name)
if 'service.enabled' in __salt__:
after_toggle_enable_status = __salt__['service.enabled'](name)
else:
after_toggle_enable_status = True
if (
(before_toggle_enable_status != after_toggle_enable_status) or
(before_toggle_status != after_toggle_status)
) and not ret.get('changes', {}):
ret['changes'][name] = after_toggle_status
# be sure to stop, in case we mis detected in the check
if after_toggle_status:
ret['result'] = False
ret['comment'] = 'Service {0} failed to die'.format(name)
else:
ret['comment'] = 'Service {0} was killed'.format(name)
if enable is True:
ret.update(_enable(name, after_toggle_status, result=not after_toggle_status, skip_verify=False, **kwargs))
elif enable is False:
ret.update(_disable(name, after_toggle_status, result=not after_toggle_status, skip_verify=False, **kwargs))
return ret
def enabled(name,
skip_verify=False,
**kwargs):
'''
Ensure that the service is enabled on boot, only use this state if you
don't want to manage the running process, remember that if you want to
enable a running service to use the enable: True option for the running
or dead function.
name
The name of the init or rc script used to manage the service
skip_verify
Skip verifying that the service is available before enabling it.
``True`` will skip the verification. The default is ``False``,
which will ensure the service is available before enabling it.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
ret.update(_enable(name, None, skip_verify=skip_verify, **kwargs))
return ret
def disabled(name,
skip_verify=False,
**kwargs):
'''
Ensure that the service is disabled on boot, only use this state if you
don't want to manage the running process, remember that if you want to
disable a service to use the enable: False option for the running or dead
function.
name
The name of the init or rc script used to manage the service
skip_verify
Skip verifying that the service is available before disabling it.
``True`` will skip the verification. The default is ``False``,
which will ensure the service is available before disabling it.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
ret.update(_disable(name, None, skip_verify=skip_verify, **kwargs))
return ret
def masked(name, runtime=False):
'''
.. versionadded:: 2017.7.0
.. note::
This state is only available on minions which use systemd_.
Ensures that the named service is masked (i.e. prevented from being
started).
name
Name of the service to mask
runtime : False
By default, this state will manage an indefinite mask for the named
service. Set this argument to ``True`` to runtime mask the service.
.. note::
It is possible for a service to have both indefinite and runtime masks
set for it. Therefore, this state will manage a runtime or indefinite
mask independently of each other. This means that if the service is
already indefinitely masked, running this state with ``runtime`` set to
``True`` will _not_ remove the indefinite mask before setting a runtime
mask. In these cases, if it is desirable to ensure that the service is
runtime masked and not indefinitely masked, pair this state with a
:py:func:`service.unmasked <salt.states.service.unmasked>` state, like
so:
.. code-block:: yaml
mask_runtime_foo:
service.masked:
- name: foo
- runtime: True
unmask_indefinite_foo:
service.unmasked:
- name: foo
- runtime: False
.. _systemd: https://freedesktop.org/wiki/Software/systemd/
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if 'service.masked' not in __salt__:
ret['comment'] = 'Service masking not available on this minion'
ret['result'] = False
return ret
mask_type = 'runtime masked' if runtime else 'masked'
expected_changes = {mask_type: {'old': False, 'new': True}}
try:
if __salt__['service.masked'](name, runtime):
ret['comment'] = 'Service {0} is already {1}'.format(
name,
mask_type,
)
return ret
if __opts__['test']:
ret['result'] = None
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} would be {1}'.format(name, mask_type)
return ret
__salt__['service.mask'](name, runtime)
if __salt__['service.masked'](name, runtime):
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} was {1}'.format(name, mask_type)
else:
ret['comment'] = 'Failed to mask service {0}'.format(name)
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
def unmasked(name, runtime=False):
'''
.. versionadded:: 2017.7.0
.. note::
This state is only available on minions which use systemd_.
Ensures that the named service is unmasked
name
Name of the service to unmask
runtime : False
By default, this state will manage an indefinite mask for the named
service. Set this argument to ``True`` to ensure that the service is
runtime masked.
.. note::
It is possible for a service to have both indefinite and runtime masks
set for it. Therefore, this state will manage a runtime or indefinite
mask independently of each other. This means that if the service is
indefinitely masked, running this state with ``runtime`` set to
``True`` will _not_ remove the indefinite mask.
.. _systemd: https://freedesktop.org/wiki/Software/systemd/
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if 'service.masked' not in __salt__:
ret['comment'] = 'Service masking not available on this minion'
ret['result'] = False
return ret
mask_type = 'runtime masked' if runtime else 'masked'
action = 'runtime unmasked' if runtime else 'unmasked'
expected_changes = {mask_type: {'old': True, 'new': False}}
try:
if not __salt__['service.masked'](name, runtime):
ret['comment'] = 'Service {0} was already {1}'.format(name, action)
return ret
if __opts__['test']:
ret['result'] = None
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} would be {1}'.format(name, action)
return ret
__salt__['service.unmask'](name, runtime)
if not __salt__['service.masked'](name, runtime):
ret['changes'] = expected_changes
ret['comment'] = 'Service {0} was {1}'.format(name, action)
else:
ret['comment'] = 'Failed to unmask service {0}'.format(name)
return ret
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.