Ansible收集集群中的节点IP

时间:2017-09-26 15:52:21

标签: ansible ansible-facts

以下是一个简单的群集清单:

[cluster]
host1
host2 
host3

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

如何从每个主机获取interface的IPv4地址,并使cluster中的每个主机都可以使用这些地址,以便每个主机都知道所有群集IP?

如何在角色中实施?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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