Search code examples
python-3.xyamljinja2

If condition does not work in state triggered by reactor


I am using an if condition utilizing grain item within a state which triggered by reactor. and I got an error message Jinja variable 'dict object' has no attribute 'environment'

=================================================

REACTOR config:

cat /etc/salt/master.d/reactor.conf
reactor:

  - 'my/custom/event':
    - salt://reactor/test.sls

==============================

test.sls

cat /srv/salt/reactor/test.sls

sync_grains:
  local.saltutil.sync_grains:
    - tgt: {{ data['id'] }}

{% if grains['environment'] in ["prod", "dev", "migr"] %}
test_if_this_works:
  local.state.apply:
    - tgt: {{ data['id'] }}
    - arg:
      - dummy_state
{% endif %}

===================================

dummy_state/init.sls

cat /srv/salt/dummy_state/init.sls
create_a_directory:
  file.directory:
    - name: /tmp/my_test_dir
    - user: root
    - group: root
    - makedirs: True

=================================================

salt 'salt-redhat-23.test.local' grains.item environment
salt-redhat-23.test.local:
    ----------
    environment:
        prod

=================================================

salt-redhat-23 ~]# cat /etc/salt/grains
role: MyServer
environment: prod

================================================

If I change the test.sls and use instead of custom grain a grain which salt-master is taking by default then it will works. Also it will work without the if condition in the state.

Do you know why this is happening?

Thank you all in advance.


Solution

  • Issue resolved.

    You cannot use custom grains with Reactor directly, you need to call another state to be able to add condition there.

    for instance:

    cat /etc/salt/master.d/reactor.conf

    reactor:
    
    - 'my/custom/event':
      - salt://reactor/test.sls
    

    test.sls

    # run a state using reactor
    test_if_this_works:
      local.state.apply:
        - tgt: {{ data['id'] }}
        - arg:
          - reactor.execute
    

    execute.sls

    {% set tst = grains['environment'] %}
    
    {% if tst in ['prod', 'dev', 'test', 'migr'] %}
    create_a_directory:
      file.directory:
        - name: /tmp/my_test_dir
        - user: root
        - group: root
        - makedirs: True
    {% endif %}
    

    this will work with the if condition, if you try to add the if statement on the test.sls it will not work.