Search code examples
salt-project

Access listed grain values


I'm trying to access listed grain values from state file, need help on this.

State file is as below

{% set list = grains['selinux'] %}

echo {{ list }}:
  cmd.run

But when i run the state file got the error.

# salt '*' state.sls list_grains
client1:
    Data failed to compile:
----------
    Rendering SLS 'base:list_grains' failed: mapping values are not allowed in this context
ERROR: Minions returned with non-zero exit code
[root@server ~]# vim /srv/salt/list_grains.sls

grain values accessed are as below

# salt '*' grains.item selinux
client1:
    ----------
    selinux:
        ----------
        enabled:
            True
        enforced:
            Permissive

Solution

  • The selinux grain is a dictionary/map like:

    selinux:
      enabled: True
      enforced: Permissive
    

    So in a state ID you cannot have dictionary/map. You can pick the required dictionary key like list.enabled or list.enforced.

    For example, the below state ID will output Permissive:

    {% set list = grains['selinux'] %}
    
    echo {{ list.enforced }}:
      cmd.run
    

    If you want to get the complete dict as output, you can use a module like test.echo:

    {% set list = grains['selinux'] %}
    
    show-selinux-grains:
      module.run:
        - name: test.echo
        - text: "{{ list }}"