0

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?

0

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much! You're a live-saver

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.