Search code examples
pythonjinja2salt-project

salt-stack : adding grains to minion or to top file


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)

Solution

  • 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