Ansible - 检查有多少 Play Host 具有变量值 X

问题描述 投票:0回答:1

我遇到以下 Ansible 问题。

每个宿主一个变量,我们称之为

is_master
,可以是“0”或“1”。

我现在想检查具有

is_master
== "1" 的主机数量是否大于 1。

所以我想做类似的事情

- set_fact: master_counter = "0"
- set_fact: {{ master_counter + 1 }}
  when: {{ hostvars['{{ item }}']['is_master'] }} == "1"
  loop: "{{ ansible_play_hosts_all }}"
  delegate_to: localhost
  run_once: true
- debug: msg="There is more than one master!"
  when: master_counter > 1
loops variables ansible hostvars
1个回答
0
投票

例如,给出用于测试的库存

shell> cat hosts
test:
  hosts:
    host_A:
      is_master: '1'
    host_B:
      is_master: '1'
    host_C:
      is_master: '0'

数数大师

  master_counter: "{{ ansible_play_hosts_all|
                      map('extract', hostvars, 'is_master')|
                      select('eq', '1')|length }}"

并显示结果

    - debug:
        msg: "master_counter={{ master_counter }}. There is more than one master!"
      when: master_counter|int > 1
      run_once: true

给予

  msg: master_counter=2. There is more than one master!

用于测试的完整剧本示例

- hosts: all

  vars:

    master_counter: "{{ ansible_play_hosts_all|
                        map('extract', hostvars, 'is_master')|
                        select('eq', '1')|length }}"

  tasks:

    - debug:
        var: is_master

    - debug:
        msg: "master_counter={{ master_counter }}. There is more than one master!"
      when: master_counter|int > 1
      run_once: true
© www.soinside.com 2019 - 2024. All rights reserved.