Set fact with dynamic key name in ansible

The above does not work for me. What finally works is

- set_fact:
    example_dict: "{'{{ some var }}':'{{ some other var }}'}"

Which is in the end obvious. You construct a string (the outer double quotes) which is then interpreted as a hash. In hashes key and value must be single quotes (the inner single quotes around the variable replacements). And finally you just place your variable replacements as in any other string.

Stefan


take a look at this sample playbook:

---
- hosts: localhost
  vars:
    iter:
      - key: abc
        val: xyz
      - key: efg
        val: uvw
  tasks:
    - set_fact: {"{{ item.key }}":"{{ item.val }}"}
      with_items: "{{iter}}"
    - debug: msg="key={{item.key}}, hostvar={{hostvars['localhost'][item.key]}}"
      with_items: "{{iter}}"