Access nested YAML mappings using jinja2

I recently started using YAML and jinja2. I am having trouble understanding why I need to reference the whole structure of my YAML mapping in the jinja2 template.

I have the following yaml file

---
PROVIDERS:
    PROV1:
        int: ge-0/1/1
        ipv4: 10.0.1.1/30
    PROV2:
        int: ge-0/1/2
        ipv4: 10.0.1.2/30

and this is my jinja2 template

{%- for provider in PROVIDERS %}
    {{ provider }}
    {{ PROVIDERS[provider].int }}   <-- why not provider.int
    {{ PROVIDERS[provider].ipv4 }}  <-- why not provider.ipv4
{%- endfor %}

Pyyaml ​​analysis gives me (expected) output

PROV2
ge-0/1/2
10.0.1.2/30
PROV1
ge-0/1/1
10.0.1.1/30

However, why should I use PROVIDERS[provider].int? provider.intdoes not work.

Also, I was wondering if I can make this a list of mappings instead of a nested mapping:

---
PROVIDERS:
    - PROV1:
        int: ge-0/1/1
        ipv4: 10.0.1.1/30
    - PROV2:
        int: ge-0/1/2
        ipv4: 10.0.1.2/30

I tried to do this, but the jinja2 template no longer produced the desired result.

+4
source share
1 answer

There are two things here:

  • Python YAML?
  • ?

1 :

>>> import yaml
>>> from pprint import pprint
>>> p1 = yaml.load("""
... ---
... PROVIDERS:
...     PROV1:
...         int: ge-0/1/1
...         ipv4: 10.0.1.1/30
...     PROV2:
...         int: ge-0/1/2
...         ipv4: 10.0.1.2/30
... """)
>>> pprint(p1)
{'PROVIDERS': {'PROV1': {'int': 'ge-0/1/1', 'ipv4': '10.0.1.1/30'},
               'PROV2': {'int': 'ge-0/1/2', 'ipv4': '10.0.1.2/30'}}}

, 'PROVIDERS', 'PROV1' 'PROV2', . , ( ), , , , .

:

{%- for provider in PROVIDERS %}

PROVIDERS (, , , , , 'PROVIDERS' ), , , , :

{{ PROVIDERS[provider].int }}
{{ PROVIDERS[provider].ipv4 }}

YAML :

---
- id: PROV1
  int: ge-0/1/1
  ipv4: 10.0.1.1/30
- id: PROV2
  int: ge-0/1/2
  ipv4: 10.0.1.2/30

, . , , :

>>> p2 = yaml.load("""
... ---
... - id: PROV1
...   int: ge-0/1/1
...   ipv4: 10.0.1.1/30
... - id: PROV2
...   int: ge-0/1/2
...   ipv4: 10.0.1.2/30
... """)
>>> pprint(p2)
[{'int': 'ge-0/1/1', 'ipv4': '10.0.1.1/30', 'id': 'PROV1'},
 {'int': 'ge-0/1/2', 'ipv4': '10.0.1.2/30', 'id': 'PROV2'}]

:

{%- for provider in PROVIDERS %}
    {{ provider.id }}
    {{ provider.int }}
    {{ provider.ipv4 }}
{%- endfor %}

, , PROVIDERS , , YAML, , .

+4
source

Source: https://habr.com/ru/post/1569555/


All Articles