# Conditonally run task based on wether a variable has been set

**URL:** <https://forum.ansible.com/t/conditonally-run-task-based-on-wether-a-variable-has-been-set/13844>\
**Category:** Ansible Project\
**Created:** [November 5, 2013, 4:14am UTC](https://forum.ansible.com/t/conditonally-run-task-based-on-wether-a-variable-has-been-set/13844 "2013-11-05T04:14:07Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Torrance\_Hodgson](https://avatars.discourse-cdn.com/v4/letter/t/9dc877/32.png) [@Torrance\_Hodgson](https://forum.ansible.com/u/Torrance_Hodgson)\
**Post date:** [November 5, 2013, 4:14am UTC](https://forum.ansible.com/t/conditonally-run-task-based-on-wether-a-variable-has-been-set/13844/1 "2013-11-05T04:14:07Z")

</div>

Hi all,

This should be simple to solve: I want run a task only if a variable is set (by providing the variable on the command line). How best to do this?

The following doesn’t work:

- name: Set mysql root password  
mysql\_user: name=root password={{ mysql\_pw }}  
when: “mysql\_pw”

I get the error: ‘Conditional expression must evaluate to True or False’. Surely an empty string evaluates to false?

Nor does:

- name: Set mysql root password  
mysql\_user: name=root password={{ mysql\_pw }}  
when: “mysql\_pw != ‘’”

…which always runs whether irrespective of whether the variable mysql\_pw is set.

Any other ideas?

Thanks,  
Torrance

---

<div class="post-metadata">

**Author:** ![benno\_joy](https://avatars.discourse-cdn.com/v4/letter/b/73ab20/32.png) [@benno\_joy](https://forum.ansible.com/u/benno_joy)\
**Post date:** [November 5, 2013, 6:23am UTC](https://forum.ansible.com/t/conditonally-run-task-based-on-wether-a-variable-has-been-set/13844/2 "2013-11-05T06:23:21Z")

</div>

Hi Torrance,

try

when: mysql\_pw is defined

---

<div class="post-metadata">

**Author:** ![Torrance\_Hodgson](https://avatars.discourse-cdn.com/v4/letter/t/9dc877/32.png) [@Torrance\_Hodgson](https://forum.ansible.com/u/Torrance_Hodgson)\
**Post date:** [November 5, 2013, 6:50am UTC](https://forum.ansible.com/t/conditonally-run-task-based-on-wether-a-variable-has-been-set/13844/3 "2013-11-05T06:50:46Z")

</div>

Benno, thank you! That did the trick 🙂
