本文介绍了有没有办法验证 Ansible Inventory 文件中组的主机数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My requirement is shown below, I have an Ansible inventory file which is divided into some groups based on the components shown below:

[all]

node1
node2
node3
node4

[webapp]
node3
node4

[ui]
node1

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

Is there a way to validate the number of hosts for a group in inventory file if condition fails then playbook should not run ?

我的条件是:ui 组应该总是只有一个主机.

My condition is: ui group should always have only one host.

例如:

[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

推荐答案

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

You can easily do it in a single task:

将它与 length 过滤器结合 统计ui组中的元素个数,

combine it with length filter to count the number of elements in ui group,

将上述内容插入assertfail 验证和控制流程的模块.

insert the above into an arithmetic comparison conditional in assert or fail module to verify and control the flow.

例如:

- name: Inventory validation
  hosts: localhost
  gather_facts: false
  tasks:
    - assert:
        that:
          - "groups['ui'] | length <= 1"
          - "groups['webapp'] | length <= 1"

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

But (this is based on comment) if you assign the variables first, you need to cast the value to integer in comparison:

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

这篇关于有没有办法验证 Ansible Inventory 文件中组的主机数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 03:05