Bootstrap FreeKB - Ansible - Define a default value using the default filter
Ansible - Define a default value using the default filter

Updated:   |  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
    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
    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 Buy Me A Coffee



Comments


Add a Comment


Please enter 94d001 in the box below so that we can be sure you are a human.