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
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 inui
group,insert the above into an arithmetic comparison conditional in
assert
orfail
module to verify and control the flow.For example:
But (this is based on comment) if you assign the variables first, you need to cast the value to integer in comparison: