Home > Mobile >  Ansible loop with additional filters
Ansible loop with additional filters

Time:10-06

I have the following list

ids: [id1, id2, id3]

and the following registered result of an iteration

  output2:
    changed: false
    msg: All items completed
    results:
    - ansible_loop_var: item
      changed: false
      failed: false
      item: id1
      msg:
        json:
          key1: '0'
          key2: '6'
          key3: '4'
    - ansible_loop_var: item
      changed: false
      failed: false
      item: id2
      msg:
        json:
          key1: '2'
          key2: '6'
          key3: '6'
    - ansible_loop_var: item
      changed: false
      failed: false
      item: id3
      msg:
        json:
          key1: '8'
          key2: '0'
          key3: '9'
    skipped: false

How can I create the dictionary below and select the keys?

    "id1": {
       "key1": "0",
       "key3": "4"
           }
    "id2": {
       "key1": "2",
       "key3": "6"
           }
    "id3": {
       "key1": "8",
       "key3": "9"
           }

CodePudding user response:

Declare the below variables in vars

    ids: [id1, id2, id3]
    _values: "{{ output2.results|
                 json_query('[].msg.json.{key1: key1, key3: key3}') }}"
    result: "{{ dict(ids|zip(_values)) }}"

As a hint, create the task below for testing. Select key1 and key3 from the resulting JSON

    - debug:
        msg: "{{ stat|from_yaml }}"
      register: output2
      loop: "{{ ids }}"
      vars:
        stat: |
          json:
            key1: "{{ range(10)|random }}"
            key2: "{{ range(10)|random }}"
            key3: "{{ range(10)|random }}"

gives

  _values:
    - {key1: '0', key3: '5'}
    - {key1: '1', key3: '9'}
    - {key1: '3', key3: '6'}
  result:
    id1: {key1: '0', key3: '5'}
    id2: {key1: '1', key3: '9'}
    id3: {key1: '3', key3: '6'}

Fit the query according to the content of your output2.


Example of a complete playbook for testing

- hosts: localhost

  vars:

    ids: [id1, id2, id3]
    _values: "{{ output2.results|
                 json_query('[].msg.json.{key1: key1, key3: key3}') }}"
    result: "{{ dict(ids|zip(_values)) }}"

  tasks:

    - debug:
        msg: "{{ stat|from_yaml }}"
      register: output2
      loop: "{{ ids }}"
      vars:
        stat: |
          json:
            key1: "{{ range(10)|random }}"
            key2: "{{ range(10)|random }}"
            key3: "{{ range(10)|random }}"

    - debug:
        var: output2
    - debug:
        var: _values|to_yaml
    - debug:
        var: result|to_yaml

CodePudding user response:

OK -- given that output2, this task will create foo:

- name: Build list
  set_fact:
    foo: |-
      {
      {% for item in output2.results %}
         "{{ item.item }}": {
                 "key1": "{{ item.msg.json.key1 }}",
                 "key3": "{{ item.msg.json.key3 }}"
          },
      {% endfor %}
      }
  • Related