[英]How to compare and merge key values when there is a matching values in a ansible list
我有以下 output,我想比较列表中的tunnel
值,如果匹配,则必须合并相应custip
值。 我在堆栈溢出中遇到过几篇文章,但其中大多数都在比较两个列表,如果发现有任何共同点,则合并列表。 找不到帖子来比较单个列表中的键值并合并相应的其他键值。 我是 ansible 的新手,仍处于学习阶段,我真的很乐意为我指出正确的资源/示例/任何文档,以便我弄清楚或者是否提供很棒的解决方案。 谢谢
TASK [debug] *******************************************************************
ok: [localhost] => {
"msg": [
{
"custip": "192.168.10.0/24",
"tunnel": "tunnel.5"
},
{
"custip": "192.168.20.0/24",
"tunnel": "tunnel.5"
},
{
"custip": "1.1.1.1/32",
"tunnel": "tunnel.10"
},
{
"custip": "2.2.2.0/24",
"tunnel": "tunnel.11"
},
{
"custip": "3.3.3.0/24",
"tunnel": "tunnel.11"
}
]
}
如果tunnel
值匹配,则必须合并/合并custip
以低于 output
想要/想要的 output:
[
{
"custip": ["192.168.10.0/24","192.168.20.0/24"],
"tunnel": "tunnel.5"
},
{
"custip": ["1.1.1.1/32"],
"tunnel": "tunnel.10"
},
{
"custip": ["2.2.2.0/24",3.3.3.0/24],
"tunnel": "tunnel.11"
}
]
如果我们假设您的原始数据结构位于名为the_list
的 var 中,那么groupby
过滤器将执行您想要的操作,只需稍加按摩即可将其恢复为所需的形状
- debug:
msg: >-
{%- set results = [] -%}
{%- for k, v in the_list | groupby("tunnel") -%}
{%- set _ = results.append({
"tunnel": k,
"custip": v | map(attribute="custip") | list
}) -%}
{%- endfor -%}
{{ results }}
该map(attribute="custip")
是由于中间形状是
[
"tunnel.5",
[
{
"custip": "192.168.10.0/24",
"tunnel": "tunnel.5"
},
{
"custip": "192.168.20.0/24",
"tunnel": "tunnel.5"
}
]
]
所以我们需要进入grouper.list
并从中提取有趣的custip
元素
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.