robert@notes: ~/posts — zsh
➜ robert@notes ~/posts git:(master) cat ~/.motd
Robert's notes - Notes on Go, Kubernetes, Terraform/OpenTofu, AWS and DevOps culture.
➜ robert@notes ~/posts git:(master) ls ~
➜ robert@notes ~/posts git:(master) glow pass-variables-to-jinja-template-in-salt.md

How to pass variable to Jinja template in Salt

Salt

Yesterday I faced a quite interesting problem. In my SLS definition I was iterating over a hash of hashes and wanted to pass the hash from the current iteration to a Jinja template. To make it more clear, let me show you the problem in the code:

{% for vhost in pillar['vhosts'] %}
/etc/httpd/conf.d/{{ vhost.name }}.conf:
  file.managed:
    - template: jinja
    - source: salt://httpd/files/vhost/vhost_template.conf.jinja
    - user:     apache
    - group:    apache
    - mode:     644
    - require:
      - pkg: httpd
{% endfor %}

I simply wanted to use the variable vhost in my template. The variable vhost is nothing more than a hash with parameters for each vhost. We can solve this problem by using context in the salt definition. Here is the final version of my sls snippet (aka the solution):


{% for vhost in pillar['vhosts'] %}
/etc/httpd/conf.d/{{ vhost.name }}.conf:
  file.managed:
    - template: jinja
    - source: salt://httpd/files/vhost/vhost_template.conf.jinja
    - user:     apache
    - group:    apache
    - mode:     644
    - require:
      - pkg: httpd
    - context:             # set up context for template
        vhost: {{ vhost }} # it makes vhost hash available inside
                           # Jinja template under the name vhost
{% endfor %}

Of course you can pass as many variables as you want via the context.

–robert

➜ robert@notes ~/posts git:(master) cat FEEDBACK