惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

MongoDB | Blog
MongoDB | Blog
宝玉的分享
宝玉的分享
博客园 - 三生石上(FineUI控件)
小众软件
小众软件
罗磊的独立博客
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
S
SegmentFault 最新的问题
Last Week in AI
Last Week in AI
人人都是产品经理
人人都是产品经理
博客园 - 聂微东
博客园 - 司徒正美
博客园 - 叶小钗
T
Tailwind CSS Blog
博客园 - Franky
V
V2EX
有赞技术团队
有赞技术团队
美团技术团队
雷峰网
雷峰网
爱范儿
爱范儿
Jina AI
Jina AI
D
DataBreaches.Net
H
Help Net Security
酷 壳 – CoolShell
酷 壳 – CoolShell

Sealos Blog

Build a Full-Stack App with Claude Code + InsForge — Zero Backend Code | Sealos Blog InsForge vs Supabase: Which Backend for AI-Powered Development? | Sealos Blog Kubernetes NodePort Exhaustion: SSH Gateway Solution | Sealos Blog Claude Code Metrics Dashboard: Grafana Setup (2026) | Sealos Blog What Is RustFS? Apache 2.0 MinIO Alternative (2026) | Sealos Blog Claude Code Mobile: iPhone, Android & SSH (2026) | Sealos Blog Eaglercraft Server Hosting: Fast Setup (2026) | Sealos Blog An Honest Review: Migrating a Complex Microservice App from Heroku to Sealos | Sealos Blog The Ultimate Guide to Kubernetes Audit Logging for Security and Compliance | Sealos Blog Cost Optimization Shootout: Sealos Autonomous FinOps vs. Kubecost Manual Reports | Sealos Blog For CTOs: How to Cut Your Cloud Bill by 50% Without Sacrificing Performance | Sealos Blog Building Resilient Systems: A Deep Dive into Sealos High-Availability and Auto-Failover | Sealos Blog Building a Scalable Event-Driven Architecture with Sealos Managed Kafka | Sealos Blog Beyond kubectl apply: 5 GitOps Best Practices for Production-Ready CI/CD on Sealos | Sealos Blog Advanced RAG Pipelines: Why Your Choice of Vector Database (like Milvus) Matters | Sealos Blog Advanced MLOps: How to Monitor and Evaluate LLM Applications in Production | Sealos Blog A Developer's Guide to Kubernetes RBAC: Securing Your Cluster the Easy Way with Sealos | Sealos Blog A CISO's Guide to Cloud Development: Securing the CI/CD Pipeline with Sealos DevBox | Sealos Blog What is Kubernetes Multi-Tenancy? A Guide for Platform Engineers | Sealos Blog What is Infrastructure from Code (IfC)? The Next Step After Infrastructure as Code (IaC) | Sealos Blog What is GitOps? A Beginner's Guide to "Push-to-Deploy" Workflows | Sealos Blog What is eBPF? The Future of Kubernetes Networking and Security | Sealos Blog What is an "AI-Native" Platform? (And Why You Need One for MLOps) | Sealos Blog What is an Agentic Workflow? Building the Next Generation of AI Apps | Sealos Blog What is a Kubernetes Chargeback Model (And How Does it Save You Money?) | Sealos Blog What is a "Headless" Development Environment? (And How it Works with VS Code) | Sealos Blog What is a Graph-Based Vector Database? (And When to Use It Over Milvus) | Sealos Blog What is a "Cloud Operating System"? The Next Evolution of PaaS Explained | Sealos Blog The Real Cost of EKS: How Sealos Delivers a Simpler, Cheaper Kubernetes Experience | Sealos Blog The 3 Types of Kubernetes Autoscaling (HPA, VPA, CA) and How Sealos Manages Them for You | Sealos Blog
Mastering YAML: A Comprehensive Guide to Data Serializati...
Sealos · 2025-07-27 · via Sealos Blog

YAML is a cornerstone of modern software development and IT operations—a human-friendly data serialization language designed for both intuitive readability and seamless machine interpretability. Its name, "YAML Ain't Markup Language," underscores its focus on representing structured data, not annotating documents like XML. YAML is a strict superset of JSON, meaning any valid JSON is also valid YAML. This philosophy drives YAML's minimalist, indentation-based syntax, making complex data structures easy to read and write.

YAML's core design revolves around simplicity and accessibility. It minimizes the learning curve with a clean syntax, relying on indentation for structure and key-value pairs for data. Unlike XML's verbosity or JSON's braces and brackets, YAML's format is visually intuitive and closely resembles natural language. This makes YAML especially effective for configuration files, Infrastructure as Code (IaC), and automation workflows where clarity and human interaction are paramount.

YAML is platform-agnostic and supported by most modern programming languages, making it a popular choice for cross-platform configuration and data exchange. Its Unicode support ensures compatibility with international character sets.

FeatureYAMLJSONXML
ReadabilityExcellent for humansGood for developersVerbose
Machine ParsingSlowerFastSlow
Comments Support✅ Supported❌ Not supported✅ Supported
Metadata Support❌ Limited❌ None✅ Attributes, namespaces
Schema ValidationLimited (YAML 1.2)JSON SchemaXSD / DTD
Best Use CasesConfigs, IaCAPIs, Web/MobileEnterprise data, Docs
Tooling EcosystemStrong in DevOpsUniversalMature, legacy-focused

