[英]Ansible: count hosts based on specific fact
I'm using Ansible 2.9.13 to manage about 250 ubuntu clients.我正在使用 Ansible 2.9.13 来管理大约 250 个 ubuntu 客户端。 If I list all the facts of one client, one of the lines is:如果我列出一个客户的所有事实,其中一行是:
"distribution_release": "bionic",
What I would like to do now is count the number of machines, which are bionic, focal, and any other version it may find.我现在想做的是计算机器的数量,它们是仿生的、焦点的,以及它可能找到的任何其他版本。 So, something like this:所以,像这样:
bionic: 180
focal: 42
precise: 2
Is that possible and if yes, how?这是可能的,如果是,如何?
You can use group_by
to create new dynamic groups on the fly.您可以使用group_by
动态创建新的动态组。
---
- name: Count hosts based on ansible_distribution_release
hosts: "{{ target|default('all') }}"
gather_facts: true
tasks:
- name: Create dynamic groups
group_by:
key: dist_release_{{ ansible_distribution_release }}
- name: Make the statistics
hosts: localhost
gather_facts: false
tasks:
- name: Sample output
debug:
msg: "Group {{ item }} has {{ groups[item] | length }} hosts."
when: item.startswith('dist_release_')
loop: "{{ groups|flatten(levels=1) }}"
The first play creates dynamic groups based on {{ ansible_distribution_release }}
and all groups start with the prefix dist_
.第一个 play 基于{{ ansible_distribution_release }}
创建动态组,所有组都以前缀dist_
。
In the second play the dynamic groups will just be used to create a rather ugly but working statistics of the groups and the number of hosts within the groups.在第二场比赛中,动态组将仅用于创建组和组内主机数量的相当丑陋但有效的统计数据。
If you like you could just use Jinja2 template to create a nice output to a file.如果您愿意,您可以使用 Jinja2 模板创建一个不错的文件输出。
Create the dictionary from the hostvars in a single task在单个任务中从主机变量创建字典
- hosts: all
tasks:
- set_fact:
distros: "{{ distros|default({})|
combine({ item.0: item.1|length }) }}"
loop: "{{ hostvars|dict2items|
groupby('value.ansible_distribution_release') }}"
run_once: true
The same dictionary can be created without iteration when json_query is used使用json_query时无需迭代即可创建相同的字典
- hosts: all
tasks:
- set_fact:
distros: "{{ dict(keys|zip(vals)) }}"
vars:
dist: "{{ hostvars|dict2items|
json_query('[].{distro: value.ansible_distribution_release}')|
groupby('distro') }}"
keys: "{{ dist|map('first')|list }}"
vals: "{{ dist|map('last')|map('length')|list }}"
run_once: true
Next option is to create the dictionary with the help of a custom filter下一个选项是在自定义过滤器的帮助下创建字典
shell> cat filter_plugins/count.py
def count(l):
d = {}
for i in set(l):
d[i] = l.count(i)
return d
class FilterModule(object):
def filters(self):
return {
'count': count,
}
- hosts: all
tasks:
- set_fact:
distros: "{{ hostvars|
json_query('*.ansible_distribution_release')|
count}}"
run_once: true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.