直接上列子吧:
比如有如下的一个hosts文件,我分别想获取主机组master、node、cluster的主机数量
[master]
192.168.100.28 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass='root' host_id=1
192.168.100.29 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass='root' host_id=2
192.168.100.30 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass='root' host_id=3
[node]
192.168.100.31 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass='root' host_id=4
[cluster:children]
master
node
全局变量这样定义:
Master_Count: "{{ groups['master'] | length }}"
Node_Count: "{{ groups['node'] | length }}"
Cluster_Count: "{{ groups['cluster'] | length }
}"
得到结果分别是:3、1、4
{% for n in range(groups['test'] | length) %}
{{ hostvars[groups['test'][n]]['ip'] }}
{% endfor %}