简体   繁体   中英

Ansible - create a list of unused disks

I am trying to create a list of unused disks from gather facts

-

           key | search ("sd")

     with_dict: "{{ ansible_devices }}"

But its only displaying one disk, like if the server have two unused disks sdb and sdc, its only displaying sdb. How can I modify my code to include all unused disks.

the way you have it, set_fact gets equal to the "current" item from the iteration, probably this is why you see only 1 disk in the final result. You need to set the disks as a list of elements and append to that list the current item.key . you can use this syntax:

set_fact:
   disks: "{{ disks|default([]) + ['/dev/{{item.key}}'] }}"

to understand how many results you have in the loops of the with_dict clause, you can try a debug task:

- name: Print disk result

     debug:
        msg: "/dev/{{item.key}}"

     when:
     - not item.value.partitions
     - not item.value.holders
     - not item.value.links.ids
     - item.key | search ("sd")

     with_dict: "{{ ansible_devices }}"

(indentation may need fixes, i just copied from your code)

hope it helps

thanks for the reply, I used the mentioned code for printing the disk result, it was displaying multiple disks, but when I used set_fact, and the msg to display the variable, its showing like this:-

"disks": [
        "/dev/sdc",
        "/dev/{{item.key}}"
    ]

   - name: Print disk result
     set_fact:
        disks: "{{ disks|default([]) + ['/dev/{{item.key}}'] }}"
     when:
     - not item.value.partitions
     - not item.value.holders
     - not item.value.links.ids
     - item.key | search ("sd")
     with_dict: "{{ ansible_devices }}"

   - debug: var=disks

If anyone is ever looking for the answer, this works for me:

- name: Print disk result
  set_fact:
    disks: "{{ disks|default([]) + ['/dev/' + item.key] }}"
  when:
  - not item.value.partitions
  - not item.value.holders
  - not item.value.links.ids
  - item.key | regex_search ("sd")
  with_dict: "{{ ansible_devices }}"

- name: debug
  debug:
    msg: "{{disks}}"

It returns:

ok: [localhost] => {
    "msg": [
        "/dev/sdb"
    ]
}

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