提问人:Bl Jay 提问时间:9/1/2023 最后编辑:isherwoodBl Jay 更新时间:9/2/2023 访问量:40
如何查看 Ansible 中有多少 Play 主机具有变量值 X?
How can I check how many Play Hosts have variable value X in Ansible?
问:
我有以下 Ansible 问题。
每个主机都有一个变量,我们称之为 ,它可以是 “0” 或 “1”。is_master
我现在想检查具有 ==“1”的主机数量是否为 g而不是 1。is_master
所以我想做类似的事情
- 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
答:
2赞
Vladimir Botka
9/2/2023
#1
例如,给定用于测试的清单
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!
- 用于测试的完整 playbook 示例
- 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
- 使用布尔值而不是 stings 更实用
test:
hosts:
host_A:
is_master: true
host_B:
is_master: true
host_C:
is_master: false
计数稍微简单一些
master_counter: "{{ ansible_play_hosts_all|
map('extract', hostvars, 'is_master')|
select()|length }}"
- 上述选项将主机数限制为受播放ansible_play_hosts_all限制的主机。如果需要,可以计算清单中的所有主机
master_counter: "{{ hostvars|
json_query('*.is_master')|
select()|length }}"
评论