Ansible 在循环中打印ip地址
我正在尝试将一条线与我的集群的ip地址放在一个循环中:Ansible 在循环中打印ip地址,ansible,Ansible,我正在尝试将一条线与我的集群的ip地址放在一个循环中: set_fact: nodelist={%for host in groups['proxmox-cluster']%}"{{hostvars[host].ansible_all_ipv4_addresses|string}}"{% if not loop.last %},{% endif %}{% endfor %} 但是当我试图把这一行放进一个 lineinfile: path: "/etc/security/acc
set_fact: nodelist={%for host in groups['proxmox-cluster']%}"{{hostvars[host].ansible_all_ipv4_addresses|string}}"{% if not loop.last %},{% endif %}{% endfor %}
但是当我试图把这一行放进一个
lineinfile:
path: "/etc/security/access.conf"
line: "+:root:{{ nodelist }}"
我得到:
“[u'192.168.31.238'],[u'192.168.31.248'],[u'192.168.31.252'],“[u'192.168.31.250',u'192.168.1.250',u'192.168.32.250',u'192.168.33.250']”
而不是
192.168.31.238192.168.31.248192.168.31.252192.168.31.250192.168.1.250192.168.32.250192.168.33.250
尝试下面更简单的版本
- set_fact:
nodelist: "{{ nodelist|default([]) + hostvars[item].ansible_all_ipv4_addresses }}"
loop: "{{ groups['proxmox-cluster'] }}"
尝试在lineinfile模块中的nodelist变量上使用筛选器:
原因是,
hostvars[host].ansible\u all\u ipv4\u地址
是一个数组。这就是为什么要在数组中打印字符串的联接列表“[u'192.168.31.238']”,“[u'192.168.31.248']”,…
如果只想打印默认ipv4地址,则可以将hostvars表达式替换为:
hostvars[host].ansible_default_ipv4.address
hostvars[host].ansible_all_ipv4_addresses | first
如果要打印地址总数列表中的第一个地址,可以将hostvars表达式替换为:
hostvars[host].ansible_default_ipv4.address
hostvars[host].ansible_all_ipv4_addresses | first
如果要包含来自所有主机的所有ip地址,则需要两个循环。这可以通过Jinja2模板语法、巧妙的过滤器链或两者来实现。例如,将整个表达式替换为带有筛选器的jinja2循环的组合将为您提供:
{% for host in groups['proxmox-cluster'] %}"{{ hostvars[host].ansible_all_ipv4_addresses | join(',') }}"{% if not loop.last %},{% endif %}{% endfor %}
就我个人而言,我尽量避免在ansible任务/剧本中混用Jinja2模板语法。通常有一种更干净的方法,只使用过滤链。例如,在您的情况下,您可以执行以下操作:
- name: Print ips in access.conf
lineinfile:
path: /etc/security/access.conf
line: "{{ groups['proxmox-cluster']
| map('extract', hostvars, 'ansible_default_ipv4')
| map(attribute='address')
| join(',') }}"
非常感谢!我也不想把这些混在一起,所以我听从了你的建议。而且它工作得很好;-)