Search code examples
jinja2salt-project

saltstack using mine.get to get value


Situation:

I have multiple minions where I want to configure monitoring for our infrastructure. The probes and thresholds are configured in the grains of the minions, that is working fine.

Now I need to configure the monitoring server where I need to configure each minion with there IP, hostname and probes.

After some research I have found saltstack mine.get function and playing around a little bit but I am stuck with the output I need.

Code:

For every node there will be a "host".cfg.bak file

{% set hostname = salt['mine.get']('nagios:enabled', 'hostname', tgt_type='grain') %}

{% for node in hostname %}

create node {{node}}:
  file.managed:
    - source: salt://nagios/files/templates/server/node.cfg.j2
    - probedir: {{nagios.client_probes_path}}
    - name: {{nagios.server_config}}{{node}}.cfg.bak
    - host: {{node}}
    - template: jinja

{% endfor %}

Inside the "host".cfg.bak file

{% set monitoring = salt['mine.get']('fqdn:' + host, 'monitoring', tgt_type='grain') %}
{% set ipv4 = salt['mine.get']('fqdn:' + host, 'ip', tgt_type='grain') %}

define host {
  use linux-server
  host_name {{host}}
  alias {{host}}
  address {{ipv4}}
  max_check_attempts 5
  check_period 24x7
  notification_interval 30
  notification_period 24x7
}

{{monitoring}}

The results I get from ipv4 and monitoring are:

{'HOSTNAME': 'IP_ADDRESS'}

{'HOSTNAME': {'probe': {'check_apt': {'check_apt': {}}, 'check_swap': {'check_swap': {'c': '10%', 'w': '20%'}}, 'check_user': {'check_user': {'c': 10, 'w': 5}}, 'check_yum': {'check_yum': {}}, 'data_disk': {'check_disk': {'c': '2%', 'p': '/data', 'w': '5%'}}, 'root_disk': {'check_disk': {'c': '2%', 'p': '/', 'w': '5%'}}}}}

I am only interested in the second element of both ipv4 and monitoring.

Have tried multiple things like {{monitoring[1]}} but I receive the error that element 1 is not there.

Hope someone can give me some directions or maybe there is a other way to get the grains from multiple minion. unfortunately need to use nagios for the time being.


Solution

  • Those are dicts, not lists.

    mine.get returns data from all matching minions, keyed by their minion id.

    If you're only expecting one result, you can get it via:

    {% set value = salt["mine.get"](tgt, fun).values() | first %}