Created
September 5, 2018 17:34
-
-
Save geekq/f3c21c2045a0a3253cf12e4f06422c46 to your computer and use it in GitHub Desktop.
ansible lookup_plugin to generate a multihost zabbix expression
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import (absolute_import, division, print_function) | |
__metaclass__ = type | |
# Run with `python app_zabbix.py` to execute doctests | |
import sys | |
from ansible.plugins.lookup import LookupBase | |
try: | |
from __main__ import display | |
except ImportError: | |
from ansible.utils.display import Display | |
display = Display() | |
class LookupModule(LookupBase): | |
def run(self, terms, variables=None, **kwargs): | |
"""Helpers for appserver registering in zabbix. | |
>>> hosts = ['host-01', 'host-02', 'host-03'] | |
>>> lookup('app_zabbix', 'service_trigger_expr', hosts, '125s', '300s') | |
['({host-01:apphealth.status.max(125s)} and not {host-01:apphealth.status.nodata(300s)}) + ({host-02:apphealth.status.max(125s)} and not {host-02:apphealth.status.nodata(300s)}) + ({host-03:apphealth.status.max(125s)} and not {host-03:apphealth.status.nodata(300s)}) <= 1.5'] | |
""" | |
return self.lookup_impl(*terms) | |
def lookup_impl(self, *terms): | |
mode = terms[0] | |
if mode == "service_trigger_expr": | |
if len(terms) != 4: | |
display.v("service_trigger_expr lookup mode requires exactly 4 arguments: mode, array of hosts, timespan, nodata_timespan") | |
hosts = terms[1] | |
timespan = terms[2] | |
nodata_timespan = terms[3] | |
exprs = ["({" + host + ":apphealth.status.max(" + timespan + ")} and not {" + host + ":apphealth.status.nodata(" + nodata_timespan + ")})" for host in hosts] | |
threshold = len(hosts) * 0.5 | |
return [" + ".join(exprs) + " <= " + str(threshold)] | |
def lookup(placeholder, *args): | |
"""Enable using `lookup(...` in doctests""" | |
return testfixture.lookup_impl(*args) | |
if __name__ == "__main__": | |
"""When used as standalone file and not as library - run unit tests""" | |
import doctest | |
testfixture = LookupModule() | |
sys.exit(doctest.testmod()[0]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment