Write a script that validates all YAML files in a repo and exits non-zero on any error (for CI).
IntermediateHands-onPython for DevOps
Answer
import pathlib
import sys
import yaml
bad = 0
for path in pathlib.Path(".").rglob("*.y*ml"):
if ".git" in path.parts:
continue
try:
list(yaml.safe_load_all(path.read_text()))
except yaml.YAMLError as e:
print(f"{path}: {e}")
bad += 1
sys.exit(1 if bad else 0)
Key trick → safe_load_all returns a lazy generator, so wrap it in list() to force every document to be parsed. The exit code is what fails the CI step.
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