Create config from array with 1 element

Hi all.

I have an application with j2 config.yaml:

    address1:
      redirect_urls: {{ web1_address }}
    address2:
      redirect_urls: {{ web2_address }}

and variables:

web1_address:
  - https://web1.{{ stack_dns_zone }}/endpoint
web2_address:
  - https://web2.{{ stack_dns_zone }}/endpoint

When I use array with only 1 element, it generates a wrong config(in one string, with square brackets and quotes):

    address1:
      redirect_urls: ["https://web1.{{ stack_dns_zone }}/endpoint"]
    address2:
      redirect_urls: ["https://web2.{{ stack_dns_zone }}/endpoint"]

but I need to get this structure:

    address1:
      redirect_urls: 
        - https://web1.{{ stack_dns_zone }}/endpoint
    address2:
      redirect_urls: 
        - https://web2.{{ stack_dns_zone }}/endpoint

Could you answer, please: how I need to retrieve vars from array with 1 element, to generate right config with required structure?

1 Like

Your template says to interpolate complex (more than simple scalars) data without specifying the format. The default formatted yaml is equivalent to what you want, but if you want it to look another way you need to be specific. Try this in your template:

    address1:
      redirect_urls: {{ web1_address | to_nice_yaml() }}
    address2:
      redirect_urls: {{ web2_address | to_nice_yaml() }}
1 Like

The filter to_nice_yaml is a good start. Complete it with the filter indent. For example,

- copy:
    dest: /tmp/config.yml
    content: |
      address1:
        redirect_urls:
          {{ web1_address | to_nice_yaml(indent=2) | indent(4) }}
      address2:
        redirect_urls:
          {{ web2_address | to_nice_yaml(indent=2) | indent(4) }}
  vars:
    stack_dns_zone: example.com
    web1_address:
      - https://web1.{{ stack_dns_zone }}/endpoint
      - https://web3.{{ stack_dns_zone }}/endpoint
    web2_address:
      - https://web2.{{ stack_dns_zone }}/endpoint
      - https://web4.{{ stack_dns_zone }}/endpoint

gives

shell> cat /tmp/config.yml
address1:
  redirect_urls:
    - https://web1.example.com/endpoint
    - https://web3.example.com/endpoint

address2:
  redirect_urls:
    - https://web2.example.com/endpoint
    - https://web4.example.com/endpoint
2 Likes

@utoddl @vbotka good morning!
Thank you for reply with good examples and description:-)
I’ll try it now.

2 Likes

Hello!
It works.
Thank you very much!

1 Like