如何比较 2 个值并根据结果采取行动

How to compare 2 values and take an action based on the result in ansible

我想根据一个键比较 2 个值并相应地采取行动。 下面是输入 json,在此我想比较 gpmgmt>L_123456> 101gpmgmtcurrent>L_123456 > 101。在这种情况下,两个值都是 101,因此不需要任何操作。但是第二个 JSON 的值是 101 & 103 因此需要采取行动。我如何遍历这些值并在存在差异时采取措施。

输入JSON(gpidmgmt):

{
    "changed": false,
    "msg": "All items completed",
    "results": [
        {
            "ansible_facts": {
                "gpmgmt": [
                    {
                        "L_123456": [
                            "101"
                        ]
                    }
                ],
                "gpmgmtcurrent": {
                    "L_123456": [
                        "101"
                    ]
                }
            },
            "ansible_loop_var": "item",
            "changed": false,
            "failed": false,
            "item": "L_123456"
        },
        {
            "ansible_facts": {
                "gpmgmt": [
                    {
                        "N_1188779": [
                            "103"
                        ]
                    }
                ],
                "gpmgmtcurrent": {
                    "N_1188779": [
                        "101"
                    ]
                }
            },
            "ansible_loop_var": "item",
            "changed": false,
            "failed": false,
            "item": "N_1188779"
        }
    ],
    "skipped": false
}

代码:取出gpmgmt & gpmgmtcurrent的值:

- name: GP Info
      set_fact:
         gplisttest: "{{gpidmgmt | json_query(gpmquerytest) }}"
         gplisttest1: "{{gpidmgmt | json_query(gpmquerytest1) }}"
      vars:
        gpmquerytest:  "results[*].ansible_facts.gpmgmt[].{{ item }}"
        gpmquerytest1:  "results[*].ansible_facts.gpmgmtcurrent.{{ item }}"
      with_items: "{{ gpnet }}"
      register: gpidmgmttest

gpnet:

[
    [
        "L_662029145223476760",
        "N_782500435255632820"
    ]
]

迭代子元素,因为 gpmgmt 是一个列表。从 gpmgmtcurrent 获取密钥并比较列表,例如

    - debug:
        msg: "{{ _key }}: {{ _gpmgmt }} is NOT equal to {{ _gpmgmt_current }}"
      with_subelements:
        - "{{ gpidmgmt.results|map(attribute='ansible_facts')|list }}"
        - gpmgmt
      vars:
        _key: "{{ item.0.gpmgmtcurrent.keys()|first }}"
        _gpmgmt: "{{ item.1[_key] }}"
        _gpmgmt_current: "{{ item.0.gpmgmtcurrent[_key] }}"
      when: _gpmgmt|difference(_gpmgmt_current)|length > 0

给予

  msg: 'N_1188779: [''103''] is NOT equal to [''101'']'