Search code examples
salt-project

SaltStack - generate pillar value base on what folder it is being executed


I'm trying to learn SaltStack and now I'm facing a problem. I have a property file (propertyfile.properties) with values being populated by salt pillar. Now this property file exists in multiple directories. The issue that I have is that I want the values of the property file be populated/rendered by salt pillar.get function base on what directory currently it is into. To give you more idea, let's consider this example:

propertyfile.property (in directory 1)
name={{ salt['pillar.get']['dir1.name'] }}


propertyfile.property (in directory 2)
name={{ salt['pillar.get']['dir2.name'] }}

#pillar
dir1.name=dir1
dir2.name=dir2

note that the property file is only one and is generated by salt to multiple directories via loop like this:

{% for dir in 'dir1', 'dir2' %}
propertyfile_properties_{{ dir }}:
    file.managed:
        - name: /home/devuser/{{ dir }}/propertyfile.properties
        - source: {{ propertyfile_source }}
        - source_hash: {{ propertyfile_source }}.MD5
        - template: jinja
        - show_diff: True
        - makedirs: True
{% endfor %}

Any ideas? Your help is very much appreciated. Thanks


Solution

  • You can do this by passing each directory to the template as context, as it's rendered:

    # In .sls
    {% for dir in salt['pillar.get']("directories") %}
    propertyfile_properties_{{ dir }}:
        file.managed:
            - name: /home/devuser/{{ dir }}/propertyfile.properties
            - source: salt://path/to/template.jinja
            - template: jinja
            - context:
                dir: {{ dir }}
    {% endfor %}
    
    # In template:
    dirname={{ dir }}
    fullpath=/home/devuser/{{ dir }}/propertyfile.properties
    
    # In pillar:
    directories:
      - dir1
      - dir2
      - ...and so on
    

    Note the extra indentation of the contents of the context dictionary. There's an explanation of why that's sometimes necessary here.