Andrey Bistrinin
Andrey Bistrinin

Reputation: 910

Ansible and Jinja2 variables combination

I have a playbook that generates bash script of two Ansible lists.

In Jinja2 template file I am trying to run for loop on one Ansible list and then run another for loop inside it based on output from first one.

Here is my Ansible defaults.yml:

##################################
#        FIRST LOOP              #
##################################

prefix_list:
  - prefix1
  - prefix2

##################################
#         SECOND LOOP            #
##################################
prefix1:
  - kola
  - wlcom
  - linkstory



prefix2:
  - kola

Jinja2 Template:

#!/bin/bash
date=$(date +'%Y.%m' -d "month ago")
exdate=$(date +'%Y.%m' -d "{{ exdate }} months ago")
{% for prefix in prefix_list %}
    {% for index in prefix %}
        {{ index }}
    {% endfor %}
{% endfor %}

Result:

#!/bin/bash
date=$(date +'%Y.%m' -d "month ago")
exdate=$(date +'%Y.%m' -d "12 months ago")
            p
            r
            e
            f
            i
            x
            1
                p
            r
            e
            f
            i
            x
            2

Upvotes: 0

Views: 892

Answers (2)

techraf
techraf

Reputation: 68439

Use the vars lookup plugin to refer to variables (instead of iterating over the characters in their names, as you do now).

Your internal loop should be:

{% for index in lookup('vars', prefix) %}

Also check how to control whitespace in Jinja2, because the output you'll get with your current code will be strangely indented.

Upvotes: 2

oxfn
oxfn

Reputation: 6840

I'm not much experienced with Ansible, but I guess you should try to nest your lists in defaults.yml

Case 1 - nested lists

(This is what your template expects)

prefix_list:
  -
    - kola
    - wlcom
    - linkstory

  -
    - kola

Case 2 - dictionary

(When you need prefix1 and prefix2 in your template

prefix_list:
  prefix1:
    - kola
    - wlcom
    - linkstory

  prefix2:
    - kola

In this case Jinja loop should be fixed this way

{% for prefix in prefix_list %}
    {% for index in prefix_list[prefix] %}
        {{ index }}
    {% endfor %}
{% endfor %}

Upvotes: 0

Related Questions