Write a minimal Prometheus exporter in Python that exposes a custom metric.
AdvancedHands-onPython for DevOps
Answer
import time
import requests
from prometheus_client import Gauge, start_http_server
QUEUE_DEPTH = Gauge("app_queue_depth", "Messages waiting in queue", ["queue"])
def collect():
data = requests.get("http://localhost:15672/api/queues",
auth=("guest", "guest"), timeout=5).json()
for q in data:
QUEUE_DEPTH.labels(queue=q["name"]).set(q.get("messages", 0))
if __name__ == "__main__":
start_http_server(9100) # serves /metrics
while True:
collect()
time.sleep(15)
Key trick → Use a Gauge for values that go up and down and a Counter only for monotonic totals. Keep label values bounded (queue names, not message IDs) to avoid a cardinality explosion.
More on Python for DevOps
Write a Python script using boto3 that lists all running EC2 instances with their Name tag.BeginnerWrite a script that finds unattached EBS volumes and deletes them (with a dry-run flag).IntermediateCall a REST API with `requests`, handle timeouts and non-2xx responses properly.BeginnerAdd retry with exponential backoff to HTTP calls without writing the loop yourself.IntermediateWrite your own retry decorator with exponential backoff and jitter.AdvancedParse a YAML file and print every container image in a multi-document Kubernetes manifest.Intermediate