Score:0

Use variable to construct dictionary key in Ansible

cn flag
TSG

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.

Zeitounator avatar
fr flag
[mustaches don't stack](https://docs.ansible.com/ansible/latest/reference_appendices/faq.html#when-should-i-use-also-how-to-interpolate-variables-or-dynamic-variable-names)
Score:0
th flag

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] }) }}
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.