Summary:

  • YAML: Human-centric, ideal for configuration and automation.
  • JSON: Lightweight, fast, and universal for APIs and web.
  • XML: Rigid, metadata-rich, suited for enterprise and document-centric systems.

Case Sensitivity and File Extensions

  • YAML is case-sensitive: Tag, TAG, and tag are different.
  • Use .yaml or .yml file extensions.

Indentation: The Heart of YAML

  • Indentation defines structure—no braces or brackets.
  • Spaces only (never tabs). Consistency is critical (2 or 4 spaces per level recommended).
  • Inconsistent indentation is the #1 source of YAML errors.
  • Whitespace outside indentation is ignored.

Key-Value Pairs and Mappings

Mappings (dictionaries/objects) are unordered collections of unique key-value pairs.

  • Block style (above) is preferred for readability.
  • Flow style uses {} and commas, similar to JSON:
    user: {username: cinnamon, name: John}

Sequences (Lists/Arrays)

Ordered collections, denoted by -:

  • Block style (above) is most readable.
  • Flow style: fruits: [apple, banana, cherry]
  • Sequences can contain mappings, and mappings can contain sequences, allowing for complex nested structures.

Scalars: Strings, Numbers, Booleans, Null

  • Strings: Unquoted by default; quote if special characters or ambiguity.
  • Numbers: Integers and floats, no quotes needed. Supports decimal, octal (0o), and hexadecimal (0x) formats.
  • Booleans: Use true/false for best compatibility. Also accepts yes/no, on/off (YAML 1.1), but these can be ambiguous.
  • Null: Use null or ~.

Multi-line Strings

  • Literal block (|): Preserves newlines and indentation.
  • Folded block (>): Folds newlines into spaces.
  • Blank lines within folded blocks are preserved as newlines.

Comments

  • Start with #, can be inline or on their own line.
  • Example:

Explicit Type Tags and Schemas

  • Use !!type to force interpretation (e.g., !!str, !!int, !!float, !!bool).
  • Example:
  • Schemas define expected structure and types; use tools for validation (e.g., JSON Schema for YAML, Kwalify, Yamale).

Anchors (&) and Aliases (*): Reusability

Define data once with an anchor, reuse with an alias:

  • Use anchors and aliases to avoid duplication.
  • The merge key (<<:) allows merging mappings.
  • Overuse can reduce readability—document and structure carefully.
  • Avoid circular references and excessive indirection.

Multiple Documents

Separate with --- (three dashes):

  • Optionally end with ... (three dots) to mark the end of a document.

Configuration Files

YAML is the standard for configuration in tools like Docker Compose (docker-compose.yml), Kubernetes (*.yaml manifests), and many CI/CD systems.

Infrastructure as Code (IaC)

  • Ansible Playbooks: Define system states and tasks.
  • Kubernetes Manifests: Describe resources like Pods, Deployments, Services.
  • Terraform: Supports YAML for complex variable files.

Example Kubernetes Pod:

CI/CD Pipelines

YAML defines workflows in GitHub Actions (.github/workflows/*.yml), GitLab CI (.gitlab-ci.yml), CircleCI, Azure Pipelines, and more.

API Documentation

OpenAPI/Swagger specs use YAML for endpoints, schemas, and responses.

Data Serialization and Exchange

YAML is used for storing and exchanging structured data between systems and languages. It is also used for custom file formats and data pipelines.

Other Use Cases

  • Cloud configuration: AWS CloudFormation, Azure Resource Manager, Google Cloud Deployment Manager.
  • Application settings: Many frameworks (e.g., Ruby on Rails, Spring Boot) use YAML for settings.
  • Data science and ML: Experiment tracking and pipeline configuration.

Best Practices

  • Consistent indentation (spaces only).
  • Descriptive key names (avoid abbreviations).
  • Strategic comments for clarity.
  • Quote strings when in doubt or when using special characters.
  • Group related data logically.
  • Limit nesting for readability.
  • Validate YAML with linters and schema tools.
  • Document anchors and aliases for maintainability.
  • Avoid mixing tabs and spaces.
  • Use explicit typing for ambiguous values.

Common Pitfalls

  • Incorrect indentation (spaces/tabs, inconsistent levels).
  • Missing colons or invalid characters.
  • Data type mismatches due to implicit typing (e.g., "yes" as boolean).
  • Typos in keys or values.
  • Overuse or mismanagement of anchors and aliases.
  • Relying on YAML 1.1 features (e.g., yes/no as booleans) when using YAML 1.2 parsers.

Debugging Tips

  • Use YAML validators (e.g., yamllint, YAML Lint, Spectral).
  • Break large files into sections.
  • Implement schema validation for critical configs.
  • Log parsing errors and check for trailing spaces.
  • Document anchors and aliases.
  • Use version control to track changes and facilitate rollbacks.
  • Test YAML files with the actual tools that will consume them.

YAML is indispensable for configuration, automation, and data serialization in DevOps and cloud-native computing. Its human-centric design, minimalist syntax, and native comment support make it ideal for environments where clarity and frequent human interaction are essential. However, strict indentation rules and implicit typing require discipline and validation tools to avoid pitfalls. Used thoughtfully, YAML empowers teams to manage complex systems with clarity and efficiency—and its role in automation and orchestration will only grow as declarative approaches continue to shape modern IT.


Further Reading: