gpt4 book ai didi

ansible - 如何使用 Ansible 或 Jinja2 转义变量名中的冒号 (":")?

转载 作者:行者123 更新时间:2023-12-02 15:33:11 25 4
gpt4 key购买 nike

我使用 Ansible 模块获取 Openstack 网络信息 os_networks_facts .

该模块返回 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"}

那么,有没有办法转义变量名中的“:”呢?

最佳答案

请记住,在 Jinja 中有两种访问字典键的语法。你可以这样写:

variable.key

或者你可以这样写:

variable['key']

因为在第二种形式中,键是带引号的字符串,因此它可以包含在标识符中无效的字符。所以你想要:

    - name: debug
debug:
msg: "{{ item['router:external'] }}"
with_items: "{{ openstack_networks }}"

关于ansible - 如何使用 Ansible 或 Jinja2 转义变量名中的冒号 (":")?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56129637/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com