Ansible Jinja2 получить элемент из списка внутри словаря - PullRequest
0 голосов
/ 12 октября 2018

Я не могу получить n-й элемент (IP-адрес) из списка внутри словаря в Jinja 2.

моей пьесы

---
- 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

1 Ответ

0 голосов
/ 12 октября 2018

Точно так же, как вы уже упоминали.Внутренний цикл не требуется.

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