Reputation: 13
I load a file with the content Some {{bar}} random text
using the file lookup plugin:
- name: Load foo
set_fact:
foo: "{{ lookup('file', 'foo.txt') }}"
- name: Output foo
debug:
msg: "{{foo}}"
If I output {{foo}}, the output is literally Some {{bar}} random text
. Ignoring the fact that I could use the template lookup plugin instead: Is it possible to evaluate {{foo}} after the file has been loaded, so that the actual value of bar
will be injected into Some {{bar}} random text
?
I am looking for something like:
- name: Evaluate foo
set_fact:
evaulated_foo: "{{ lookup('template', foo) }}" #Use the value of foo instead of a file
Upvotes: 1
Views: 1045
Reputation: 2939
This is the intended behaviour. Lookups return unsafe text, which will never be templated. Use the template
lookup when you want to return the contents of a file after template evaluation.
To avoid ordering issues, use a variable with the lookup instead of set_fact
. set_fact
sets variables to a static, fully evaluated value while normal variables are evaluated lazily, so they don't require that all of the variables be defined at the same time.
- hosts: localhost
gather_facts: false
vars:
foo: "{{ lookup('template', 'test.j2') }}"
tasks:
# These will work because bar is a current variable
- debug:
msg: "{{ foo }}"
vars:
bar: lemon
- debug:
msg: "{{ foo }}"
vars:
bar: orange
# This will not work, because bar isn't set
- set_fact:
foo: "{{ foo }}"
PLAY [localhost] ***************************************************************
TASK [debug] *******************************************************************
ok: [localhost] => {
"msg": "Some lemon random text\n"
}
TASK [debug] *******************************************************************
ok: [localhost] => {
"msg": "Some orange random text\n"
}
TASK [set_fact] ****************************************************************
fatal: [localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: {{ lookup('template', 'test.j2') }}: 'bar' is undefined\n\nThe error appears to be in '/home/ec2-user/test.yml': line 18, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n # This will not work, because bar isn't set\n - set_fact:\n ^ here\n"}
Upvotes: 3