SaltStack: Stop on first error

saltstack

I have a sls file for SaltStack which looks like this:

etckeeper:
  pkg.installed

etckeeper_extra_packages:
  pkg.installed:
    - pkgs:
      - hwinfo

{%- if not salt['file.directory_exists' ]('/etc/.git') %}
init_etckeeper:
  cmd.run:
    - name: etckeeper init
{%- endif %}

gitconfig_etckeeper_name:
  git.config_set:
    - name: user.name
    - value: Etckeeper running on {{grains.id}}
    - repo: /etc

gitconfig_etckeeper_mail:
  git.config_set:
    - name: user.email
    - value: root@{{grains.id}}
    - repo: /etc


{%- if not salt['file.directory_exists' ]('/etc/.git') %}
initial_commit_etckeeper:
  cmd.run:
    - name: etckeeper commit -m "initial commit"
{%- endif %}

I would like to make this fail on the first non successful state/command/… (of to call this?)

For example if pkg.installed of etckeeper fails, I don't want the hwinfo to get installed.

How to do this?

You can compare this question to set -e in the shell:

-e Exit immediately if a command exits with a non-zero status.

Best Answer

You can just require the first state in the second one:

etckeeper:
  pkg.installed

etckeeper_extra_packages:
  pkg.installed:
    - pkgs:
      - hwinfo
    - require:
      - pkg: etckeeper

It will not stop the whole execution. If you have some other states that can be applied without the package being installed, it will. That's requisites: https://docs.saltstack.com/en/latest/ref/states/requisites.html

If you absolutely want to stop the execution right now, you can use

etckeeper:
  pkg.installed:
    - failhard: True

That's the failhard global option: https://docs.saltstack.com/en/latest/ref/states/failhard.html. Don't abuse its use.