Reputation: 14549
Take this bit of code:
- name: One
set_fact:
test_var: "default_name"
- name: Two
debug:
msg: "{{ test_var is defined }}"
- name: Three
set_fact:
second_test_var: '{{ test_var | default(groups | my_custom_filter_plugin("should not execute")) }}'
The filter plugin looks like this:
def my_custom_filter_plugin(groups, txt):
print(groups)
return "Test"
class FilterModule(object):
''' Testing filters '''
def filters(self):
return {
'my_custom_filter_plugin': my_custom_filter_plugin
}
From this text I read that defaults only get executed if a variable is not defined: https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html#providing-default-values
My variable is defined... and yet the code in the default filter gets executed.
What am I missing here?
Upvotes: 1
Views: 357
Reputation: 39314
You can achieve this taking an other route and use an inline if expression instead of the default
filter.
So, your last set_fact
would become:
- name: Three
set_fact:
second_test_var: >-
{{
test_var
if test_var is defined
else groups | my_custom_filter_plugin("should not execute")
}}
Given the playbook:
- hosts: localhost
gather_facts: no
tasks:
- set_fact:
second_test_var: >-
{{
test_var
if test_var is defined
else I_do_not_exists | int
}}
vars:
test_var: foobar
- debug:
var: second_test_var
- name: Showing that doing the same with `default` errors
set_fact:
second_test_var: "{{ test_var | default(I_do_not_exists | int) }}"
vars:
test_var: foobar
This would yield:
TASK [set_fact] *****************************************************************
ok: [localhost]
TASK [debug] ********************************************************************
ok: [localhost] =>
second_test_var: foobar
TASK [Showing that doing the same with `default` errors] ************************
fatal: [localhost]: FAILED! =>
msg: |-
The task includes an option with an undefined variable. The error was: 'I_do_not_exists' is undefined
The error appears to be in '/usr/local/ansible/play.yml': line 18, column 7, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
- name: Showing that doing the same with `default` errors
^ here
Upvotes: 1