Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ansible: 'default' filter that treats the empty string as not defined

Tags:

ansible

If I do this:

- set_fact:
    NEW_VARIABLE: "{{ VARIABLE | default('default') }}"

and VARIABLE is the empty string (""), than the default not triggering.

I could do this:

- set_fact:
    NEW_VARIABLE: "{{ VARIABLE | default('default') }}"
- set_fact:
    NEW_VARIABLE: "default"
   when: VARIABLE == ""

But I actually want to do this in a loop. So it would be much easier if I could do this using ansible filters and not conditionals.

Is this possible? Are there ansible filters that work like default but treats "" as not defined?

like image 351
Nathan Avatar asked Jan 18 '19 16:01

Nathan


People also ask

Which filter is used to provide default values to variables Ansible?

So if you want to define a default value for a variable you should set it in role/defaults/main.

What is Ansible filter?

Ansible filters are a powerful feature that lets you assign values to variables, convert variable data types, and more. Posted: August 24, 2022 | 5 min read | by Roberto Nozaki (Sudoer, Red Hat)

What is Ansible Set_fact?

In Ansible, we have various modules that work with variables and are used to get or set variable values. One such important module is set_fact. This module is used to set new variables. These variables are set on a host-by-host basis which is just like ansible facts, discovered by setup module.

How do you use Ansible facts in playbook?

Using the Ansible playbook To access the variables from Ansible facts in the Ansible playbook, we need to use the actual name without using the ansible keyword. The gather_facts module from the Ansible playbook runs the setup module by default at the start of each playbook to gather the facts about remote hosts.


1 Answers

You have to set second argument of default to true

{{ VARIABLE | default('default', true) }}

https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html#defaulting-undefined-variables

like image 91
elmariofredo Avatar answered Sep 29 '22 23:09

elmariofredo