首页 > 解决方案 > ansible的dict键中是否允许使用破折号?

问题描述

我对剧本有疑问,想知道问题是否在于我使用的字典中的某些键名中有破折号。Ansible 不清楚这是否允许。

我正在使用 nmstatectl 获取描述 RHEL8 主机上当前网络配置的 json。json 输出使用带有破折号的键,我想按原样使用输出。

剧本:

- name: check static route using nmstatectl
  hosts: rhv


  tasks:
  - name: collect network config
    command:
      cmd: nmstatectl show --json
    register: nmstate
    changed_when: false

  - name: set fact with block storage route config
    set_fact:
      block_storage_route: "{{ nmstate.stdout | from_json | json_query(query) }}"
    vars:
      query: "routes.config[?destination == '{{ block_storage_cidr }}' ]"

  - debug:
      var: block_storage_route

  - debug:
      var: block_storage_route[0].destination    

  - debug:
      var: block_storage_route[0].table-id

输出:

...
TASK [debug] ************************************************************************************************************************
ok: [one.example.com] => {
    "block_storage_route": [
        {
            "destination": "10.201.142.0/24",
            "metric": 301,
            "next-hop-address": "10.123.231.161",
            "next-hop-interface": "bond0.1161",
            "table-id": 0
        }
    ]
}

TASK [debug] ************************************************************************************************************************
ok: [one.example.com] => {
    "block_storage_route[0].destination": "10.201.142.0/24"
}

TASK [debug] ************************************************************************************************************************
ok: [one.example.com] => {
    "block_storage_route[0].table-id": "VARIABLE IS NOT DEFINED!"
}

如您所见,我收到“变量未定义”错误。即使存在密钥“table-id”......为什么?

标签: ansible

解决方案


问:Ansible 中的字典键中是否允许使用破折号?

答:是的。他们是。实际上,YAML 中对密钥没有任何限制。引用映射(又名 Python 字典)

“映射节点的内容是一组无序的键:值节点对,限制每个键都是唯一的。YAML 对节点没有进一步的限制。特别是,键可以是任意节点,...... "

当键的名称不符合 Ansible 时,使用括号表示法而不是点表示法创建有效的变量名

    - debug:
        var: block_storage_route[0]['table-id']

推荐阅读