title: How can I make Ansible interpret a variable inside a variable?
body: <p>Whenever I try to make Ansible interpret a nested variable — so, a variable inside another variable — I cannot get the result I expect.</p>
  <p>Given the variables:</p>
  <pre class="lang-yaml prettyprint-override"><code>key: bar
  foo:
    bar: baz
  foo_bar: baz
  </code></pre>
  <p>I have tried those three approaches without much luck to dynamically access the key <code>bar</code> of the dictionary <code>foo</code> or the key <code>foo_bar</code>, when constructed from the value of <code>key</code>:</p>
  <ul>
  <li>
  <pre class="lang-yaml prettyprint-override"><code>- ansible.builtin.debug:
      msg: &quot;{{ foo[{{ key }}] }}&quot;
  </code></pre>
  <p>But, I get the error:</p>
  <blockquote>
  <p>'template error while templating string: expected token '':'', got ''}''. String: {{ foo[{{ key }}] }}'</p>
  </blockquote>
  </li>
  <li>
  <pre class="lang-yaml prettyprint-override"><code>- ansible.builtin.debug:
        msg: &quot;{{ foo_{{ key }} }}&quot;
  </code></pre>
  <p>But, I get a similar error</p>
  <blockquote>
  <p>'template error while templating string: expected token ''end of print statement'', got ''{''. String: {{ foo_{{ key }} }}'</p>
  </blockquote>
  </li>
  <li>
  <pre class="lang-yaml prettyprint-override"><code>- ansible.builtin.debug:
      msg: &quot;{{ foo['{{ key }}'] }}&quot;
  </code></pre>
  <p>And here, I get the error</p>
  <blockquote>
  <p>The task includes an option with an undefined variable. The error was: 'dict object' has no attribute '{{ key }}'</p>
  </blockquote>
  </li>
  </ul>
  <p>I was expecting to get the value of <code>foo.bar</code> or <code>foo_bar</code>, so <code>baz</code>.<br />
  What would be the correct approach to achieve this?</p>