问:如何比较具有相同键的两个字典?
答:给定简化的测试数据
s:
flag1: true
Flag3: true
flag2: false
t:
flag3: true
flag1: false
flag2: false
- debug:
msg: The dictionaries are identical
when: s == t
- debug:
msg: The dictionaries are different
when: s != t
提供
msg: The dictionaries are different
s_keys: "{{ s.keys()|list }}"
t_keys: "{{ t.keys()|list }}"
diff_keys: "{{ s_keys|symmetric_difference(t_keys) }}"
测试 symmetric_difference 的长度。
- debug:
msg: "The difference in the keys: {{ diff_keys }}"
when: diff_keys|length != 0
提供
msg: 'The difference in the keys: [''Flag3'', ''flag3'']'
s:
flag1: true
flag3: true
flag2: false
t:
flag3: true
flag1: false
flag2: false
- debug:
msg: "{{ item }} is {{ (s[item] == t[item])|ternary('OK', 'KO') }}"
loop: "{{ s.keys()|sort }}"
when: diff_keys|length == 0
提供
msg: flag1 is KO
msg: flag2 is OK
msg: flag3 is OK
问:如何突出它们之间的差异?
答:创建一个仅包含不同值的字典,例如:
- set_fact:
diff_vals: "{{ diff_vals|d({})|combine({item: s[item]}) }}"
loop: "{{ s.keys()|sort }}"
when:
- diff_keys|length == 0
- s[item] != t[item]
- debug:
var: diff_vals
提供
diff_vals:
flag1: true
Example of a complete playbook
- hosts: localhost
gather_facts: false
vars:
s:
flag1: true
flag3: true
flag2: false
t:
flag3: true
flag1: false
flag2: false
s_keys: "{{ s.keys()|list }}"
t_keys: "{{ t.keys()|list }}"
diff_keys: "{{ s_keys|symmetric_difference(t_keys) }}"
tasks:
- debug:
msg: The dictionaries are identical
when: s == t
- debug:
msg: The dictionaries are different
when: s != t
- debug:
msg: "The difference in the keys: {{ diff_keys }}"
when: diff_keys|length != 0
- debug:
msg: "{{ item }} is {{ (s[item] == t[item])|ternary('OK', 'KO') }}"
loop: "{{ s.keys()|sort }}"
when: diff_keys|length == 0
- set_fact:
diff_vals: "{{ diff_vals|d({})|combine({item: s[item]}) }}"
loop: "{{ s.keys()|sort }}"
when:
- diff_keys|length == 0
- s[item] != t[item]
- debug:
var: diff_vals