Saltstack get grains of a minion in orchestration

2.7k Views Asked by At

I'm using salt-cloud to deploy VMs and I'm trying to get them registred in my DNS with the Saltstack Reactor system.

I have a reactor.conf with this trigger:

reactor:
  - 'salt/cloud/*/created':           # Add a VM
    - /srv/reactor/initialize_vm.sls

initilize_vm.sls :

invoke_orchestrate_add_to_dns:
  runner.state.orchestrate:
    - mods: orch.add_to_dns
    - pillar:
        event_name: {{ name }}
        event_profile: {{ profile }}

orch/add_to_dns.sls:

{% set name = pillar['event_name'] %}
{% set profile = pillar['event_profile'] %}

vm-add-dns-{{ name }}:
  sqlite3.row_present:
    - db: /var/lib/powerdns/pdns.sqlite3
    - table: records
    - where_sql: "name='{{ name }}' and type='A'"
    - data:
        domain_id: 1
        name: {{ name }}
        type: A
        content: {{ ??? }}
        ttl: 300
        prio: 0
        disabled: 0

I just need to know the IP address of the new minion. But as the orchestration run on the master, I can't just do a content: {{ grains['fqdn_ip4'] }}.

Any ideas to get minions informations ?

2

There are 2 best solutions below

1
On

You can use the Salt Mine to get information from minions. To use the Salt Mine you need to know which minion you want to have information from. Luckily the reactor receives the data from the event bus. data['id'] contains the minion ID.

In the Salt Mine you can add a function to retrieve a minions IP like this:

mine_functions:
  public_ip4:
    - mine_function: grains.get
    - fqdn_ip4

Now you can use mine.get in your sls files to get the IP address from a minion. In your case it will be the minion ID you just received from the event bus like this:

{%- for server, addrs in salt['mine.get'](data['id']', 'public_ip4') %}
  {{ addrs[0] }}
{% endfor %}

Notes:

  • I don't use Salt Cloud and orchestration for DNS so I can't combine your code with mine and check if it works. I hope it will be useful for you :)
  • I named the mine public_ip4 instead of fqdn_ip4. It's to
    clarify that this is a name in the Salt Mine and not the Grain you
    are requesting.
0
On

If you don't wish to add configuration you can also do the following:

{% set ip = salt.saltutil.runner('salt.execute', [data['id']], {'fun': 'grains.get', 'kwarg': {'key':'fqdn_ip4'}})[data['id']] %}

Or as mentioned in the comments:

{% set ip = salt['saltutil.runner']('cache.grains', tgt=data['id'])[data['id']]['fqdn_ip4'][0] %}

Figured I'd add this here as a reference for others.