Reputation: 567
I have the followinf Ansible code:
- name: "Set variable"
set_fact:
my_var: "{{ ((all_vars | from_yaml).metadata.annotations['var'] | default(undefined)) | from_json }}"
If 'var' is not present/declared I would like to set it to string "undefined".
I've tried using single and double quotes like this default("undefined")
and it didn't help.
It fails with:
The task includes an option with an undefined variable. The error was: Unable to look up a name or access an attribute in template string ({{ ((all_vars | from_yaml).metadata.annotations['var'] | default(undefined)) | from_json }}).
What am I doing wrong?
Upvotes: 0
Views: 1473
Reputation: 171
The issue is that undefined
is being interpreted as a variable, since it is not quoted. To set it to the string "undefined", you need to quote it:
- name: "Set variable"
set_fact:
my_var: "{{ ((all_vars | from_yaml).metadata.annotations['var'] | default('undefined')) }}"
The default()
filter requires the value to be a quoted string, number, boolean, etc. By passing undefined
without quotes, Ansible thinks it is a variable name rather than a literal string.
Quoting it as 'undefined'
makes it a string literal, which will then be used as the default value if 'var' is not present.
With all of that being said:
default(undefined)
- tries to use a variable called undefineddefault("undefined")
- sets the default to the string "undefined"Upvotes: 0