未替换变量字典键

Variable dictionary key not substituted

我正在努力找出正确的语法来对这段代码进行变量化:

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 }}"

vm_cidr 的替换从未发生。我读过 post 但我仍在挣扎。知道如何正确地对其进行变量化吗?

您不能假设标量“vm_cidr”(前后没有空格)与 {{ 和 [=14= 中的“vm_cidr”相同].

你应该试试:

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}}"

给你:

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

注意 dict 末尾的 space 以防止不必要的双括号。

您可以使用 | 字符创建多线标量

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}}"
        }
    }