I have an Ansible variable called port_mapping that is assigned an array of JSON objects. I want to create this array of JSON objects in a dynamic way using Jinja2 templates.
ports_mapping:
- name: Et1
port_number: 1
type: access
vlan: 1
- name: Et2
port_number: 2
type: access
vlan: 1
- name: Et3
port_number: 3
type: access
vlan: 1
- name: Et4
port_number: 4
type: access
vlan: 1
Here's what I am trying to do and it's throwing errors, I think it's reading the spacing wrong so it doesn't interpret it as an array of json objects. In this example, I want to create 30 JSON objects.
ports_mapping: "{{ lookup('template', 'switchports.j2') }}"
switchports.j2
{% for i in range(1,30) %}
- name: Et{{ i }}
port_number: {{ i }}
type: access
vlan: 1
{% endfor %}
Can someone please recommend how I can achieve what I am trying to do?
The result of the template is string
- debug:
var: ports_mapping
- debug:
var: ports_mapping|type_debug
give (the range limited to 2 items)
ports_mapping: |-
- name: Et1
port_number: 1
type: access
vlan: 1
- name: Et2
port_number: 2
type: access
vlan: 1
ports_mapping|type_debug: str
Use the filter from_yaml to convert the string to the list
ports_mapping: "{{ lookup('template', 'switchports.j2')|from_yaml }}"
Then the tasks above give
ports_mapping:
- name: Et1
port_number: 1
type: access
vlan: 1
- name: Et2
port_number: 2
type: access
vlan: 1
ports_mapping|type_debug: list
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.