Is there a way to validate the number of hosts for

2019-07-20 05:35发布

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条回答
我只想做你的唯一
2楼-- · 2019-07-20 05:44

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"
查看更多
登录 后发表回答