I'm new to Python, learning python now, I have Prometheus configuration file, need to add few fields and values in one node for now. when loading in rt mode, it goes to ordereddict format and unable to get into the nodes, to add fields
# 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']
under scrape_configs, for job_name: 'machine' I need to following data in using Ruamel yaml python,
- job_name: 'machine'
honor_labels: true
static_configs:
- targets: ['localhost:9100']
labels:
ip: 'x.x.x.x
below code I tried to but getting error
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)
error is:
if elem['scrape_configs']['static_configs']['job_name']== 'machine':
TypeError: string indices must be integers
Process finished with exit code 1
How can I add a new entry to existing node using python?
I followed the Anton's answer in this question but still unable to get the
for elem in data:
print('elem', elem)
if elem['job_name'] == 'machine':
print('elem->honor_labels', elem['honor_labels'])
elem['honor_labels'] = ['true']
error stack:
elem global
File "D:/***/.idea/editYaml.py", line 19, in <module>
if elem['job_name'] == 'machine':
TypeError: string indices must be integers
how to access job_name if we have more nodes in yaml? please guide me.