Write a script that sends a Slack alert when a Kubernetes deployment has unavailable replicas, using the official client.
AdvancedHands-onPython for DevOps
Answer
import os
import requests
from kubernetes import client, config
try:
config.load_incluster_config() # running inside a pod
except config.ConfigException:
config.load_kube_config() # local ~/.kube/config
apps = client.AppsV1Api()
problems = []
for d in apps.list_deployment_for_all_namespaces().items:
want = d.spec.replicas or 0
ready = d.status.available_replicas or 0
if ready < want:
problems.append(f"{d.metadata.namespace}/{d.metadata.name}: {ready}/{want}")
if problems:
requests.post(os.environ["SLACK_WEBHOOK"],
json={"text": "Degraded deployments:\n" + "\n".join(problems)},
timeout=5)
Key trick → Try in-cluster config first, then fall back to kubeconfig, so the same script runs as a CronJob and on your laptop. Status fields are None (not 0) when no replica is available.
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