Install PyYAML and use yaml.safe_load() and yaml.dump() to read, write, and update YAML config files ā the format used by Docker Compose, Kubernetes manifests, and GitHub Actions workflows. Learn why yaml.safe_load() is always required and why bare yaml.load() is a security risk you must avoid.
Create the lesson-302 directory, activate the virtual environment, install PyYAML, and write a `deploy.yaml` file that demonstrates YAML anchors and merge keys. This is the YAML equivalent of the `deploy.json` from lesson 301.
mkdir -p ~/devops-python/lesson-302cd ~/devops-python/lesson-302source ~/devops-python/lesson-101/devops-env/bin/activatepip install "PyYAML>=6,<7"pip show PyYAML | grep -E 'Name|Version'app_name: devops-app
version: "1.4.0"
# YAML anchor: define a reusable defaults block
defaults: &defaults
port: 8080
debug: false
health_check: /health
replicas: 2
environments:
dev:
<<: *defaults
host: dev.example.internal
debug: true
replicas: 1
staging:
<<: *defaults
host: staging.example.internal
prod:
<<: *defaults
host: app.example.com
port: 443
replicas: 5
notify_on_failure:
- ops@example.com
- platform@example.compython3 -c "import yaml; data = yaml.safe_load(open('deploy.yaml')); print(type(data)); print(list(data.keys()))"PyYAML is not part of the Python standard library, so it must be installed with pip.
The version pin PyYAML>=6,<7 locks to the current stable series with improved security defaults.
YAML anchors (&defaults) define a reusable block that can be referenced elsewhere in the same file.
The merge key (<<: *defaults) copies every key from the anchored block into the current mapping, and local keys override the merged ones ā dev overrides debug: true and replicas: 1 while inheriting port, health_check, and the default replicas from &defaults.
PyYAML's yaml.safe_load() resolves anchors and merge keys automatically, so the returned Python dict contains fully expanded values with no trace of anchor syntax.
pip outputs Name: PyYAML and Version: 6.x.
The one-liner prints <class 'dict'> and ['app_name', 'version', 'defaults', 'environments', 'notify_on_failure'] ā confirming the file parsed and the top-level keys including defaults are accessible.