# Run a task only if a variable is defined

**URL:** <https://forum.ansible.com/t/run-a-task-only-if-a-variable-is-defined/16804>\
**Category:** Ansible Project\
**Created:** [November 17, 2014, 6:29pm UTC](https://forum.ansible.com/t/run-a-task-only-if-a-variable-is-defined/16804 "2014-11-17T18:29:07Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Simon\_Munoz](https://avatars.discourse-cdn.com/v4/letter/s/a4c791/32.png) [@Simon\_Munoz](https://forum.ansible.com/u/Simon_Munoz)\
**Post date:** [November 17, 2014, 6:29pm UTC](https://forum.ansible.com/t/run-a-task-only-if-a-variable-is-defined/16804/1 "2014-11-17T18:29:07Z")

</div>

Hi all,

I’m trying to run a task only if a variable is defined (for example, I have some groups where it’s defined and some others where it’s not). I got to this (adding when: nginx\_sites), that seems to work, but just asking in case there is a better way.

`

- name: Enabling nginx sites according to group and host\_vars  
file: \>  
src=/etc/nginx/sites-available/{{ item }}  
dest=/etc/nginx/sites-enabled/{{ item }}  
state=link  
with\_items: random\_var  
when: random\_var  
notify:
- reload nginx  
`

Thanks in advance!

---

<div class="post-metadata">

**Author:** ![rektide](https://avatars.discourse-cdn.com/v4/letter/r/a88e57/32.png) [@rektide](https://forum.ansible.com/u/rektide)\
**Post date:** [November 17, 2014, 7:27pm UTC](https://forum.ansible.com/t/run-a-task-only-if-a-variable-is-defined/16804/2 "2014-11-17T19:27:28Z")

</div>

`when: foo is defined` is what i used to do.

these days though, i've found that more often i want to still be able to signal a falsity.

unless extremely carefully considered, i try to use:

`when: foo|default(False)`

HH, -r

---

<div class="post-metadata">

**Author:** ![Michael\_DeHaan1](https://avatars.discourse-cdn.com/v4/letter/m/5e9695/32.png) [@Michael\_DeHaan1](https://forum.ansible.com/u/Michael_DeHaan1)\
**Post date:** [November 17, 2014, 8:16pm UTC](https://forum.ansible.com/t/run-a-task-only-if-a-variable-is-defined/16804/3 "2014-11-17T20:16:17Z")

</div>

You can do this:

when: foo is defined

---

<div class="post-metadata">

**Author:** ![Simon\_Munoz](https://avatars.discourse-cdn.com/v4/letter/s/a4c791/32.png) [@Simon\_Munoz](https://forum.ansible.com/u/Simon_Munoz)\
**Post date:** [November 18, 2014, 8:38am UTC](https://forum.ansible.com/t/run-a-task-only-if-a-variable-is-defined/16804/4 "2014-11-18T08:38:59Z")

</div>

Thanks a lot guys ;)!
