cmoe
cmoe

Reputation: 191

Loop through a directory on a windows minion using Salt State

I need to work with folders and files in a directory on a minion not master. This is what I have tried but it's not working. Unfortunately, salt documentation is not very explicit in their examples.

{% set folderLocation = 'D:\\Myfolder' %} 
{% for folder in folderLocation %}
  {% if folder == "Something" %}
      DeleteFolder:
          file.absent:
              - name = 'D:\\Myfolder\\folder' 
  {% endif %}
{% endfor %}

Basically, I want to get the content of Myfolder like how you use Get-Item/Get-ChildItem 'D:\\Myfolder' in powershell and then loop through it. How can I achieve this please in a salt state? I want to avoid using cmd.script or cmd.run. "Myfolder" is on the minion.

Upvotes: 0

Views: 557

Answers (1)

seshadri_c
seshadri_c

Reputation: 7340

You can use the file.find module to get the contents of a given path.

For a simple operation like delete, that you have shown in the question, you can write it as (without having to iterate):

delete-myfolder-files:
  module.run:
    - file.find:
        - path: "D:/MyFolder/"
        - mindepth: 1
        - delete: fd

The above state will delete all files and directories (represented by fd), in the given path, but excluding the base directory because of mindepth.

You could also save the results of the "find" operation into a variable, and use it.

{% set dir_contents = salt['file.find'](path="D:/MyFolder/", type="fd", mindepth=1) %}

{% for item in dir_contents %}
# Do something
{% endfor %}

Now the dir_contents variable will have an array of files and directories (specified by type). We can iterate over each "item" and do something else with it

Upvotes: 1

Related Questions