有没有办法验证 Ansible Inventory 文件中组的主机数量?

Vij*_*jay 2 ansible ansible-inventory

我的要求如下所示,我有一个 Ansible 库存文件,它根据下面显示的组件分为几组:

[all]

node1 
node2
node3
node4

[webapp]
node3
node4

[ui]
node1
Run Code Online (Sandbox Code Playgroud)

如果条件失败,那么有没有办法验证库存文件中组的主机数量,那么 playbook 不应运行?

我的条件是:ui组应该始终只有一个主机。

前任:

[ui]
node1  -- condition check pass proceed with playbook execution

[ui]
node1 
node2  -- condition fails should stop playbook execution with exception 
          with ui group cannot have more than one hosts
Run Code Online (Sandbox Code Playgroud)

tec*_*raf 5

您可以在单个任务中轻松完成:


例如:

- name: Inventory validation
  hosts: localhost
  gather_facts: false
  tasks:
    - assert:
        that:
          - "groups['ui'] | length <= 1"
          - "groups['webapp'] | length <= 1"
Run Code Online (Sandbox Code Playgroud)

但是(这是基于评论)如果您先分配变量,则需要将值转换为整数以进行比较:

- name: Inventory validation
  hosts: localhost
  gather_facts: false
  vars:
    UI_COUNT: "{{ groups['ui'] | length }}"
    WEBAPP_COUNT: "{{ groups['webapp'] | length }}"
  tasks:
    - assert:
        that:
          - "UI_COUNT | int <= 1"
          - "WEBAPP_COUNT | int <= 1"
Run Code Online (Sandbox Code Playgroud)