'ansible loop variable in a template

in a j2 ansible template, I have below section:

{% for action in actions %} 
    my-{{ action }}-job: |-
    {{ lookup('template', 'files/myjobs.yaml.j2' ) | indent(width=4) }}
{% endfor %}

actions is defined in another yaml:

actions:
- check
- action1
- action2

playbook:

  vars:
    cert_manager_enabled: true
    roles_array:
      - testtask

role testtask:

- name: Create resources for test deployment
  k8s:
    state: present
    namespace: "testns"
    definition: "{{ lookup('template', item.name) | from_yaml }}"
  loop:
    - name: myjob.yaml.j2

when I run the playbook, error with below message:

The task includes an option with an undefined variable. The error was: 'action' is undefined

the action is a loop variable, any solution to inject a loop variable into lookup('template', ....)?

from here, https://docs.ansible.com/ansible/latest/collections/ansible/builtin/template_lookup.html#parameter-template_vars.

I saw there is a dict param named "templated_vars", but when I passed value like below:

  {{ lookup('template', 'files/myjobs.yaml.j2', template_vars={'action': action} ) | indent(width=4) }}

it does not work... is it an ansible bug?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source