我通过Ansible模块os_networks_facts获取Openstack网络信息。
此模块以openstack_networks结构返回信息:
"openstack_networks": [
{
"admin_state_up": true,
"id": "5632dc44-dbda-4752-8155-fe782e95cc29",
"mtu": 0,
"name": "public_RSC",
"port_security_enabled": true,
"router:external": true,
"shared": false,
"status": "ACTIVE",
"subnets": [
"7b07432c-f0a0-415a-8b28-7e87918cc6d4",
"a56e25cb-0710-4a64-869e-4af2d5bf9c64",
"c4ff60af-44bc-4252-ab38-fd242d51f0f2"
],
"tenant_id": "6025f8013cee46c093cb97cb36a1a86e"
},
{
"admin_state_up": true,
"id": "7812f951-4bc9-41c0-9db2-1f49b8a7ee47",
"mtu": 0,
"name": "kuby-network",
"port_security_enabled": true,
"router:external": false,
"shared": false,
"status": "ACTIVE",
"subnets": [
"6ad9ce9b-ba54-4d74-bbb6-8dfc50526eff"
],
"tenant_id": "a9cffc26ba5a4a8e883f04dc7180a91d"
}
]
我想对“ router:external”属性的值进行测试。但是,此属性的名称中包含一个冒号。
当我尝试通过以下方式在Ansible中进行打印时:
- hosts: localhost
connection: local
gather_facts: false
tasks:
- name: get network information
os_networks_facts:
cloud: "{{ InfraCloudName }}"
- name: debug
debug:
msg: "{{ item.router:external }}"
with_items: "{{ openstack_networks }}"
我有一个错误:
TASK [debug] ******************************************
fatal: [localhost]: FAILED! => {"msg": "template error while templating string: expected token 'end of print statement', got ':'. String: {{ item.router:external }}"}
当我尝试通过以下方式在jija2模板中对其进行测试时:
Networks
========
{% for n in openstack_networks %}
# {{ n.name }}
{% if n.router:external %}
{{ n.name }} is an external network.
{% endif %}
{% endfor %}
我也有一个错误:
fatal: [localhost]: FAILED! => {"changed": false, "msg": "AnsibleError: template error while templating string: expected token 'end of statement block', got 'external'. String: Networks\n========\n\n{% for n in openstack_networks %}\n# {{ n.name }}\n\n{% if n.router:external %}\n{{ n.name }} is an external network.\n{% endif %}\n\n{% endfor %}\n"}
那么,有没有一种方法可以对变量名中的“:”进行转义?
答案 0 :(得分:4)
请记住,在Jinja中有两种用于访问字典键的语法。您可以这样写:
variable.key
或者您也可以这样:
variable['key']
由于键的第二种形式是带引号的字符串,它可以包含在标识符中无效的字符。所以你想要:
- name: debug
debug:
msg: "{{ item['router:external'] }}"
with_items: "{{ openstack_networks }}"