title: Ansible check if variables are set
body: <p>I want to automate the installation process of our software for our client. Therefore I wrote an Ansible playbook which has a task which should check if all the mandatory variables are set:</p>
  
  <pre><code>- name: Check environment variables.
    hosts: all
    vars_files: 
      - required_vars.yml
    tasks:
      - fail: msg="Variable '{{ item }}' is not defined"
        when: item not in hostvars[inventory_hostname]
        with_items: 
          - required_vars
  </code></pre>
  
  <p>The <code>required_vars.yml</code> looks like this: </p>
  
  <pre><code>required_vars:
    - APPHOME: /home/foo/bar
    - TMPDIR: /home/foo/bar/tmp
  </code></pre>
  
  <p>When I execute the playbook via <code>ansible-playbook -i inventory/dev.yml playbook.yml</code> I get the following error: </p>
  
  <pre><code>TASK [Gathering Facts] *************************************************************************************************************************************************************************************************************************ok: [localhost]
  
  TASK [fail] ************************************************************************************************************************************************************************************************************************************failed: 
  [localhost] (item=required_vars) =&gt; {"changed": false, "failed": true, "item": "required_vars", "msg": "Variable 'required_vars' is not defined"}
  </code></pre>
  
  <p>It is obvious that I am doing something wrong, but I cannot point to the error. Can you help me please?</p>
  
  <p><strong>Edit</strong>: the accepted answer helped me out. Thank you.
  But I have two more questions: </p>
  
  <ol>
  <li><p>The executed task says: </p>
  
  <pre><code>TASK [fail]
  skipping: [some_ip] =&gt; (item=/root)
  skipping: [some_ip] =&gt; (item=TMPDIR: /home/foo/bar/tmp)
  </code></pre></li>
  </ol>
  
  <p>It is getting skipped because all variables are set, correct?</p>
  
  <ol start="2">
  <li><p>I think I figured out how to print the correct message, if the variable is not set:</p>
  
  <pre><code>- name: Check environment variables.
    hosts: all
    vars_files: 
      - required_vars.yml
    tasks:
      - fail: 
          msg: "Variable '{{ item }}' is not defined"
        with_items: "{{ required_vars }}"
        when: item is undefined
  </code></pre></li>
  </ol>
  
  <p>Correct? Or is there a better solution?</p>