Python's powerful SDKs allow you to automate infrastructure tasks that usually require CLI commands like docker run or kubectl apply.
1. Docker SDK for Python (docker)
The docker package allows you to communicate with the Docker daemon.
Basic Usage: List Running Containers
Action:
import docker
client = docker.from_env()
for container in client.containers.list():
print(f"ID: {container.short_id}, Name: {container.name}, Status: {container.status}")Result:
ID: a1b2c3d4, Name: redis_cache, Status: running
ID: f5e6d7c8, Name: nginx_proxy, Status: running2. Kubernetes Python Client (kubernetes)
The official Kubernetes Python client is used for automating tasks like scaling deployments or auditing pods.
Listing All Pods in a Namespace
Action:
from kubernetes import client, config
# Load local kubeconfig
config.load_kube_config()
v1 = client.CoreV1Api()
print("Listing pods in 'default' namespace:")
pods = v1.list_namespaced_pod(namespace="default")
for pod in pods.items:
print(f"Pod: {pod.metadata.name}, IP: {pod.status.pod_ip}")Result:
Listing pods in 'default' namespace:
Pod: web-server-v1-6789fb8c-x2jkl, IP: 10.244.1.42
Pod: database-master-0, IP: 10.244.1.123. DevOps Automation: Health Checks
A common use case is writing a script that checks if a Kubernetes Deployment has the correct number of ready replicas and restarts it if necessary.
Snippet:
apps_v1 = client.AppsV1Api()
deploy = apps_v1.read_namespaced_deployment(name="my-app", namespace="prod")
if deploy.status.ready_replicas < deploy.spec.replicas:
print("ALERT: Not all replicas are ready!")
# Notification or auto-remediation logic...4. Comparison: CLI vs. SDK
| Feature | CLI (bash) | SDK (python) |
|---|---|---|
| Speed | Fast for single tasks | Better for complex logic |
| Parsing | Requires jq / awk | Native objects/JSON |
| Error Handling | Exit codes | Try/Except blocks |
| Integration | Difficult to test | Easy unit testing |
Summary
- Use
docker-pyfor managing local or remote containers. - Use
kubernetes-python-clientfor sophisticated orchestration. - Prefer SDKs when your logic involves multi-step decision-making.