Python 替换从alertmanager yml加载的字典动态列表中的值?
这个问题非常具体,我成功地做到了我想要的,但是它非常具体,对于我的用例来说可能很难看,所以我很好奇它是否更通用和/或更聪明 我需要编辑存储在yml文件中的prometheus alertmanager路由 在我的用例中,我的路由是提取的:Python 替换从alertmanager yml加载的字典动态列表中的值?,python,list,replace,yaml,prometheus-alertmanager,Python,List,Replace,Yaml,Prometheus Alertmanager,这个问题非常具体,我成功地做到了我想要的,但是它非常具体,对于我的用例来说可能很难看,所以我很好奇它是否更通用和/或更聪明 我需要编辑存储在yml文件中的prometheus alertmanager路由 在我的用例中,我的路由是提取的: route: routes: - match: product: my_product stage: prod routes: - continue: true mat
route:
routes:
- match:
product: my_product
stage: prod
routes:
- continue: true
match_re:
severity: (info|warning|critical)
receiver: mattermost
- continue: true
match_re:
severity: (warning|critical)
receiver: mail_infra
- match:
severity: critical
receiver: sms_voidandnany
我需要编辑接收者短信,接收者是否依赖谷歌日历
这是我的初稿:
将打开的'alertmanager.yml'作为f:
数据=yaml.safe\u载荷f
routes=数据['route']['routes']
对于路线中的项目:
如果item.get'match'。get'product'='my_product'和item.get'match'。get'stage'='prod':
对于item.get'routes'中的子项:
如果子项中的“匹配”:
如果子项.get'match'。get'severity'=='critical':
子项['receiver']=“sms\u其他用户”
使用openalertmanager2.yaml,w作为f:
yaml.dumpdata,f
3个如果,2个循环,即使是我,不是python专家,也不是全职开发人员,我认为这很难看
你有没有看到一个更好的方法,一个更像Python的方法来达到这个目的
蛋糕上的樱桃,你认为有没有一个简单的方法可以让替代品变得普通?
路由结构是动态的,可以进行路由匹配、路由匹配等。。。
递归函数?您的查询在这里似乎更具体,因此我们无法重写太多。但这是我的尝试
import yaml
with open('alertmanager.yml') as f:
data = yaml.safe_load(f)
subitems = [subitem for item in data['route']['routes'] for subitem in item.get('routes') if item.get('match').get('product') == 'my_product' and item.get('match').get('stage') == 'prod']
for subitem in subitems:
if 'match' in subitem and subitem.get('match').get('severity') == 'critical':
subitem['receiver'] = 'sms_another_user'
with open("alertmanager2.yaml", "w") as f:
yaml.dump(data, f)
该解决方案实现了一个用于附加值的API,您可以对其进行调整,使其也能够替换值。