就我而言,有四个运行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"]
对此有任何想法吗?
答案 0 :(得分:1)
您的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。