Home > Enterprise >  Ansible - keys missing after changing values in a dict
Ansible - keys missing after changing values in a dict

Time:10-12

I want to change all the values "b" in a way that I will divide it with some number. Here is the code:

    - name: code
      hosts: localhost
      gather_facts: false
    
      vars:
        dict1: [{"a": 1, "b": 2, "c": 3}, {"a": 5, "b": 5, "c": 6},{"a": 8, "b": 9, "c": 10}]
        dict2: |
          [
          {% for i in dict1 %}
          {{ i.a, (i.b/2)|int, i.c }},
          {% endfor %}
          ]
    
      tasks: 

      - debug:
          var: dict2|type_debug
      - debug:
          var: dict2

Problem with this is that I've got just values and "keys" are missing

ok: [localhost] => { "dict2": [ [ 1, 1, 3 ], [ 5, 2, 6 ], [ 8, 4, 10 ] ]

What should I change to include keys too?

Also, not that important, but I've got [ ] instead { } for each item in the loop (simple replacement [] with {} in the variable dict2 doesn't work).

Thanks!

CodePudding user response:

The variable dict1 is a list of dicts. This means that you cannot simply define a list of values, but must also create a dict again.

There are surely different approaches for this, one is the following:

dict1: [{"a": 1, "b": 2, "c": 3}, {"a": 5, "b": 5, "c": 6},{"a": 8, "b": 9, "c": 10}]
dict2: |
  [
  {% for i in dict1 %}
  {{ dict( ['a', 'b', 'c'] | zip( [i.a, (i.b/2)|int, i.c] ) ) }},
  {% endfor %}
  ]
  1. a list with the values a, b and c is defined
  2. another list with the values for a, b, c is created
  3. both lists are connected by zip().
  4. the resulting zip lists are converted to a dict by dict().

The result von - debug: var=dict2 looks like this:

TASK [debug] **********************
ok: [localhost] => {
    "dict2": [
        {
            "a": 1,
            "b": 1,
            "c": 3
        },
        {
            "a": 5,
            "b": 2,
            "c": 6
        },
        {
            "a": 8,
            "b": 4,
            "c": 10
        }
    ]
}
  • Related