site.lyte.dev/content/blog/the-only-good-thing-about-yaml-anchors-and-aliases-and-extend.md
2020-09-17 13:35:38 -05:00

2.1 KiB


description: "" title: The Only Good Thing About YAML: Anchors, Aliases, and Extend draft: true

TL;DR: You can prefix a YAML value with &{NAME_HERE} (like &key) to create an anchor with that name and reference it later with *{NAME_HERE} (like *key) to avoid repeating yourself in a document. You can also "merge" object values using the << key.

Introduction

Since working at [Postmates][pm] (we're hiring!) and getting my feet wet in the vast world of Kubernetes, I've had to work with a lot of YAML.

One of the most important things for me when dealing with YAML was to keep in mind is that YAML is a superset of JSON. This means all JSON documents are valid YAML documents. When you look at YAML, it can be easy as a human to fail to parse what's actually going on. Which is fair, since fully parsing a YAML document actually requires quite a bit of code, which is a topic unto itself. If you remember that a YAML document is really (almost always) just a map of keys and values with various shortcuts that allow you the text representation (YAML) to look nice, YAML becomes a good deal easier to reason about.

That also means, though, that YAML is wordy. Not as noisy as JSON, since many of the symbols are now unnecessary, but still wordy. If you have a type of object with 20 fields, all of which are mostly the same except for a few fields here and there, you are going to have to repeat yourself a lot.

... At least in JSON. While I dislike YAML, I did learn two really neat features that helped enormously in cleaning things up and avoiding repetition or needing to change things in more than one place. I'm surprised, though, that these features occur so infrequently (maybe parser support is lacking?) out in the real, wild world as to be nearly undiscoverable: Anchors and Aliases and the Merge Key.

What is it?

Basically, in a YAML document, you may denote a value node for future referencing later.