Is there a way to validate the number of hosts for a group in Ansible Inventory file?

时光怂恿深爱的人放手 提交于 2020-01-04 05:31:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!