Search code examples
salt-project

salt file.directoy_exists check in a loop


Trying to loop over a list of folder to check if the directory exists and then to clean that directory (remove all files).

{% set FOLDERS_TO_CLEAN = ['C:\Test\Folder1'] %}
{% for FOLDER in FOLDERS_TO_CLEAN %}
{% if salt['file.directory_exists']({{ FOLDER }}) %}
{{ FOLDER }}_delete:
file.directory:
  - name: {{ FOLDER }}
  - clean: True
  - failhard: True
{% endif %}
{% endfor %}

The problematic line is the third line. With the variable FOLDER that ends up in a syntax error but when i change that to my test string it works. Any idea what i can change so that it works?


Solution

  • You need to have single quotes around {{ FOLDER }} in the if statement. Like this:

    {% set FOLDERS_TO_CLEAN = ['C:\Test\Folder1'] %}
    {% for FOLDER in FOLDERS_TO_CLEAN %}
    {% if salt['file.directory_exists']('{{ FOLDER }}') %}
    {{ FOLDER }}_delete:
    file.directory:
      - name: {{ FOLDER }}
      - clean: True
      - failhard: True
    {% endif %}
    {% endfor %}