Ansible - Define a default value using the default filter
by
Jeremy Canfield |
Updated: August 07 2024
| Ansible articles
default is a Jinja2 filter, used to set a default value. This is almost always used when a variable can possibly be undefined. Take for example the following playbook. This will output "Hello World" when the foo variable is undefined.
---
- hosts: localhost
tasks:
- name: output the value of the foo variable, default Hello World if undefined
ansible.builtin.debug:
msg: "{{ foo | default ('Hello World') }}"
...
Which should return the following.
TASK [output the value of the foo variable, default Hello World if undefined]
ok: [localhost] => {
"msg": [
"Hello world"
]
}
As a bit more of a practical example, let's say you are using the file module to create directories. In this example, the /tmp/foo directory will default to mode 0775 whereas the /tmp/bar directory will use the defined mode 0700.
---
- hosts: localhost
tasks:
- name: create directories
ansible.builtin.file:
path: "{{ item.path }}"
state: directory
mode: "{{ item.mode | default ('0775') }}"
with_items:
- { path: "/tmp/foo" }
- { path: "/tmp/bar", mode: "0700" }
...
Did you find this article helpful?
If so, consider buying me a coffee over at