gpt4 book ai didi

ansible - 如何访问 Ansible 中包含连字符的变量名

转载 作者:行者123 更新时间:2023-12-05 02:51:03 25 4
gpt4 key购买 nike

我有一个简单的 vlan 配置文件,我希望它具有与 JunOS 语法匹配的键(这样我可以在需要时将它们作为聚合传递),所以我使用 vlan-id 键像这个示例变量文件。

# vlans.yaml
vlans:
- name: general
description: "General"
vlan-id: 100
- name: hotline
description: "Accounting"
vlan-id: 110

但由于连字符,我无法访问 vlan-id key

    - debug:
msg: "{{ item.vlan-id }}"
loop: "{{ vlans }}"
tags: debug

"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'vlan'

如果我直接输出项目我可以看到 key

    - debug:
msg: "{{ item }}"
loop: "{{ vlans }}
ok: [SW02] => (item={'name': 'external', 'description': 'External', 'vlan-id': 209}) => {
"msg": {
"description": "External",
"name": "external",
"vlan-id": 209
}
}
ok: [SW01] => (item={'name': 'external', 'description': 'External', 'vlan-id': 209}) => {
"msg": {
"description": "External",
"name": "external",
"vlan-id": 209
}
}

有什么解决办法吗?

最佳答案

将属性放入方括号“[]”中,又名数组表示法。例如

        msg: "{{ item['vlan-id'] }}"

引自Ansible allows dot notation and array notation for variables. Which notation should I use?

If your variable contains dots (.), colons (:), or dashes (-), if a key begins and ends with two underscores, or if a key uses any of the known public attributes, it is safer to use the array notation.


Q: "This is not a variable, it's the key."

答:对。唯一的限制是 key 是唯一的。引自 YAML 1.2

Mapping. The content of a mapping node is an unordered set of key: value node pairs, with the restriction that each of the keys is unique. YAML places no further restrictions on the nodes. In particular, keys may be arbitrary nodes, the same node may be used as the value of several key: value pairs, and a mapping could even contain itself as a key or a value (directly or indirectly).

关于ansible - 如何访问 Ansible 中包含连字符的变量名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63437205/

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