簡體   English   中英

Ansible 比較兩個列表變量

[英]Ansible compare two list variables

我必須檢查系統上是否有可用的掛載點列表。
所以,我用掛載點列表定義了一個變量,然后從 Ansible 事實中提取可用的掛載點。

---
- 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也總是失敗。

我必須一個一個循環嗎? 並逐項比較? 如果是這樣,我怎樣才能做到這一點?

您可以為此使用集合論,因為您要尋找的只是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`'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM