繁体   English   中英

Ansible Jinja2从字典中的列表中获取元素

[英]Ansible Jinja2 get element from list inside dictionary

我无法从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

与您已经提到的完全相同。 不需要内部循环。

{% for host in list_dict %}
   Current host is {{host.hostname}}
   The ips for this host are:
   {{ host.ip[0] }}
{% endfor %}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM