YAML

chevron-rightMethodshashtag

yaml (PyYAML - YAML Parser)

pythonCopyEditimport yaml
Method
Description

yaml.safe_load()

Loads YAML into Python (safe, preferred)

yaml.load()

Loads YAML (use only with Loader arg)

yaml.dump()

Dumps Python object into YAML

yaml.safe_dump()

Dumps safely without tags or custom types

yaml.load_all()

Loads multiple YAML documents

yaml.dump_all()

Dumps multiple documents to a stream

chevron-rightExamplehashtag

Here are real-world DevOps/SRE scenarios using PyYAML, demonstrating each commonly used method for working with YAML in Python:


✅ PyYAML — yaml Module DevOps Use Cases

First, install PyYAML:

pip install pyyaml

🔹 yaml.safe_load()Load Kubernetes Manifest for Validation

import yaml

with open("deployment.yaml") as f:
    manifest = yaml.safe_load(f)

print("Deployment Name:", manifest["metadata"]["name"])

📌 Use when reading trusted YAML like Kubernetes configs, CI/CD pipelines.


🔹 yaml.load()Load with Custom Loader (when required)

import yaml

with open("pipeline.yaml") as f:
    data = yaml.load(f, Loader=yaml.FullLoader)

print("Stages:", data.get("stages"))

⚠️ Use only with Loader=.... Prefer safe_load unless you need custom types.


🔹 yaml.dump()Generate Ansible Inventory Dynamically

import yaml

inventory = {
    "all": {
        "hosts": ["web1.example.com", "web2.example.com"],
        "vars": {"ansible_user": "ubuntu"}
    }
}

with open("inventory.yml", "w") as f:
    yaml.dump(inventory, f)

print("Inventory YAML created")

🔹 yaml.safe_dump()Write CI/CD Config Without Tags

import yaml

config = {
    "stages": ["build", "test", "deploy"],
    "build": {"script": "make build"}
}

with open("gitlab-ci.yml", "w") as f:
    yaml.safe_dump(config, f, default_flow_style=False)

print("GitLab CI config written")

✅ Avoids Python object tags like !!python/object.


🔹 yaml.load_all()Load Multi-Document YAML (K8s manifest)

import yaml

with open("multi-doc.yaml") as f:
    docs = list(yaml.load_all(f, Loader=yaml.SafeLoader))

for doc in docs:
    print("Loaded kind:", doc.get("kind"))

📄 Example input:

---
kind: Deployment
metadata:
  name: my-app
---
kind: Service
metadata:
  name: my-service

🔹 yaml.dump_all()Generate Multi-Doc K8s File

import yaml

docs = [
    {"kind": "Deployment", "metadata": {"name": "web-app"}},
    {"kind": "Service", "metadata": {"name": "web-service"}}
]

with open("k8s-stack.yaml", "w") as f:
    yaml.dump_all(docs, f)

print("Multi-doc YAML written")

✅ Summary

Method
Real Use Case Example

yaml.safe_load()

Load Kubernetes YAML safely

yaml.load()

Load full YAML with custom Python types

yaml.dump()

Convert Python to YAML (Ansible inventory)

yaml.safe_dump()

Export CI/CD YAML (safe, clean format)

yaml.load_all()

Read multi-resource Kubernetes YAML file

yaml.dump_all()

Write multiple YAML docs (e.g., full K8s stack)


Would you like a visual cheat sheet, Jupyter notebook, or combined PDF guide for all 3 topics (requests, boto3, yaml)?

Last updated