G
GuideDevOps
Lesson 4 of 9

Nested Structures

Part of the YAML tutorial series.

Deep Nesting

While a simple name and value are easy to read, production-grade YAML for Kubernetes or Ansible can become incredibly deep.

Understanding the "Level" of your code is vital. Every time you indent further, you are creating a "Child" attribute for the "Parent" key above it.


1. Mappings of Mappings

This is used to describe objects that have sub-properties.

database:
  connection:
    host: 10.0.0.5
    port: 5432
  auth:
    username: admin
    secret_key: vault/db-key

In this structure:

  • database is the parent.
  • connection and auth are siblings.
  • host and port are the children of connection.

2. Lists of Mappings (Most Common)

In DevOps, we almost always deal with "Lists of Objects." For example, a Kubernetes Pod might run 3 different containers. Each container is an object (mapping) with a name and an image.

containers:                # A List
  - name: frontend         # Item 1 starts here (A Mapping)
    image: nginx:1.19
    ports:
      - containerPort: 80
  - name: logger           # Item 2 starts here (A Mapping)
    image: fluentd:latest

Common Mistake: Forgetting to indent the properties of a list item. The name and image keys belong to the list item started by the hyphen (-). If you don't line them up properly, the YAML won't parse.


3. Mappings of Lists

Sometimes a single object has multiple values for one attribute.

monitoring:
  targets:           # A scalar key pointing to a List
    - prometheus
    - jaeger
    - grafana
  alert_channels:    # Another scalar key pointing to a List
    - slack
    - email
    - pagerduty

The "Visual Test"

A great way to test your nesting is to draw vertical lines down the left side of your code.

  • Every line that starts at the same vertical column is a Sibling.
  • Every line that is further to the right is a Child.
  • Every line further to the left is a Parent (or belong to a different branch entirely).