【问题标题】:Is there a way to validate the number of hosts for a group in Ansible Inventory file?有没有办法验证 Ansible Inventory 文件中组的主机数量?
【发布时间】:2017-11-29 09:41:22
【问题描述】:

我的需求如下所示,我有一个 Ansible 库存文件,该文件根据如下所示的组件分为几组:

[all]

node1 
node2
node3
node4

[webapp]
node3
node4

[ui]
node1

如果条件失败,是否有办法验证清单文件中组的主机数量,那么 playbook 不应该运行?

我的条件是:ui 组应该始终只有一个主机。

例如:

[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

【问题讨论】:

    标签: ansible ansible-inventory


    【解决方案1】:

    您可以在单个任务中轻松完成:


    例如:

    - name: Inventory validation
      hosts: localhost
      gather_facts: false
      tasks:
        - assert:
            that:
              - "groups['ui'] | length <= 1"
              - "groups['webapp'] | length <= 1"
    

    但是(这是基于注释)如果您首先分配变量,则需要将值转换为整数进行比较:

    - 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"
    

    【讨论】:

    • - 名称:库存验证主机:localhost gather_facts:false vars:UI_COUNT:“{{ groups['ui'] | length }}” WEBAPP_COUNT:“{{ groups['webapp'] | length }}” 任务:-名称:检查失败:msg:“不正确的主机数”当:-UI_COUNT > 1 - WEBAPP_COUNT > 1 断言:那:-“UI_COUNT > 1”失败或断言块即使在我的条件下也会执行是假的,我错过了什么吗?
    • @Vijay 阅读评论中插入的代码真的很难——例如你的assert前面没有破折号,所以我根本不知道它是什么;但最可能的问题是您需要将值转换为整数:UI_COUNT|int &gt; 1 和 WEBAPP_COUNT|int &gt; 1。还可以使用when 中的列表,使用逻辑and 加入条件。
    • @Vijay 查看我添加到答案中的示例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多