dictionary - 在字典中搜索和替换部分匹配项

标签 dictionary ansible

我正在尝试根据另一个字典中的值替换字典中的一些变量,它在完全匹配时工作得很好,但只匹配前几个单词就足够了。

  - debug:
      msg: "{{OS_short}}"
    loop: "{{store_os}}"
    vars:
      _dict: "{{ OS|dict2items }}"
      query: "[?contains(value, '{{ item.os_full }}')].key"
      OS_short: "{{ _dict|json_query(query) | join ('\n')}}"
    when: item.inventory.os_full is defined

要匹配的字典:

OS:
  ios:
    - IOS
    - ios
  nxos:
    - NX-OS
    - nx-os
    - Cisco NX-OS(tm)
    #- Cisco NX-OS(tm) nxos.bla bla bla

我尝试同时使用“contains”和“starts_with”,但使用 starts_with 我得到的是 "expected one of: ['string'], received:\"array\""}"

使用包含我只得到一个空答案

ok: [localhost] => (item={'os_full': 'Cisco NX-OS(tm) nxos.x.x.x.x.bin, Software (nxos), Version x.y(z), RELEASE SOFTWARE Copyright (c) 2002-2019 by Cisco Systems, Inc. Compiled 3/5/2019 12:00:00'}) => {
    "msg": ""
}

最佳答案

循环产品并搜索连接的模式。所有匹配项都将添加到新列表中。例如,给定删节数据

    store_os:
      - inventory:
          os_full: 'Cisco NX-OS(tm) nxos.x.x.x.x.bin, ...'

下面的任务

    - set_fact:
        store_os_short: "{{ store_os_short|d([]) +
                            [{'inventory': item.0.inventory|
                                           combine({'os_short': item.1.key})}] }}"
      with_nested:
        - "{{ store_os }}"
        - "{{ OS|dict2items }}"
      when: item.0.inventory.os_full is search(item.1.value|join('|'))

给予

  store_os_short:
  - inventory:
      os_full: Cisco NX-OS(tm) nxos.x.x.x.x.bin, ...
      os_short: nxos

关于dictionary - 在字典中搜索和替换部分匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69798373/

相关文章:

ansible - 最后修改的文件只移动了ansible?

c# - OrderedDictionary 和字典

c# - 从字典中删除最旧的项目

swift - 如何从 String 和 String 初始化字典?

Vagrant 起来 : bad interpreter: No such file or directory

python - Ansible 将变量写入 YAML 文件

Ansible:如何通过 Ansible 获取服务状态?

Java 字典迭代器类型问题

javascript - 遍历大对象也返回空值

kubernetes - 如何在不使用引号的情况下使用 k8s Ansible 模块?