Link zabbix template using SaltStack Events & Reactor

Link zabbix template using SaltStack Events & Reactor

How to use SaltStack, Event, Reactor and pyzabbix to link zabbix template to host.

  • Enable Reactor on your SaltStack master:

    Edit your master configuration file and add reactor configuration location.

    For example:

    In /etc/salt/master add default_include: master.d/*.conf.

    More on SaltStack Reactor System

  • Reactor configuration
    In our example, in /etc/salt/master.d/reactor.conf:

reactor:
  - 'link-template-zabbix':
    - /srv/salt/reactor/link-template-zabbix.sls
  • Create a sls state:
    Replace TARGET with minion_id where python script is located.
link_template_zabbix:
  local.cmd.run:
    - tgt: TARGET
    - arg:
      - /usr/local/bin/zabbix_linktemplate.py {{ data.id }} '{{ data.data.zabbix_template }}'
  • Python script to link zabbix template using pyzabbix
#!/usr/bin/env python

import socket
import os
import sys
from pyzabbix import ZabbixAPI

ZABBIX_SERVER = 'https://zabbix.example.com/'
ZABBIX_USER = 'User'
ZABBIX_PASSWORD = 'PassWord'

# Create connection to the zabbix api
zapi = ZabbixAPI(ZABBIX_SERVER)
zapi.login(ZABBIX_USER, ZABBIX_PASSWORD)

def get_host_id(fqdn):
    response = zapi.host.get(
        output='extend',
        filter={"host": fqdn}
    )
    if not response:
        return "not found"
    else:
        result = response[0]["hostid"]
        return result


def get_template_id(template_name):
    response = zapi.template.get(
        output='extend',
        filter={"host": template_name}
    )
    if not response:
        return "not found"
    else:
        result = response[0]["templateid"]
        return result

if __name__ == '__main__':

    fqdn = str(sys.argv[1])
    template = str(sys.argv[2])

    host_id = get_host_id(fqdn)
    template_id = get_template_id(template)

    if host_id == "not found":
        print 'Host not found in Zabbix : %s' % fqdn
        sys.exit(42)
    elif template_id == "Not found":
        print 'Template not found in Zabbix : %s' % template
        sys.exit(42)
    else:
        response = zapi.template.massadd(
            hosts=[host_id],
            templates=[template_id]
        )
    print '%s is now linked to %s on zabbix server' % (fqdn, template)
  • Add an event to your state:
link-template-zabbix:
  event:
    - send
    - data:
        zabbix_template: 'Template Name'

If your host in Zabbix is the same as your minion_id, it's enough. Or you can add hostname to data:

link-template-zabbix:
  event:
    - send
    - data:
        zabbix_template: 'Template Name'
        hostname: 'hostname'

In this case, you will have to replace {{ data.id }} by {{ data.data.hostname }} in reactor sls state.

More on SaltStack Event System

Now when you apply state which includes event, reactor will match tag, and apply sls to link Zabbix Template Name associated.