Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@paskal
Last active July 26, 2018 03:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paskal/caef035c60a49c9d4a69c6fad03a9c56 to your computer and use it in GitHub Desktop.
Save paskal/caef035c60a49c9d4a69c6fad03a9c56 to your computer and use it in GitHub Desktop.
Recuresively resolve Zabbix user macro within string
import re
import logging
def expand_macro(zapi, itemid, hostid, macro):
"""Expand macro in passed string, recursively. Non-existent macro resolved to empty string.
Example:
# {$MACRO} resolves to "test macro in ${ENV} environment"
# {$ENV} resolves to "dev"
>>> print(expand_macro(zapi, 12345, 54321, "string with {$MACRO}"))
"string with test macro with dev environment"
Args:
zapi (ZabbixAPI): https://github.com/gescheit/scripts/tree/master/zabbix
itemid (str or int): itemid of the item to expand
hostid (str or int): hostid of the item to expand
macro (str): string to expand
Returns:
str: string with expanded macros in it
"""
# no macro left in passed string, return it
if '{$' not in macro:
return macro
# macro inside but not yet called
if not re.match(r'^{\$.+?}$', macro):
return re.sub('{\$.+?}', lambda x: expand_macro(zapi, itemid, hostid, x.group()), macro)
# flow for case macro is the only thing we have in passed string - we need to extract it
result = zapi.usermacro.get({'hostids': hostid, 'output': ['value'], 'filter': {'macro': macro}})
# we found result and expanding it in case there are more macro inside
if result:
return re.sub('{\$.+?}', lambda x: expand_macro(zapi, itemid, hostid, x.group()), result[0]['value'])
# we haven't found result and need to go deeper
template_id = zapi.item.get({'itemids': itemid, 'output': ['templateid']})[0]['templateid']
if template_id == 0:
logging.error("Reached parent template for itemid %s on host %s and didn't found macro %s, replacing with empty string", itemid, hostid, macro)
return ''
template_host_id = zapi.item.get({'itemids': template_id, 'output': [], 'selectHosts': ['hostid']})[0]['hosts'][0]['hostid']
return expand_macro(zapi, template_id, template_host_id, macro)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment