简体   繁体   中英

Ansible. Select n-th item in a list of key:value pairs where key equals to x

From a list entities containing multiple items, determine which item (index number) has a key is_default equal to true . It is known that there's only one item in the list that meets this criteria. Assign the produced item to a variable.

---  
- hosts: databases
  gather_facts: true
  vars:
    entities:
      - name: dude
        is_default: false
        id: 2104
        gen: 12-C
      - name: mate
        is_default: true
        id: 1724
        gen: 13-A
      - name: pal 
        is_default: false
        id: 1809
        gen: 13-A                                                                                                                                                       

By looking at the list we can determine that the second item in a list named mate has a key is_default equal to true . The following demonstrates which item of a list needs to be selected:

---  
- hosts: databases
  gather_facts: true
  vars:
    entities:
      - name: dude
        is_default: false
        id: 2104
        gen: 12-C
      - name: mate
        is_default: true
        id: 1724
        gen: 13-A
      - name: pal 
        is_default: false
        id: 1809
        gen: 13-A
    selected_item: "{{ entities[1] }}"                                                                                                                                                        
  tasks:
    - name: show
      debug:
        msg: "{{ selected_item }}"

The selected_item variable stores the correct item of a list in this case. This approach needs to be avoided because the item where key is_default that equals true might be at any index in the list and the point is to avoid looking at the list to determine which item is needed. Needs to be solved within Ansible config file that is shown.

Try

selected_item: "{{ entities|selectattr('is_default')|list|first }}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM