Run a shell command from Python, capture output, and fail properly on error.
IntermediateHands-onPython for DevOps
Answer
import subprocess
result = subprocess.run(
["kubectl", "get", "nodes", "-o", "name"],
capture_output=True, text=True, check=True, timeout=30,
)
nodes = result.stdout.split()
print(f"{len(nodes)} nodes")
On failure, check=True raises CalledProcessError with .returncode and .stderr.
Key trick → Pass a list and avoid shell=True. Then no shell parses your input, which removes command injection when arguments come from users.
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