site.lyte.dev/content/blog/the-only-good-thing-about-yaml-anchors-and-aliases-and-extend.md
2023-06-26 14:35:12 -05:00

50 lines
2.2 KiB
Markdown

---
description: "A 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.
<!--more-->
# Introduction
Since working at [Postmates][pm] ([we're hiring][pm-referral]!) and getting my
feet wet in the vast world of Kubernetes, I've had to work with a *lot* of
[YAML][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][aa-spec]
and the [Merge Key][mk-spec].
# What is it?
Basically, in a YAML document, you may denote a value node for future
referencing later.
[pm-referral]: https://grnh.se/cc2da77e1
[yaml]: https://yaml.org/
[aa-spec]: https://yaml.org/spec/1.2/spec.html#id2765878
[mk-spec]: https://yaml.org/spec/1.2/spec.html#id2765878