如果服务器上不存在磁盘sdb,如何显示“磁盘不存在”之类的消息

时间:2019-12-11 00:41:37

标签: ansible ansible-facts

如果服务器上不存在磁盘sdb,如何显示“磁盘不存在”之类的消息。

我尝试了以下方法,但是没有用。

  - debug:
     msg: "disk does not exist"
    when: ansible_devices != "sdb"

  - debug:
     msg: "disk does not exist"
    when: item.key != "sdb"
    with_dict: "{{ ansible_devices }}"

  - debug:
     msg: "disk does not exist"
    when: ansible_devices.sdb == "false"

谢谢

1 个答案:

答案 0 :(得分:0)

ansible_devices是设备的字典。还有更多选项可用于确定设备是否存在。

1)让我们创建设备列表,并搜索设备列表。例如

- hosts: localhost
  gather_facts: true
  tasks:
    - debug:
        msg: Disk nvme0n1 exists.
      when: "'nvme0n1' in ansible_devices.keys()|list"
    - debug:
        msg: Disk sdb does not exist.
      when: "'sdb' not in ansible_devices.keys()|list"

给予

"msg": "Disk nvme0n1 exists."
"msg": "Disk sdb does not exist."

2)也可以测试变量是否定义 。例如,这出戏的结果相同

    - debug:
        msg: Disk nvme0n1 exists.
      when: ansible_devices.nvme0n1 is defined
    - debug:
        msg: Disk sdb does not exist.
      when: ansible_devices.sdb is undefined

3)也可以使用以下事实:一个空变量的值为False 。例如,这出戏的结果相同

    - debug:
        msg: Disk nvme0n1 exists.
      when: ansible_devices.nvme0n1|default('')
    - debug:
        msg: Disk sdb does not exist.
      when: not ansible_devices.sdb|default('')