Ansible獲取主機分組的個數並獲取ip

比如有如下的一個hosts檔案,我分別想獲取主機組master、node、cluster的主機數量

[master]192。168。100。28 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass=‘root’ host_id=1192。168。100。29 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass=‘root’ host_id=2192。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]masternode1234567891011

全域性變數這樣定義:

Master_Count: “{{ groups[‘master’] | length }}”Node_Count: “{{ groups[‘node’] | length }}”Cluster_Count: “{{ groups[‘cluster’] | length }123

}”

得到結果分別是:3、1、4

{% for n in range(groups[‘test’] | length) %}{{ hostvars[groups[‘test’][n]][‘ip’] }}{% endfor %}