1

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.

1 Answer 1

1

The case you describe is not complete. Without the variable var defined you have to see the error message:

'var'' is undefined 

The below play

- hosts: localhost vars: checks: - name: "x" setting: "y" eval: "{{ 'OK' if var == 'x' else 'NOK' }}" tasks: - include_tasks: do.yml loop: "{{ checks }}" 

fails

fatal: [localhost]: FAILED! => msg: '[{''name'': ''x'', ''setting'': ''y'', ''eval'': "{{ ''OK'' if var == ''x'' else ''NOK'' }}"}]: ''var'' is undefined' 

To answer your question: "How do I make it so that the item.eval is re-evaluated after var is registered?"

It is not possible to reevaluate item.eval


The solution might be to restructure the data. For example,

 checks: - eval: x: OK default: NOK - eval: y: OK default: NOK 

Then, evaluate the dictionary in the loop. For example,

shell> cat do.yml - command: echo x register: out - set_fact: result: "{{ result | d([]) + [ res ] }}" vars: res: result: "{{ item.eval[out.stdout] if out.stdout in item.eval else item.eval.default }}" 

gives

 result: - result: OK - result: NOK 

Example of a complete playbook for testing

- hosts: localhost vars: checks: - eval: x: OK default: NOK - eval: y: OK default: NOK tasks: - include_tasks: do.yml loop: "{{ checks }}" - debug: var: result 

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.