替换从alertmanager yml加载的字典动态列表中的值?

2024-09-22 20:25:43 发布

您现在位置:Python中文网/ 问答频道 /正文

这个问题非常具体,我成功地做到了我想要的,但是它非常具体,对于我的用例来说可能很难看,所以我很好奇它是否更通用和/或更聪明

我需要编辑存储在yml文件(documentation here)中的prometheus alertmanager路由

在我的用例中,我的路由是(摘录):

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

我需要编辑收件人“sms_voidAndNay”(收件人取决于谷歌日历)

这是我的初稿:

with open('alertmanager.yml') as f:
    data = yaml.safe_load(f)
    routes=data['route']['routes']

    for item in routes:
        if item.get('match').get('product') == 'my_product' and item.get('match').get('stage') == 'prod':
            for subitem in item.get('routes'):
                if 'match' in subitem:
                    if subitem.get('match').get('severity') == 'critical':
                        subitem['receiver'] = 'sms_another_user'

with open("alertmanager2.yaml", "w") as f:
    yaml.dump(data, f)

3ifs,2个循环,即使是我,也不是python专家,也不是全职开发人员,我认为这很难看

你有没有看到一个更好的方法,一个更像Python的方法来达到这个目的

蛋糕上的樱桃,你认为有一个“简单”的方法使替换通用? 路由结构是动态的,可以进行路由匹配、路由匹配等。。。 递归函数


Tags: inyaml路由datagetifmatchproduct
1条回答
网友
1楼 · 发布于 2024-09-22 20:25:43

您的查询在这里似乎更具体,因此我们无法重写太多。但这是我的尝试

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)

相关问题 更多 >