0

I have the following array of record with the value:

  • myRecord.record.0.number = "Number 0"
  • myRecord.record.1.number = "Number 1"
  • myRecord.record.2.number = "Number 2"
  • myRecord.record.3.number = "Number 3"

How to create a playbook to debug the above value using loop dynamically/for every array?

for other common languange it can be done as follows:

for(int i = 0; i < myRecord.length(); i++)
{
   echo myRecord.record.[i].number
}

for the repeating task of the playbook, it will looks like this:

---

- hosts: localhost
  name: Array of Object
  gather_facts: false

  tasks:
    - name: using debugMsg
      debug: 
        msg: 
          -   "{{ myRecord.record.0.number  }}"
          -   "{{ myRecord.record.1.number  }}"
          -   "{{ myRecord.record.2.number  }}"
          -   "{{ myRecord.record.3.number  }}"
James Z
  • 12,209
  • 10
  • 24
  • 44
Fitri Izuan
  • 350
  • 1
  • 6
  • 18

2 Answers2

1

I have figured out how to do this. Basically I just need to use loop_control to filter which specific value I need. Here is the playbook:

---

- hosts: localhost
  name: Array of Object
  gather_facts: false
  tasks:
    - name: using loop_control
      debug:
        msg: "{{ item.number }}"
      with_items:
        - "{{ myRecord.record }}"  #this will become 'item'
      loop_control:
        label: "{{ item.number }}" #filter to display the value of number only
Fitri Izuan
  • 350
  • 1
  • 6
  • 18
0

There are two methods. The first method uses the with_* keyword, and depends on the Lookup plugin. The second method uses loop keyword, which is equivalent to 'with_' + 'list lookup plugin' (so you get 'with_list').

Now, assuming your data structure looks like this:

---
# vars file for print_variable_from_list
myRecord:
  record:
    - number: "Number 0"
    - number: "Number 1"
    - number: "Number 2"
    - number: "Number 3"

Every number is indexable with the "number" key.

- name: loop through myRecord
  debug:
    msg: "{{  item.number  }}"
  loop: "{{ myRecord.record }}"

Kindly refer to other posts for more complex queries.

Sebastiaan
  • 106
  • 7
  • Hi, thank you for reply. However, ur answer will display the whole value of the record. For example each record may have: - myRecord.record.[i].number - myRecord.record.[i].name - myRecord.record.[i].email - myRecord.record.[i].status What I want to do is that it will only display/list the 'myRecord.record.[i].number' for every existing records, not the whole things. – Fitri Izuan Apr 13 '20 at 10:12
  • Hey, I edited my answer. Does it answer your question now? – Sebastiaan Apr 13 '20 at 12:32
  • I have tried that. It still debug/print the whole value of the records. What I did is filter the output by using loop_control as described above. – Fitri Izuan Apr 13 '20 at 13:52