When are file lookups performed? How to store lookup result in a variable?

I was under the impression that if I define a variable with a lookup function, it would store the results of the lookup. And then when I used that variable, it would spit out the results of the lookup.

However, from running a bunch of different test cases that Ansible performs the lookup every time I try to use that variable. Is that by design? Is there a way to avoid repeated lookups?

So… expectation:

`
myvar: lookup(…)

look up stuff and store result of lookup in ‘myvar’

  • name: ‘{{ myvar }}’

spit out contents of ‘myvar’

  • debug:
    var: myvar

spit out contents of ‘myvar’

etc.

`

What seems to be happening is…

`
myvar: lookup(…)

look up stuff

  • name: ‘{{ myvar }}’

look at ‘myvar’ and perform the lookup defined by it, then spit out result

  • debug:
    var: myvar

look at ‘myvar’ and perform the lookup defined by it, then spit out result

etc.
`

Yes, by design, but you can avoid it by using set_fact.

- set_fact:
    myvar: '{{ lookup(...) }}'

Thank you for clearing it up!