我无法从Jinja 2的字典中的列表中获取第n个元素(IP地址)。
我的剧本
---
- name: Test dictionaries playbook
hosts: test
remote_user: user
vars:
list_dict:
- {"hostname": "server01", "ip": [ '10.10.10.161', '10.10.10.250', '10.228.115.120', '10.10.10.224' ] }
- {"hostname": "server02", "ip": [ '10.10.10.162', '10.10.10.253', '10.228.115.121', '10.10.10.225' ] }
tasks:
- name: Get Facts
template:
src: ../template.j2
dest: /tmp/template-out
delegate_to: localhost
with_items: list_dict
模板使用的是“ template.j2”
{% for host in list_dict %}
Current host is {{host.hostname}}
The ips for this host are:
{% for ip in host.ip %}
{{ ip[0] }}
{% endfor %}
{% endfor %}
当前输出(我想它是每个IP的第一个元素为“ 1”
Current host is server01
The ips for this host are:
1
1
1
1
Current host is server02
The ips for this host are:
1
1
1
1
所需的输出(我想为每个主机获取整个第一个IP)
知道我该如何完成吗?
The ips for this host are:
10.10.10.161
Current host is server02
The ips for this host are:
10.10.10.162
在Python中,应该是这样的:
hostname = { "name" : "server02", "ip": [ '10.10.10.162', '10.228.115.121', '10.10.10.225', '10.10.10.251' ] }
print hostname["ip"][0]
10.10.10.162
答案 0 :(得分:0)
与您已经提到的完全相同。不需要内部循环。
{% for host in list_dict %}
Current host is {{host.hostname}}
The ips for this host are:
{{ host.ip[0] }}
{% endfor %}