[英]Ansible gather IPs of nodes in cluster
Here is a simple cluster inventory: 这是一个简单的群集清单:
[cluster]
host1
host2
host3
Each host has an interface
configured with ipv4 address. 每个主机都有一个配置有ipv4地址的interface
。 This information could be gathered with setup
module and will be in ansible_facts.ansible_{{ interface }}.ipv4.address
. 该信息可以通过setup
模块收集,并将位于ansible_facts.ansible_{{ interface }}.ipv4.address
。
How do to get IPv4 addresses for interface
from each individual host and make them available to each host in cluster
so that each host knows all cluster IPs? 如何从每个单独的主机获取interface
IPv4地址,并使它们可用于cluster
每个主机,以便每个主机都知道所有群集IP?
How this could be implemented in a role? 如何在角色中实现?
As @larsks already commented, the information is available in hostvars. 正如@larsks所说,该信息在hostvars中可用。 If you, for example, want to print all cluster IPs you'd iterate over groups['cluster']
: 例如,如果要打印所有要在groups['cluster']
遍历的群集IP:
- name: Print IP addresses
debug:
var: hostvars[item]['ansible_eth0']['ipv4']['address']
with_items: "{{ groups['cluster'] }}"
Note that you'll need to gather the facts first to populate hostvars
for the cluster hosts. 请注意,您需要首先收集事实以为集群主机填充hostvars
。 Make sure you have the following in the play where you call the task (or in the role where you have the task): 确保在调用任务的剧本中(或在拥有任务的角色中)具有以下内容:
- name: A play
hosts: cluster
gather_facts: yes
After searching for a while on how to make list variables with Jinja2. 搜索了一段时间后,如何使用Jinja2制作列表变量。 Here is complete solution that requires cluster_interface
variable and pings all nodes in cluster to check connectivity: 这是一个完整的解决方案,它需要cluster_interface
变量并ping集群中的所有节点以检查连接性:
---
- name: gather facts about {{ cluster_interface }}
setup:
filter: "ansible_{{ cluster_interface }}"
delegate_to: "{{ item }}"
delegate_facts: True
with_items: "{{ ansible_play_hosts }}"
when: hostvars[item]['ansible_' + cluster_interface] is not defined
- name: cluster nodes IP addresses
set_fact:
cluster_nodes_ips: "{{ cluster_nodes_ips|default([]) + [hostvars[item]['ansible_' + cluster_interface]['ipv4']['address']] }}"
with_items: "{{ ansible_play_hosts }}"
- name: current cluster node IP address
set_fact:
cluster_current_node_ip: "{{ hostvars[inventory_hostname]['ansible_' + cluster_interface]['ipv4']['address'] }}"
- name: ping all cluster nodes
command: ping -c 1 {{ item }}
with_items: "{{ cluster_nodes_ips }}"
changed_when: false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.