Jinja array collection in SaltStack


configuration saltstack apache

Saltstack states allow for explicit configuration management, but the real power of saltstack is obtained when states are combined with pillar data and even further with grain data.

I needed to combined multiple pillar environment elements into one collection in a apache state sls file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
{% set ENVIRONMENT_A = pillar['environment_a'] %}

{% set ENV_COLLECTION = [] %}

{% if pillar['environment_b'] is defined %}
{% do ENV_COLLECTION.append( "NICE_ENV_VAR " ~ pillar['environment_b']['top_notch_env_var'] ) %}
{% do ENV_COLLECTION.append( "MORE_ENV " ~ pillar['environment_b']['even_better_env'] ) %}
{% endif %}

{% for env_key, env_value in ENVIRONMENT_A.items() %}
{% do ENV_COLLECTION.append( env_key ~ " " ~ env_value ) %}
{% endfor %}

/etc/httpd/conf.d/site.conf:
  apache.configfile:
    - config:
      - VirtualHost:
          - this: '*:443'
              {% if ENV_COLLECTION | length %}
              SetEnv:
                {% for env_part in ENV_COLLECTION %}
                - {{ env_part }}
                {% endfor %}
              {% endif %}