简体   繁体   English

Ansible - 创建未使用磁盘的列表

[英]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.但它只显示一个磁盘,例如如果服务器有两个未使用的磁盘 sdb 和 sdc,它只显示 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.按照您的方式, set_fact等于迭代中的“当前”项,这可能就是您在最终结果中只看到 1 个磁盘的原因。 You need to set the disks as a list of elements and append to that list the current item.key .您需要将disks设置为元素列表,并将当前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:要了解在with_dict子句的循环中有多少结果,您可以尝试debug任务:

- 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:-感谢您的回复,我使用提到的代码打印磁盘结果,它显示多个磁盘,但是当我使用 set_fact 和 msg 显示变量时,其显示如下:-

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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