Use lookup/dynamic variable names in jinja2 template

Hi,

The playbook below should generate a file with the content:
a,b
ssh_host_key
ssh_rsa_host_key

However, the way I construct the variable names results in either syntax/templating errors or ‘variable name does not exists’.

You can use the varnames lookup to get variable names that match given
pattern: https://docs.ansible.com/ansible/latest/plugins/lookup/varnames.html

Hi Martin,

Thanks, but I’m not sure varnames is useful to me.

I know what the variable is called, but don’t know how to construct it programmatically (as the Ansible manual calls it). Taking the example code from the documentation results in an empty list:

  • debug:
    msg: “{{ lookup(‘varnames’, ansible_distribution + ‘.hostkeys’) }}”

    TASK [debug] *******
    ok: [localhost] => {
    “msg”:
    }

Regards,
Willem.

Sorry, I misread your example and missed that the variable you want to
look up is a dictionary and that you want to access a key within that
dictionary. In that case you need to look up just the var and access
the key on the result of the lookup:

- hosts: localhost
  gather_facts: yes
  vars:
    Fedora:
      key: value
  tasks:
    - debug:
        msg: "{{ lookup('vars', ansible_distribution)['key'] }}"

Hi Martin,

Thanks for your quick response, really appreciate it. I hope you don’t mind an additional question: the vars section actually is one level deeper:

vars:
sshd:
CentOS:
ciphers: “a,b”
hostkeys:

  • “ssh_host_key”
  • “ssh_rsa_host_key”

How do I add this to:
{% for hostkey in lookup(‘vars’, ansible_distribution)[‘hostkeys’] %}
{{ hostkey }}
{% endfor %}

I tried [‘sshd’]lookup(‘vars’, ansible_distribution)[‘hostkeys’] and a few variants, but they all fail.

Sorry for being such a noob, but accessing vars/lists/dicts/etc. always gives me major headaches :slight_smile:

Regards,
Willem.

- hosts: localhost
  gather_facts: yes
  vars:
    top_level:
      Fedora:
        key: value
  tasks:
    - debug:
        msg: "{{ top_level[ansible_distribution]['key'] }}"

Hi Martin,

Thank you for your effort. And your patience.

Regards,
Willem.