我是Python的新手,现在学习python,我拥有Prometheus配置文件,现在需要在一个节点中添加一些字段和值。在rt模式下加载时,它将变为ordereddict格式,并且无法进入节点,无法添加字段
# my global config
global:
scrape_interval: 60s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
evaluation_interval: 60s # Evaluate rules every 15 seconds. The default is every 1 minute.
# scrape_timeout is set to the global default (10s).
# Alertmanager configuration
alerting:
alertmanagers:
- scheme: http
path_prefix: /
static_configs:
- targets:
- 127.0.0.1:9093
# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
- "first_rules.yml"
- "second_rules.yml"
# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
- job_name: 'cassandra'
static_configs:
- targets: ['localhost:18080']
- job_name: 'machine'
static_configs:
- targets: ['localhost:9100']
在scrape_configs下,对于job_name:'machine',我需要在使用Ruamel yaml python时跟踪数据,
- job_name: 'machine'
honor_labels: true
static_configs:
- targets: ['localhost:9100']
labels:
ip: 'x.x.x.x
下面我尝试但出现错误的代码
import sys
from ruamel.yaml import YAML
from collections import OrderedDict
from pathlib import Path
yaml=YAML()
yaml.preserve_quotes = True
yaml.explicit_start = True
yaml.default_flow_style = False
with open('D:\***\prometheus.yml') as fp:
data = yaml.load(fp)
print("data = %s" %(data))
for elem in data:
if elem['scrape_configs']['static_configs']['job_name']== 'machine':
elem['honor_labels']='true'
break # no need to iterate further
yaml.dump(data, sys.stdout)
错误是:
if elem['scrape_configs']['static_configs']['job_name']== 'machine':
TypeError: string indices must be integers
Process finished with exit code 1
如何使用python向现有节点添加新条目?
我在此question中遵循了安东的回答,但仍然无法获得
for elem in data:
print('elem', elem)
if elem['job_name'] == 'machine':
print('elem->honor_labels', elem['honor_labels'])
elem['honor_labels'] = ['true']
错误堆栈:
elem global
File "D:/***/.idea/editYaml.py", line 19, in <module>
if elem['job_name'] == 'machine':
TypeError: string indices must be integers
如果Yaml中有更多节点,如何访问job_name?请引导我。