Search code examples
salt-project

Is there a Salt requisite that will execute a state only if another state has not run


I have a situation where I only want to execute a salt state if another state does not run. Is that possible?

E.g.

  • State1 manages file-abc
  • State2 has an onchanges requisite that will only run if the file-abc changes
  • State3 should only run if State2 does not execute.

The expected behavior is:

If file-abc changes:
   execute State2

If State2 did not execute:
   execute State3

The requirement here is that State3 should run if State2 doesn't, and there might be a lot of future reasons for State2 to run beyond a single file changing.

State1

test-state-file1:
  file.managed:
    - name: /data/test-file1
    - source: salt://foo-states/test-file

State2

test-state2-echo:
  cmd.run:
    - name: echo "Test State 2"
    - onchanges:
      - file: /data/test-file1

State3 - Only run if State 1 and 2 don't run.

test-state3-echo:
  cmd.run:
    - name: echo "Test State 3"

Solution

  • There's no type of requisite that's a negative requisite for other states. The way to accomplish what you're asking (though maybe not what you want), is to use unless which executes a command. Try:

    one:
      test.succeed_without_changes
    
    two:
      cmd.run:
        - name: echo 'hi' > /tmp/fun.txt
        - onchanges:
          - test: one
    
    three:
      test.succeed_with_changes:
        - unless:
          - grep 'hi' /tmp/fun.txt
    

    You'll see three run. Change it to

    one:
      test.succeed_with_changes
    

    And you'll see two run, but not three.

    Depending on what you are really trying to accomplish, this might suit you, but it may be that there's a better way to do what you're trying to do.