如何合并并去重Ansible中metrics_config变量的重复配置项
合并Prometheus风格配置中重复的default条目解决方案
核心实现思路
通过Jinja2模板逻辑将configs列表按name字段分组,对同一分组内的配置条目进行深度合并:列表类型字段(如scrape_configs)做列表拼接,非列表字段保留存在的唯一值(比如仅在其中一个条目中存在的remote_write配置)。
Ansible具体实现代码
- name: 合并重复的default配置条目 set_fact: merged_metrics_config: >- {% set grouped_configs = metrics_config.configs | groupby('name') %} {% set merged_list = [] %} {% for config_name, items in grouped_configs %} {% set combined_item = {} %} {% for item in items %} {% for key, val in item.items() %} {% if key in combined_item %} {% if combined_item[key] is iterable and combined_item[key] is not string %} {% do combined_item.update({ key: combined_item[key] + val }) %} {% endif %} {% else %} {% do combined_item.update({ key: val }) %} {% endif %} {% endfor %} {% endfor %} {% do merged_list.append(combined_item) %} {% endfor %} {{ metrics_config | combine({ 'configs': merged_list }, recursive=True) }}
代码说明
- 分组:使用
groupby('name')将所有配置条目按name字段归类,两个default条目会被分到同一组 - 合并条目:遍历每个分组,初始化空字典存储合并结果;对组内每个条目逐键处理:
- 若键已存在且对应值为可迭代非字符串类型(如列表),则拼接两个列表
- 若键不存在,则直接赋值
- 替换原配置:用
combine过滤器将原配置中的configs替换为合并后的列表,保留其他原有配置
示例验证
假设原配置为:
metrics_config: configs: - name: default remote_write: - url: "http://remote-write.example.com" scrape_configs: - job_name: job1 static_configs: - targets: ["localhost:9090"] - name: default scrape_configs: - job_name: job2 static_configs: - targets: ["localhost:8080"] - name: other scrape_configs: - job_name: job3 static_configs: - targets: ["localhost:7070"]
合并后merged_metrics_config的configs部分会变为:
configs: - name: default remote_write: - url: "http://remote-write.example.com" scrape_configs: - job_name: job1 static_configs: - targets: ["localhost:9090"] - job_name: job2 static_configs: - targets: ["localhost:8080"] - name: other scrape_configs: - job_name: job3 static_configs: - targets: ["localhost:7070"]
内容的提问来源于stack exchange,提问作者bjo0
相关产品推荐
相关产品推荐

