'How to turn a variable into a dictionary item

I am struggling with what I believe is the simplest of tasks. I want to take a variable v and turn that into a dictionary where

v: ValueofV

The end goal is to write that dictionary to a JSON file that contains a list of variables, with key: value where key name is always a variable name, so for variables a, b, c, ... I should end up with:

{
  "a": "a_val",
  "b": "v_val",
  "c": "c_val"
}

I've tried building lists with_items, e.g.

- name: Var3
  set_fact:
    node_state4: "{{ node_state4 | default({}) | combine({ item : item })}}"
  with_items:
    - requested_node_count
    - added_node_count

But, that makes the value the string name. If I make the second item {{ item }} it fails.



Solution 1:[1]

Use filter community.general.dict_kv e.g.

  _dict: "{{ v|community.general.dict_kv('v') }}"

gives

  _dict:
    v: ValueofV

Given the list of the variables

    rnodes: [a, b, c]
    a: a_val
    b: b_val
    c: c_val

iterate the list and create the dictionary, e.g.

    - set_fact:
        _dict: "{{ _dict|d({})|
                   combine(lookup('vars', item)|
                           community.general.dict_kv(item)) }}"
      loop: "{{ rnodes }}"

gives

  _dict:
    a: a_val
    b: b_val
    c: c_val

The next option is to extract the variables and use filters dict and zip, e.g. the task below gives the same result

    - set_fact:
        _dict: "{{ dict(rnodes|zip(_vals)) }}"
      vars:
        _vals: "{{ rnodes|map('extract', vars) }}"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1