使用 Jinja2 模板将 Ansible 变量分配给 JSON 个对象的动态数组
Assign Ansible variable to dynamic array of JSON objects using Jinja2 template
我有一个名为 port_mapping 的 Ansible 变量,它被分配了一个 JSON 对象数组。我想使用 Jinja2 模板以动态方式创建这个 JSON 对象数组。
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
这是我正在尝试做的事情,它抛出错误,我认为它读取的间距有误,因此它不会将其解释为 json 对象的数组。在此示例中,我想创建 30 个 JSON 个对象。
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 %}
有人可以推荐我如何实现我想要做的事情吗?
模板的结果是字符串
- debug:
var: ports_mapping
- debug:
var: ports_mapping|type_debug
给(范围限制为2项)
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
使用过滤器from_yaml将字符串转换为列表
ports_mapping: "{{ lookup('template', 'switchports.j2')|from_yaml }}"
然后上面的任务给
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
我有一个名为 port_mapping 的 Ansible 变量,它被分配了一个 JSON 对象数组。我想使用 Jinja2 模板以动态方式创建这个 JSON 对象数组。
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
这是我正在尝试做的事情,它抛出错误,我认为它读取的间距有误,因此它不会将其解释为 json 对象的数组。在此示例中,我想创建 30 个 JSON 个对象。
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 %}
有人可以推荐我如何实现我想要做的事情吗?
模板的结果是字符串
- debug:
var: ports_mapping
- debug:
var: ports_mapping|type_debug
给(范围限制为2项)
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
使用过滤器from_yaml将字符串转换为列表
ports_mapping: "{{ lookup('template', 'switchports.j2')|from_yaml }}"
然后上面的任务给
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