[英]Ansible gather IPs of nodes in cluster
这是一个简单的群集清单:
[cluster]
host1
host2
host3
每个主机都有一个配置有ipv4地址的interface
。 该信息可以通过setup
模块收集,并将位于ansible_facts.ansible_{{ interface }}.ipv4.address
。
如何从每个单独的主机获取interface
IPv4地址,并使它们可用于cluster
每个主机,以便每个主机都知道所有群集IP?
如何在角色中实现?
正如@larsks所说,该信息在hostvars中可用。 例如,如果要打印所有要在groups['cluster']
遍历的群集IP:
- name: Print IP addresses
debug:
var: hostvars[item]['ansible_eth0']['ipv4']['address']
with_items: "{{ groups['cluster'] }}"
请注意,您需要首先收集事实以为集群主机填充hostvars
。 确保在调用任务的剧本中(或在拥有任务的角色中)具有以下内容:
- name: A play
hosts: cluster
gather_facts: yes
搜索了一段时间后,如何使用Jinja2制作列表变量。 这是一个完整的解决方案,它需要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.