5

It is said in saltstack documentation that adding :

{% set node_type = salt['grains.get']('node_type', '') %}

{% if node_type %}
  'node_type:{{ self }}':
    - match: grain
    - {{ self }}
{% endif %}

to

/srv/salt/top.sls

will create a grain called node_type

I added the code below to the top file, and I would like to know why I can't see node_type in my minion :

myHost ~ # service salt-master restart; service salt-minion restart;
myHost ~ # salt '*' grains.get "node*"

The last command returns nothing. And I think it is normal because I haven't defined node_type in /etc/salt/grains

This makes me ask a question : what is the difference between :

  • Declaring node_type in top.sls file

and

  • Adding it simply to grains file ( /etc/salt/grains) or to minion file ( /etc/salt/minion)
Mureinik
  • 297,002
  • 52
  • 306
  • 350
4m1nh4j1
  • 4,289
  • 16
  • 62
  • 104

2 Answers2

9

You can't create a grain in the top file. Can you point me to the documentation that's telling you that? All a top file does is define which Salt states (sls files) should be applied to which servers.

You can use grains to match in your top file. You don't declare grains in your top file.

You can create a Salt state that will add a grain to your minion for you and reference that in your top file. Docs here: http://docs.saltstack.com/en/latest/ref/states/all/salt.states.grains.html#salt.states.grains.present

Here's an example

$ cat /srv/salt/top.sls

base:
  'server01':
    - rolegrain

$ cat /srv/salt/rolegrain.sls

role:
  grains.present:
    - value: application_server

When running a highstate, this would cause your server with the Salt id of server01 to have a grain with the key role and value application_server.

That would look like this:

salt server01 state.highstate

or

salt server01 state.sls rolegrain

Then you'd get this output

salt server01 grains.item role

server01:
    ----------
    role:
        application_server

For completeness, here's some docs.

The top file: http://docs.saltstack.com/en/latest/ref/states/top.html

Grains: http://docs.saltstack.com/en/latest/topics/targeting/grains.html

Utah_Dave
  • 4,531
  • 24
  • 23
1

You can create a top file where you do advanced minion targeting. The targeting can be done based on the matched type seen in https://docs.saltstack.com/en/latest/ref/states/top.html#advanced-minion-targeting

What I have in my top.sls file is:

'site:private':
    - match: grain
    - path.to.state1
    - path.to.state2

Assuming that your target minion has a grain with key 'site' and value 'private', you can do:

salt -v 'minion_id' state.highstate test=True

This will pickup all the state assigned in the top.sls file above.

Pier
  • 351
  • 2
  • 4
  • 16