title: How to check whether variable is defined, when dictionary may be missing in ansible/j2
body: <p>I have a Ansible and Jinja2 related question. I have an yml file like this:</p>
  
  <pre><code>---
  haproxy:
    global:
      maxconn: 30000
      ssl: true
    defaults:
      maxconn: 400
    server:
      maxconn: 200
      httpclose: true
    frontend:
      web:
        maxconn: 20000
        ssl: true
  </code></pre>
  
  <p>In J2 template, I want to do something like this:</p>
  
  <pre><code>{% if haproxy.frontend.web.maxconn is defined  %}
      maxconn {{ haproxy.frontend.web.maxconn }}
  {% endif %}
  </code></pre>
  
  <p>This works well, when the value is defined, but we use several environments and in some of them, the <code>frontend</code> dictionary is not defined (then, it will fall under defaults in haproxy, which is fine in dev) and when <code>frontend</code> is missing I get this error in ansible:</p>
  
  <pre><code>"msg": "AnsibleUndefinedVariable: 'dict object' has no attribute 'frontend'"
  </code></pre>
  
  <p>This error is produced by the if itself, not the body.</p>
  
  <p>I know that the <code>frontend</code> does not exists, but that logically means the variable is undefined  (as it does not exists at all). Please, tell me how can I check for existence / definition of variable, when its dictionary can be missing.</p>
  
  <p>Thanks!</p>
  
  <p>P.S. Please, dont tell me to do something like</p>
  
  <pre><code>{% if haproxy.frontend is defined and haproxy.frontend.web is defined and haproxy.frontend.web.maxconn is defined %}
  </code></pre>