variablesdynamicansible

Set fact with dynamic key name in ansible


I am trying to shrink several chunks of similar code which looks like:

- ... multiple things is going here
  register: list_register
- name: Generating list
  set_fact: my_list="{{ list_register.results | map(attribute='ansible_facts.list_item') | list }}"

# the same code repeats...

The only difference between them is list name instead of my_list.

In fact, I want to do this:

set_fact:
  "{{ some var }}" : "{{ some value }}"

I came across this post but didn't find any answer here.

Is it possible to do so or is there any workaround?


Solution

  • 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}}"