【问题标题】:how can I update a dictionary in Ansible如何在 Ansible 中更新字典
【发布时间】:2020-12-14 02:35:45
【问题描述】:

我正在 ansible 中创建一个简单的字典,就是这个:

"types_dict": {
    "name1": "Ethernet",
    "name2": "Ethernet",
    "name3": "Software-Pseudo",
    "name4": "Ethernet",
    "name5": "Software-Pseudo",
    "name6": "Ethernet" }

我的目标是循环字典并用“虚拟”替换一些特定值,即“软件伪”。我尝试了以下方法:

- set_fact:
    types_dict: "{{ types_dict | combine(new_item, recursive=true) }}"
  vars:
    new_item: "{ '{{ item.key }}': { 'type': 'Virtual' } }"
  with_dict: "{{ types_dict }}"

但这里的问题是这个更新了我字典中的所有值,这是我根本不想要的。我还通过添加“when”语句尝试了以下操作,但它也不起作用:

- set_fact:
    types_dict: "{{ types_dict | combine(new_item, recursive=true) }}"
  vars:
    new_item: "{ '{{ item.key }}': { 'type': 'Virtual' } }"
    when: "{{ item.value }} == Software-Pseudo"
  with_dict: "{{ types_dict }}"

我还尝试了when: "{{ item.value }} == 'Software-Pseudo'" 和许多其他类似的东西。

关于如何解决这个问题的任何想法?

【问题讨论】:

    标签: loops dictionary ansible


    【解决方案1】:

    任务完成任务。如果需要,可以将项目添加到列表中types_new

        - set_fact:
            types_dict: "{{ types_dict|combine({item.0.key: item.1.replace}) }}"
          with_nested:
            - "{{ types_dict|dict2items }}"
            - "{{ types_new }}"
          when: item.0.value is search(item.1.regex)
          vars:
            types_new:
              - {regex: 'Software-Pseudo', replace: 'Virtual'}
        - debug:
            var: types_dict
    

    给予

      types_dict:
        name1: Ethernet
        name2: Ethernet
        name3: Virtual
        name4: Ethernet
        name5: Virtual
        name6: Ethernet
    

    问:“我的字典中有像“name2”这样的空值:null,我可以以任何方式处理它,以便用其他值(另一个值)替换它。” p>

    答:在types_new 中添加一行。例如

          vars:
            types_new:
              - {regex: 'Software-Pseudo', replace: 'Virtual'}
              - {regex: 'None', replace: 'another_value'}
    

    请参阅下面的任务,nullNone'None' 是如何被 search 测试处理的

        - debug:
            msg: "{{ item.key }} {{ item.value is search('None') }}"
          loop: "{{ my_vars|dict2items }}"
          vars:
            my_vars:
              var1: abc
              var2:
              var3: None
              var4: 'None'
    

    给予

      msg: var1 False
      msg: var2 True
      msg: var3 True
      msg: var4 True
    

    【讨论】:

    • 这很完美!它比我尝试的要复杂一些,但我现在明白其中的逻辑了!!!根据我在文档中找到的内容,我无法达到这一点!最后一个问题,如果我的字典中有 "name2": null 之类的空值,我可以以任何方式处理它以便用 sth else (another value) 替换它吗? @VladimirBotka
    • 实际上我可以处理它,如果我写而不是- {regex: 'null', replace: 'Virtual'} - {regex: 'None', replace: 'Virtual'} !!!!
    • 对。 None 是 YAML 等价于 Python null
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多