title: Conditionally define variable in Ansible
body: <p>I want to conditionally define a variable in an Ansible playbook like this: </p>
  
  <pre class="lang-yml prettyprint-override"><code>my_var: "{{ 'foo' if my_condition}}"
  </code></pre>
  
  <p>I would like the variable to remain undefined if the condition does not resolve to <code>true</code>.</p>
  
  <p>Ansible gives the following error if I try to execute the code:</p>
  
  <pre class="lang-sh prettyprint-override"><code>fatal: [foo.local] =&gt; {'msg': 'AnsibleUndefinedVariable: One or more undefined
                         variables: the inline if-expression on line 1 evaluated
                         to false and no else section was defined.', 'failed': True}
  </code></pre>
  
  <p>Why is this an error anyway?</p>
  
  <p>The complete case looks like this:</p>
  
  <pre class="lang-yml prettyprint-override"><code>{role: foo, my_var: "foo"}
  </code></pre>
  
  <p>If <code>my_var</code> is defined, the role does something special. In some cases, I don't want the role to do this. I could use <code>when: condition</code>, but then I would have to copy the whole role block. I could also use an extra bool variable, but I would like a solution without having to change the "interface" to the role.</p>
  
  <p>Any ideas?</p>