YAML is the config format you meet everywhere in DevOps: Kubernetes manifests, Ansible playbooks, GitHub Actions and GitLab CI pipelines, Docker Compose files. It stores the same kind of structured data as JSON but is written to be easy for people to read and edit.
Python does not parse YAML out of the box. The standard library is
PyYAML, imported as yaml, and it is already installed on this lab
machine.
import yaml
YAML earns its place in config files for a few reasons:
#, which JSON does not. Config files live
and die by good comments.A small YAML config looks like this:
# service configuration
service: api
port: 8080
enabled: true
tags:
- web
- public
Under the surface YAML describes the same data model as JSON. That
config parses into a Python dict with the keys service, port,
enabled, and tags, where tags is a list. Mappings become dicts,
sequences become lists, and scalars become strings, numbers, or
booleans, exactly like JSON.
Because the result is ordinary dicts and lists, everything you already know about working with them applies. The next node covers the safe way to parse YAML text into those objects.
import yaml loads PyYAML, the standard YAML library for Python.