1

这是一个简单的集群清单:

[cluster]
host1
host2 
host3

每个主机都有一个interface配置了 ipv4 地址。此信息可以使用setup模块收集,并将在ansible_facts.ansible_{{ interface }}.ipv4.address.

如何interface从每个单独的主机获取 IPv4 地址并使它们可用于每个主机,cluster以便每个主机知道所有集群 IP?

如何在角色中实现这一点?

4

2 回答 2

0

在搜索了一段时间后如何使用 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
于 2017-09-27T11:01:55.803 回答
0

正如@larsks 已经评论的那样,这些信息在hostvars 中可用。例如,如果您想打印您要迭代的所有集群 IP groups['cluster']

- 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
于 2017-09-27T07:56:21.853 回答