Parse an environment-specific config: load base YAML and override with environment values.
IntermediateHands-onPython for DevOps
Answer
import os
import yaml
def deep_merge(base, override):
for k, v in override.items():
if isinstance(v, dict) and isinstance(base.get(k), dict):
deep_merge(base[k], v)
else:
base[k] = v
return base
env = os.environ.get("APP_ENV", "dev")
with open("config/base.yaml") as f:
cfg = yaml.safe_load(f)
with open(f"config/{env}.yaml") as f:
cfg = deep_merge(cfg, yaml.safe_load(f) or {})
cfg["db"]["password"] = os.environ["DB_PASSWORD"] # secrets from env, not files
print(cfg)
Key trick → A shallow dict.update replaces whole nested sections. A recursive merge overrides only the keys that differ.
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