Search code examples
jinja2salt-project

How can I retrieve a list of directories under /srv/salt/projects in the /srv/salt/top.sls


I'm trying to use a for loop like below in my /srv/salt/top.sls file.

   {%- set prjlist = salt['file.find']('/srv/salt/projects',type='d',mindepth=1,maxdepth=1,print='name') %}
   # {{ prjlist }}
   {%- for prj in prjlist %}
      'role:{{ prj }}_server':
        - match: pillar
        - projects.{{ prj }}.server
   {%- endfor %}

When I run "salt -l debug myhost state.apply test=True" doesn't match the expected role with the for block above. However if I replace the prjlist assignment with the hardcoded list that find.file should be returning like with

{%- set prjlist = ['expected'] %}

then salt finds the role as expected ¯\_(⊙︿⊙)_/¯.

If I do a "salt-call -l debug state.show_highstate" and look at the rendered top.sls output, when using salt['file.find'] command the comment line is shown as

#[u'expected']

But if I use a hardcoded list the comments becomes

#['expected']

Besides that the rendered blocks look the same.

I'm using version 2018.3.0 (Oxygen).

Is there anything wrong with the salt['file.find'] line ?

Is there another, better way I should be using to get a list of the directories under /srv/salt/projects on the salt-master ?


Solution

  • Use cp.list_master_dirs instead.

    {% for path in salt['cp.list_master_dirs']() if salt['file.dirname'](path) == 'projects' %}
      {% set prj = salt['file.basename'](path) %}
      'role:{{ prj }}_server':
        - match: pillar
        - projects.{{ prj }}.server
    {% endfor %}