Search code examples
ansiblejinja2

Evaluate a Jinja2 string as template in Ansible


I have a sort of configuration vars file through which I'm looping,

checks:
  - name: "x"
    setting: "y"
    eval: "{{ 'OK' if var == 'x' else 'NOK' }}"

main.yml

- hosts: all
  tasks:
  - name: Loop
    include_tasks: do.yml
    loop: "{{ checks }}"

Now the issue is that the eval gets templated/expanded as it's entering the loop...

inside do.yml

---
- debug:
    var: item

# (shows eval as NOK)

- name: Do stuff
  shell:
  register: var

- name: Save stuff
  set_fact
    result: "{{ result | d([]) + [ res ] }}"
  vars:
    res:
      name: "{{ item.name }}"
      setting: "{{ item.setting }}"
      result: "{{ item.eval }}"

How do I make it so that the item.eval is re-evaluated after var is registered?
What I'd like even more is if I just provided the string, without the curly brackets in checks.yml file and that would get templated inside the loop. I just can't make it work.

What happens is that the eval part gets templated right before it goes into the loop and then it works with the templated value instead of the variable references being evaluated when the Save stuff task happens.


Solution

  • I just changed the item.eval that becomes static, back to the original var file variable which ensures it gets templated again properly.

    - name: Save stuff
      set_fact
        result: "{{ result | d([]) + [ res ] }}"
      vars:
        res:
          name: "{{ item.name }}"
          setting: "{{ item.setting }}"
          result: "{{ (checks | selectattr('name', 'eq', item.name) | list | first).eval }}"