Zeinab Abbasimazar
Zeinab Abbasimazar

Reputation: 10469

edit linux telegraf.conf with python

I am using telegraf as a measuring/monitoring tool in my tests. I need to edit telegraf configurations automatically; since all tests are being executed automatically.

Currently I am using re for configuring it; this is the process:

  1. Read the whole file content.
  2. Use regex to find and edit the required plugin/property.
  3. Write the whole changed content to the file.

But I'm searching for a library, if exists, like ConfigParser or reconfigure to handle the configurations as an object not content.

I tried ConfigParser.ConfigParser, ConfigParser.RawConfigParser and ConfigParser.SafeConfigParser; all return:

ConfigParser.ParsingError: File contains parsing errors: /etc/telegraf/telegraf.conf

reconfigure library has specific configuration classes, each belongs to a special type of linux configs (e.g. FSTabConfig, ResolvConfig and some other types), but it doesn't contain a class for telegraf configs.

Does anyone have an option in mind?

EDIT 1:

I tried configobj library (as @KevinC suggested), but it loads nothing:

>>> import configobj
>>> c = configobj.ConfigObj('/home/zeinab/Desktop/config-modification/telegraf.conf', list_values=False)
>>> c
ConfigObj({})

Using list_values=True returns the same results.

Upvotes: 2

Views: 865

Answers (2)

UpperM
UpperM

Reputation: 11

You can use toml

Configuration file

[[inputs.ping]]
  ## Hosts to send ping packets to.
  urls = ["example.org"]
  method = "exec"

Usage

import toml
conf = (toml.load("/etc/telegraf/telegraf.conf"))
conf.get("inputs")

Output

{'ping': [{'urls': ['example.org'], 'method': 'exec'}]}

Upvotes: 1

Kevin C
Kevin C

Reputation: 1

You can use configobj, but you have to specify "list_values"=False

c = configobj.ConfigObj('/etc/telegraf/telegraf.conf', list_values=False)

Upvotes: 0

Related Questions