如何在 Ansible 中访问包含连字符的变量名称

Rab*_*bin 4 yaml ansible

我有一个简单的 vlan 配置文件,我喜欢让密钥与 JunOS 语法匹配(这样我可以根据需要将它们作为聚合传递),所以我使用vlan-id像此示例变量文件一样的密钥。

# vlans.yaml
vlans:
    - name: general
      description: "General"
      vlan-id: 100
    - name: hotline
      description: "Accounting"
      vlan-id: 110
Run Code Online (Sandbox Code Playgroud)

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

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

Run Code Online (Sandbox Code Playgroud)
"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'vlan'
Run Code Online (Sandbox Code Playgroud)

如果我直接输出该项目,我可以看到密钥

    - debug:
        msg: "{{ item }}"
      loop: "{{ vlans }}
Run Code Online (Sandbox Code Playgroud)
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
    }
}
Run Code Online (Sandbox Code Playgroud)

有什么想法如何解决这个问题吗?

Vla*_*tka 5

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

        msg: "{{ item['vlan-id'] }}"
Run Code Online (Sandbox Code Playgroud)

引用自:Ansible 允许变量使用点表示法和数组表示法。我应该使用哪种符号?

如果变量包含点 (.)、冒号 (:) 或破折号 (-),如果键以两个下划线开头和结尾,或者键使用任何已知的公共属性,则使用数组表示法会更安全


问:“这不是变量,而是关键。”

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

测绘。映射节点的内容是一组无序的键:值节点对,限制是每个键都是唯一的YAML 对节点没有进一步的限制。特别是,键可以是任意节点,同一节点可以用作多个键:值对的值,并且映射甚至可以将其自身包含为键或值(直接或间接)。