Python script to automate apt update and send statistics to InfluxDB / Telegraf

I wanted to get an overview how many updates my servers are currently missing. I wrote a Python script to update the APT-cache and write the results into InfluxDB via API_v2.

Since I have on all my servers Telegraf running, I am using this config also for the apt-status upload script.

My Telegraf config is in a local config file in the /etc/telegraf/telegraf.d/ directory. I specify there global tags and the outputs.influxdb_v2 API endpoint:


[global_tags]
server = 'service.cs'
os = 'Linux'

[[outputs.influxdb_v2]]
urls = ["https://your.influxdb.url"]
token = "APIv2_TOKEN"
organization = "yourOrg"
bucket = "yourTelegrafBucket"

I have placed the script apt-updates2telegraf.py in /usr/local/sbin/ (requires python3-apt and python3-toml: apt install python3-apt python3-toml).

If you add a cronjob the script will be executed regularily (I have it running once a day in the morning:

12 6 * * * /usr/local/sbin/apt-updates2telegraf.py

Additionally I have added a DPKG hook, whenever something gets installed (e.g. updates) that the script is triggered. Add the following line to the new fileĀ  /etc/apt/apt.conf.d/99postInst:

DPkg::Post-Invoke {"/usr/local/sbin/apt-updates2telegraf.py || true";};

In Grafana I have a Dashboard showing all the last apt status lines:

import "strings"
from(bucket: "telegraf")
|> range(start: -1000y)
|> filter(fn: (r) => r["_measurement"] == "linuxUpdates" and r["_field"] == "details")
|> group(columns: ["server"])
|> drop(columns: ["_start", "_stop", "_measurement", "_field", "host", "os"])
|> last()
|> map(fn: (r) => ({r with _value: strings.replaceAll(v: r._value, t: "\\n", u: "\n")}))
|> sort(columns: ["server"])

Leave a Reply

Your email address will not be published. Required fields are marked *