Ansible – How to Use Variable to Construct Dictionary Key

ansiblevariables

I am trying to update a dict in a hostvar, and the name of the key is constructed using a variable (node). For example, if 'node' is 1 then I want to update hostvars['fakehost']['mydict']['localaddress1']. Here's my code:

- name: Read IPv4 of first interface
    add_host:
      name: "fakehost"
      telium: "{{ hostvars['fakehost']['mydict'] | combine ({ 'localaddress{{ node }}' : ansible_all_ipv4_addresses[0] }) }}"

I can't figure out how to construct localaddress{{node}} with ansible complaining about the syntax.

Best Answer

Don't nest moustaches ({{ }}). Once you're inside an expression, you're already in a Jinja context and should not use additional delimiters when accessing a variable.

      telium: "{{ hostvars['fakehost']['mydict'] | combine ({ 'localaddress' ~ node: ansible_all_ipv4_addresses[0] }) }}