首页 > 解决方案 > 如何获取所有节点列表 IP 地址?

问题描述

就我而言,有四个节点运行 ansible。我想获取每个节点的 IP 地址。因此我尝试了这些。

在我的 playbook.yml

- name: Ansible hosts: all gather_facts: true vars: ansible_ec2_local_ipv4: "{{ ansible_default_ipv4.address }}" roles: - role: "ansible-mongo/roles/mongo" - role: "ansible-mongo/roles/replication"

在我的 main.yml

        - name: ensure file exists
          copy:
            content: ""
            dest: /tmp/myconfig.cfg
            force: no
            group: "{{ mongodb_group }}"
            owner: "{{ mongodb_user }}"
            mode: 0555


        - name: Create List of nodes to be added into Cluster
          set_fact: nodelist={%for host in groups['all']%}"{{hostvars[host].ansible_eth0.ipv4.address}}"{% if not loop.last %},{% endif %}{% endfor %}

        - debug: msg=[{{nodelist}}]

        - name: Set Cluster node list in config file
          lineinfile:
            path: "/tmp/myconfig.cfg"
            line: "hosts: [{{ nodelist }}]"

但结果当我试图查看 /tmp/myconfig.cfg 文件时。我只得到一个IP。

 cat /tmp/myconfig.cfg 
 hosts: ["10.1.49.149"]

对此有任何想法吗?

标签: ansible

解决方案


您的 set_fact 循环在每次传递时都会覆盖“nodelist”的值,这实际上意味着您只会得到循环中的最后一个元素。试试这个:

- set_fact:
    nodelist: "{{ ( nodelist | default([]) ) + [ hostvars[item].ansible_eth0.ipv4.address ] }}"
  loop: "{{ groups['all'] }}"
- debug:
    var: nodelist | join(',')
  • (nodelist | default([]))如果未设置,则输出“nodelist”的当前值或空列表(第一次通过)
  • + []将现有列表与新列表合并,其中包含单个元素 - 主机的 IP

所以'nodelist'最终会包含一个IP列表。然后,您可以使用| join(',')将其转换为 CSV。


推荐阅读