Fitri Izuan
Fitri Izuan

Reputation: 370

Ansible Debug array of object for specific value using Loop?

I have the following array of record with the value:

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

Upvotes: 0

Views: 2429

Answers (2)

Sebastiaan
Sebastiaan

Reputation: 116

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.

Upvotes: 0

Fitri Izuan
Fitri Izuan

Reputation: 370

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

Upvotes: 1

Related Questions