# Default filter and dictionary values

**URL:** <https://forum.ansible.com/t/default-filter-and-dictionary-values/26131>\
**Category:** Ansible Project\
**Created:** [November 24, 2017, 7:20pm UTC](https://forum.ansible.com/t/default-filter-and-dictionary-values/26131 "2017-11-24T19:20:44Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Evan\_Frey](https://avatars.discourse-cdn.com/v4/letter/e/df788c/32.png) [@Evan\_Frey](https://forum.ansible.com/u/Evan_Frey)\
**Post date:** [November 24, 2017, 7:20pm UTC](https://forum.ansible.com/t/default-filter-and-dictionary-values/26131/1 "2017-11-24T19:20:44Z")

</div>

I am having an issue with the default value not being honored for an undefined dictionary. For example, if the setup is as follows

**- name: something**  
**file:**  
**path: /somepath**  
**owner: “{{ dir[‘owner’] | default(‘root’) }}”**

and I have a variable of

**dir:**  
**owner: someowner**

when I run this, a file called **/somepath** is created with the owner **someowner** , as expected. However, if the dictionary dir does not exist, I get an error of

**_"the field ‘args’ has an invalid value, which appears to include a variable that is undefined. The error was: ‘dir’ is undefined_**

instead of running with the default as I would have expected. if I flatten the variable structure to be

**dir\_owner: someowner**

and change the task to be

**- name: something**  
**file:**  
**path: /somepath**  
**owner: “{{ dir\_owner | default(‘root’) }}”**

this works as expected. The owner of the file is either someowner if defined or root if not.

---

<div class="post-metadata">

**Author:** ![sivel](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/sivel/32/1198_2.png) [@sivel](https://forum.ansible.com/u/sivel)\
**Post date:** [November 24, 2017, 7:29pm UTC](https://forum.ansible.com/t/default-filter-and-dictionary-values/26131/2 "2017-11-24T19:29:56Z")

</div>

You have to default at every step, `default` is only applied to the deepest level specified, so if `dir` is undefined, you would have to apply `default` on `dir` directly too.

Maybe something like:

(dir|default({}))[‘owner’]|default(‘root’)

or making some assumptions that dir will either be defined or not, and when defined it will have `owner`:

(dir|default(dict(owner=‘root’)))[‘owner’]

---

<div class="post-metadata">

**Author:** ![Evan\_Frey](https://avatars.discourse-cdn.com/v4/letter/e/df788c/32.png) [@Evan\_Frey](https://forum.ansible.com/u/Evan_Frey)\
**Post date:** [November 24, 2017, 7:40pm UTC](https://forum.ansible.com/t/default-filter-and-dictionary-values/26131/3 "2017-11-24T19:40:42Z")

</div>

You rock, figured it had to be something like that but couldn’t find any docs on it. Thanks!
