Dynamic dictionary key

Hi,

I can’t find any easy way how to do something like this:

  • set_fact:
    “mydict[{{ myvar }}]”: “value”
    vars:
    myvar: “blabla”

However it does not work, because the variable name is not evaluated. The only way I found to do this is very ugly:

  • set_fact:
    mydict: “{{ mydict | combine({ myvar: ‘value’ }, recursive=true) }}”
    vars:
    myvar: “blabla”

That is very ugly and can get out of hand quickly when going into deeper nested dictionaries.

Any ideas how to make it “nicer”?

Not really. I have some similar cases where I resort to defining a list and the using items2dict to come up with the structure that I need.

Hello,

I am not sure it helps in your case, but I had success in past generating complex structures with a json template and importing it into a variable:

set_fact:
data: “{{ lookup(‘template’, ‘templates/data.json.j2’) }}”

It’s much faster than doing combines and loops.

Nuno Jordão