【问题标题】:Ansible modify a delete value in nested dictionaryAnsible修改嵌套字典中的删除值
【发布时间】:2022-06-19 02:27:25
【问题描述】:

我想在嵌套字典中添加新值,旧值应该被删除。

这是我的 parse.json 文件。

{
    "class": "Service_HTTPS",
    "layer4": "tcp",
    "profileTCP": {
        "egress": {
            "use": "/Common/Shared/f5-tcp-wan"
        },
        "ingress": {
            "use": "/Common/Shared/f5-tcp-lan"
        }
    }
}

这是我的脚本,它将添加新值但也会保留旧值,我知道我正在使用 recursive=True 但如果没有此命令,我将丢失入口密钥。

这是我的脚本:

- set_fact:
        json_file: "{{ lookup('file', 'parse.json')   }}"
    

    - set_fact:
        json_file: "{{ json_file | combine( egress_modify, recursive=True) }}"
      when: json_file['profileTCP']['egress'] is defined
      vars: 
        egress_modify: "{{ json_file  | combine({ 'profileTCP': { 'egress': { 'bigip': '/Common/' + json_file['profileTCP']['egress']['use'].split('/')[-1] } }}) }}" 
        

    - name: debug
      debug:
          msg: "{{ json_file }}"

错误的结果

ok: [localhost] => {
    "msg": {
        "class": "Service_HTTPS",
        "layer4": "tcp",
        "profileTCP": {
            "egress": {
                "bigip": "/Common/f5-tcp-wan",
                "use": "/Common/Shared/f5-tcp-wan"
            },
            "ingress": {
                "use": "/Common/Shared/f5-tcp-lan"
            }
        }
    }
}

但我想要这个结果

ok: [localhost] => {
    "msg": {
        "class": "Service_HTTPS",
        "layer4": "tcp",
        "profileTCP": {
            "egress": {
                "bigip": "/Common/f5-tcp-wan",
            },
            "ingress": {
                "use": "/Common/Shared/f5-tcp-lan"
            }
        }
    }
}

【问题讨论】:

    标签: ansible


    【解决方案1】:

    dicts 在 ansible 中是“活的”,因此您可以继续执行“set_fact:, loop:”业务,也可以一次性完成所有操作:

        - set_fact:
            json_file: >-
              {%- set j = lookup('file', 'parse.json') | from_json -%}
              {%- set tcp_egress_use = j.profileTCP.egress.pop('use') -%}
              {%- set _ = j.profileTCP.egress.update({
                    'bigip': '/Common/' + tcp_egress_use.split('/')[-1]
                  }) -%}
              {{ j }}
    

    生产

        "json_file": {
          "class": "Service_HTTPS",
          "layer4": "tcp",
          "profileTCP": {
            "egress": {
              "bigip": "/Common/f5-tcp-wan"
            },
            "ingress": {
              "use": "/Common/Shared/f5-tcp-lan"
            }
          }
        }
    

    【讨论】:

      猜你喜欢
      • 2018-09-13
      • 1970-01-01
      • 2021-12-13
      • 2021-02-23
      • 2023-02-04
      • 1970-01-01
      • 1970-01-01
      • 2018-07-10
      • 2019-07-18
      相关资源
      最近更新 更多