简体   繁体   English

使用 Jinja2 模板将 Ansible 变量分配给 JSON 对象的动态数组

[英]Assign Ansible variable to dynamic array of JSON objects using Jinja2 template

I have an Ansible variable called port_mapping that is assigned an array of JSON objects.我有一个名为 port_mapping 的 Ansible 变量,它分配了一个 JSON 对象数组。 I want to create this array of JSON objects in a dynamic way using Jinja2 templates.我想使用 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

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.这是我正在尝试做的事情,它正在抛出错误,我认为它读取的间距错误,因此它不会将其解释为 json 对象的数组。 In this example, I want to create 30 JSON objects.在这个例子中,我想创建 30 个 JSON 对象。

ports_mapping: "{{ lookup('template', 'switchports.j2') }}"

switchports.j2交换机端口.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)给(范围限于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

Use the filter from_yaml to convert the string to the list使用过滤器from_yaml将字符串转换为列表

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

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

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