Variable dictionary key not substituted

527 views Asked by At

I am struggling to figure out the proper syntax to variable-ize this snippet of code:

vm_cidr: '10.10.0.0/24'
vm_network: FOO
vm_gateway: '10.10.0.1'
networks:
     "{{ vm_cidr }}":
       network: "{{ vm_network }}"
       gateway: "{{ vm_gateway }}"

The substitution for vm_cidr never occurs. I've read this post but I'm still struggling. Any ideas how variable-ize this properly?

3

There are 3 answers

4
Konstantin Suvorov On BEST ANSWER

Here yo go:

networks: '{{ {vm_cidr:{"network":vm_network,"gateway":vm_gateway} } }}'

Note space at the end of dict to prevent double unnecessary double braces.

2
Anthon On

You cannot just assume that the scalar "vm_cidr" (without spaces at the back and front) is the same as "vm_cidr" within {{ and }}.

You should try:

vm_cidr: '10.10.0.0/24'
vm_network: FOO
vm_gateway: '10.10.0.1'
networks:
     "{{vm_cidr}}":
       network: "{{vm_network}}"
       gateway: "{{vm_gateway}}"
0
tread On

You can use the | character to create a multi-line scalar

vm_cidr: '10.10.0.0/24'
vm_network: FOO
vm_gateway: '10.10.0.1'
networks: |
    {
        "{{vm_cidr}}": {
           network: "{{vm_network}}"
           gateway: "{{vm_gateway}}"
        }
    }