Home > Blockchain >  Ansible can't find variable defined in jinja2 template during runtime
Ansible can't find variable defined in jinja2 template during runtime

Time:08-12

I'm having currently a troublesome Ansible and Template problem and would like to ask for some help.

My goal is to create a single config file on the destination from multiple template files. This Task is not that complicated but here is the catch. The following config would catch every template file but it is not possible to parse only specific templates for a group:

{% for template_name in lookup('ansible.builtin.fileglob', '{{ role_path }}/templates/*.j2', wantlist=True)  %}
{{ lookup('template', template_name) }}

{% endfor %}

So in my youthful recklessness, i thought i could create a list in the group_vars/groupXY.yaml with the names of the tempalt-files that should be parsed and loop it with an outer for loop:

applicable_templates:
  - template-1.yaml.j2
  - template-2.yaml.j2
  - template-3.yaml.j2
  - template-4.yaml.j2

main.yaml:

- name: Create config from multiple template files
  blockinfile:
    dest: "/etc/deamon/deamon.conf"
    block: "{{ item }}"
  loop: "
{% for i in applicable_templates %}
  {{ lookup('template', '{{ role_path }}/templates/{{ i }}') }}

{% endfor %}"

It could have been so easy but while executing this script ansible raises this error:

fatal: [ansible-node]: FAILED! => {"msg": "'i' is undefined"}

This is due to the fact, that the lookup command can't find the i variable because - I assume - Ansible searches for the Variables defined in the Ansible-Files. This obviously can't work since i is defined during the runntime and inside the jinja2 syntax.

Does anybody have a hint or a solution for this problem?

Thank you and best!

CodePudding user response:

You meant to do this:

- name: Create config from multiple template files
  blockinfile:
    dest: /etc/deamon/deamon.conf
    marker: "# rendering {{ item }}"
    block: |
      {{ lookup('template', '{{ role_path }}/templates/{{ item }}') }}
  loop: "{{ applicable_templates }}"
  • Related