How to manage add zabbix templates to configured hosts without overwriting what is there

ansiblezabbix

I am trying to use ansible to manage how templates are added to the configured hosts on my Zabbix server. I am looking for a way to have the templates be added without overridding the templates that are already there.

For example, I have 5 servers. I need them to be configured with the following templates:

  • server0 needs Template A, B, C, D
  • server1 needs Template A, B, C, E
  • server2 needs Template A, B, C, D, F
  • server3 needs Template A, B, C, G
  • server4 needs Template D

I have the inventory file organized by the templates, since there are far less templates in my system than servers. In the Example it would look like:

[template_a_b_c]
server0
server1
server2
server3


[template_d]
server0
server2
server4  

etc.
With the configuration like this, my ansible "zabbix" role has tasks for each template. But for servers like server2, when the template_d.yml task runs, it will overwrite the templates that tempalte_a_b_c.yml linked. This is the behavior I am trying to avoid.

I realize that I could reconfigure my ansible role to be organized by host and have a task for each, but I have hundreds of hosts and growing, so that will not scale. Is ansible just not there yet or is there a flag in ansible'szabbix_host that I could make use of?

Thanks.

Best Answer

You can construct template list based on hosts' group membership and execute zabbix_host only once.

inventory:

[mygr1]
srv1
srv2
srv3

[mygr2]
srv2

playbook:

---
- hosts: mygr1:mygr2
  gather_facts: no
  vars:
    template_map:
      mygr1: [template_a, template_b]
      mygr2: [template_c]
  tasks:
    - name: Generate template list
      set_fact:
        template_list: >
                       {{ group_names
                          | intersect(template_map.keys())
                          | map('extract',template_map)
                          | list
                          | sum(start=[]) }}
    - debug:
        msg: "{{ template_list }}"

result:

ok: [srv1] => {
    "msg": [
        "template_a",
        "template_b"
    ]
}
ok: [srv2] => {
    "msg": [
        "template_a",
        "template_b",
        "template_c"
    ]
}
ok: [srv3] => {
    "msg": [
        "template_a",
        "template_b"
    ]
}

template_list is formed in this sequence: take names of groups current host is member of, intersect it with known names from template_map, extract list of templates for each remaining name, convert result to list (from map-generator) and flatten resulting list of lists into single list.

Related Topic