# jinja2 filters for state 'present'/'absent'

**URL:** <https://forum.ansible.com/t/jinja2-filters-for-state-present-absent/18620>\
**Category:** Ansible Developer\
**Created:** [June 26, 2015, 10:54am UTC](https://forum.ansible.com/t/jinja2-filters-for-state-present-absent/18620 "2015-06-26T10:54:17Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Strahinja\_Kustudic2](https://avatars.discourse-cdn.com/v4/letter/s/b4bc9f/32.png) [@Strahinja\_Kustudic2](https://forum.ansible.com/u/Strahinja_Kustudic2)\
**Post date:** [June 26, 2015, 10:54am UTC](https://forum.ansible.com/t/jinja2-filters-for-state-present-absent/18620/1 "2015-06-26T10:54:17Z")

</div>

Every once in a while I have a situation in roles where I would like to set the state of a module to ‘present’ or ‘absent’ depending if a variable is empty or not. For example if I want to set a cron with a cron module I usually have a time variable which if it is not empty, it should set the cron job, if it is empty it should remove it (not skip it). E.g. task:

`

- name: Set cron job  
cron: name=“job1” hour=“{{ role\_cron\_hour }}” job=“/usr/locat/script.sh”  
state={{ ‘present’ if `role_cron_hour` != “” else ‘absent’ }}

`

Lately I usually solve this by adding an additional variable and setting it to ‘present’/‘absent’, which is also not natural, since I would like to set it to True/False, but than again I have to do the ugly if like above.

Would it make more sense to add a new filter like  
`  
state={{ var1|empty\_to\_absent }}

`

Or maybe just call the filters **present** (returns ‘present’ if variable is not empty, else ‘absent’) and **absent** (works the other way around). This is just a few lines of code to be added and if anyone is interested I would gladly make a pull request.

---

<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:** [June 26, 2015, 12:11pm UTC](https://forum.ansible.com/t/jinja2-filters-for-state-present-absent/18620/2 "2015-06-26T12:11:44Z")

</div>

The ternary filter should give you this ability pretty easy.

---

<div class="post-metadata">

**Author:** ![Strahinja\_Kustudic2](https://avatars.discourse-cdn.com/v4/letter/s/b4bc9f/32.png) [@Strahinja\_Kustudic2](https://forum.ansible.com/u/Strahinja_Kustudic2)\
**Post date:** [June 26, 2015, 12:20pm UTC](https://forum.ansible.com/t/jinja2-filters-for-state-present-absent/18620/3 "2015-06-26T12:20:40Z")

</div>

It was added in 1.9, I didn’t notice it in the changelog. That will do the trick. Thanks 🙂
