簡體   English   中英

群集中節點的Ansible收集IP

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM