Parse a YAML file and print every container image in a multi-document Kubernetes manifest.
IntermediateHands-onPython for DevOps
Answer
import sys
import yaml
with open(sys.argv[1]) as f:
for doc in yaml.safe_load_all(f):
if not doc:
continue
spec = doc.get("spec", {})
pod = spec.get("template", {}).get("spec", spec) # Deployment or bare Pod
for c in pod.get("containers", []) + pod.get("initContainers", []):
print(f"{doc['kind']}/{doc['metadata']['name']}: {c['image']}")
Key trick → Use safe_load_all for files separated by ---, and safe_load never load, because plain yaml.load without a safe Loader can construct arbitrary Python objects.
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.AdvancedRun a shell command from Python, capture output, and fail properly on error.Intermediate