2017-09-26 60 views
1

下面是一个简单的集群清单:Ansible聚集节点的IP地址在簇

[cluster] 
host1 
host2 
host3 

每个主机具有IPv4地址配置的interface。这些信息可以用setup模块收集,并将在ansible_facts.ansible_{{ interface }}.ipv4.address

如何从每台主机获得interface的IPv4地址,并使其可用于每台主机cluster,以便每台主机知道所有集群IP?

这是如何在角色中实现的?

+0

此信息* *已提供给集群中的每个主机通过使用[HOSTVARS](HTTPS://docs.ansible .COM/ansible /最新/ playbooks_variables.html#魔变量和 - 如何对接入信息有关,其他的主机)。 – larsks

回答

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 
0

寻找如何使列表变量与Jinja2的一段时间之后。这里是一个需要在集群cluster_interface变量和坪的所有节点来检查连接的完整的解决方案:

--- 
- 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