问题
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 ?
My condition is: ui
group should always have only one host.
Ex:
[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
回答1:
You can easily do it in a single task:
use Ansible magic variable groups,
combine it with length filter to count the number of elements in
ui
group,insert the above into an arithmetic comparison conditional in assert or fail module to verify and control the flow.
For example:
- 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"
来源:https://stackoverflow.com/questions/47549533/is-there-a-way-to-validate-the-number-of-hosts-for-a-group-in-ansible-inventory