ansible - 如何获取所有节点列表 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"]
对此有任何想法吗?
解决方案
您的 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。
推荐阅读
- r - 如何在 R 中将数据表示为字符串,就像在 REPL 中一样?
- angular - 缩小屏幕时,卡片不改变行数
- javascript - 不输入指令
- php - 如何在 Laravel 中自定义作业的日志输出?
- angular - 多模块角度应用程序中的 ng-translate 问题
- gcloud - 我无法在 lubuntu 上运行 gcloud 命令
- php - Guzzle 请求:发布正文数据
- alamofire - swift 5中的Alamofire请求
- php - mysqli_prepare() 拒绝查询并失败
- angular - 值 getDay 不是函数 Typescript Angular