Dynamic dictionary key

253 views
Skip to first unread message

Rishare Rishare

unread,
Feb 15, 2021, 6:32:43 AM2/15/21
to Ansible Project

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"?

Dick Visser

unread,
Feb 15, 2021, 7:25:10 AM2/15/21
to ansible...@googlegroups.com
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. 

--
You received this message because you are subscribed to the Google Groups "Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ansible-proje...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ansible-project/a7a6a255-65b1-48ef-9f21-1f71023b3933n%40googlegroups.com.
--
Sent from a mobile device - please excuse the brevity, spelling and punctuation.

Nuno Jordão

unread,
Feb 15, 2021, 11:40:39 AM2/15/21
to ansible...@googlegroups.com
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

--
Reply all
Reply to author
Forward
0 new messages