有没有一种方法可以验证Ansible库存文件中某个组的主机数量? [英] Is there a way to validate the number of hosts for a group in Ansible Inventory file?
问题描述
我的要求如下所示,我有一个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:
-
使用Ansible 使用
length
过滤器对其进行组合以计算数量ui
组中的元素的数量,combine it with
length
filter to count the number of elements inui
group,将以上内容插入
assert
或fail
模块来验证和控制流程.insert the above into an arithmetic comparison conditional in
assert
orfail
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库存文件中某个组的主机数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!