Ansible 比较两个列表变量

Ansible compare two list variables

我必须检查系统上是否有可用的挂载点列表。
所以,我用挂载点列表定义了一个变量,然后从 Ansible facts 中提取了可用的挂载点。

---
- hosts: all
  vars:
    required_mounts:
      - /prom/data
      - /prom/logs

  tasks:
    - name: debug mountpoint
      set_fact:
        mount_points: "{{ ansible_mounts|json_query('[].mount') }}"

    - name: check fs
      fail:
        msg: 'mount point not found'
      when: required_mounts not in mount_points

我卡在这里了,我不知道如何比较变量 required_mounts 和现有的挂载点。
如果 required_mounts 中的任何项目不在现有挂载点中,任务应该失败。

任务 check fs 总是失败,即使安装点存在。

我必须一个一个循环吗?并逐项比较?如果是这样,我该如何实现?

您可以为此使用 set theory,因为您要查找的只是 required_mountsansible_mounts 之间的区别。

此外,这里不需要JMESPath查询,这个简单的需求可以通过简单的map.

实现

所以,这可以单独通过任务来实现:

- fail:
    msg: "Missing mounts: `{{ missing_mounts | join(', ') }}`" 
  when:  missing_mounts | length > 0
  vars:
    missing_mounts: >-
      {{ 
        required_mounts 
          | difference(
              ansible_mounts | map(attribute='mount')
            ) 
      }}

鉴于剧本:

- hosts: localhost
  gather_facts: yes
  vars:
    required_mounts:
      - /etc/hostname
      - /etc/hosts
      - /tmp/not_an_actual_mount
      - /tmp/not_a_mount_either

  tasks:
    - fail:
        msg: "Missing mounts: `{{ missing_mounts | join(', ') }}`" 
      when:  missing_mounts | length > 0
      vars:
        missing_mounts: >-
          {{ 
            required_mounts 
              | difference(ansible_mounts 
              | map(attribute='mount')) 
          }}

这产生:

TASK [Gathering Facts] *******************************************************
ok: [localhost]

TASK [fail] ******************************************************************
fatal: [localhost]: FAILED! => changed=false 
  msg: 'Missing mounts: `/tmp/not_an_actual_mount, /tmp/not_a_mount_either`'