Write a script that reads a JSON file of services and checks each one's health endpoint concurrently.
IntermediateHands-onPython for DevOps
Answer
import json
from concurrent.futures import ThreadPoolExecutor, as_completed
import requests
with open("services.json") as f:
services = json.load(f) # [{"name": "api", "url": "https://.../health"}, ...]
def check(svc):
try:
r = requests.get(svc["url"], timeout=5)
return svc["name"], r.status_code, r.elapsed.total_seconds()
except requests.RequestException as e:
return svc["name"], "DOWN", str(e)[:60]
with ThreadPoolExecutor(max_workers=20) as pool:
for fut in as_completed(pool.submit(check, s) for s in services):
print(*fut.result())
Key trick → Health checks are I/O-bound, so threads give a big speed-up despite the GIL. as_completed prints results as they arrive instead of in submit order.
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