YAML Anchoring

Maria Valcam
Quiqup Engineering
Published in
2 min readMay 16, 2018

You may have seen a YAML file that looks similar to this:

default: &default
adapter: postgresql
pool: 25
timeout: 5000
database: awesomedb
qa:
<<: *default
database: awesomedb_qa
test:
<<: *default
production:
<<: *default
database: awesomedb_prod

If you have seen this before, but you don’t know what & and * mean, this post will explain it to you.

Anchors and Aliases

In YAML, & is called an anchor and * is called an alias. Using this, you can reuse values inside a YAML structure, where & indicates the data that * will reference.

Reference data

So imagine you have a list of people working for a company:

staff:
- name: 'Chiara'
age: '35'
- name: 'Carlos'
age: '35'
- name: 'Diana'
age: '35'

Every year, you need to go through this list and update every entry. It is not a very seamless process, prone to human error. Instead, you can use anchoring for people who were born the same year:

staff:
- name: 'Chiara'
age: &born_1983 '35'
- name: 'Carlos'
age: *born_1983
- name: 'Diana'
age: *born_1983

This structure resolves to the same previous structure, but in this case, you just need to update the staff’s age once for people who were born in 1983. The string value 35 is then referenced by &born_1983.

Merge data

Ok, easy enough. That works when you want to copy full values… but what if you want to merge values in a dictionary?

Let’s say you have triplets working in your company:

staff:
- name: 'Chiara'
age: 35
lastname: 'Smith'
- name: 'Carlos'
age: 35
lastname: 'Smith'
- name: 'Diana'
age: 35
lastname: 'Smith'

they all have the same properties but different names. You may want to reference this data instead of writing it 3 times. Well, luckily you can use << to merge data:

staff:
- &smith_triplet
name: 'Chiara'
age: 35
lastname: 'Smith'
- <<: *smith_triplet
name: 'Carlos'
- <<: *smith_triplet
name: 'Diana'

This resolves to the previous structure. Our anchor &smith_triplet points to our dictionary, and then we merge it with other key values.

Conclusion

This, of course, is a very simplistic explanation and is not all anchoring can do. There are many more interesting features in YAML, like Folded Style or Literal Style, to name a few. If you’re interested in learning more follow this link to YAML Specification.

Hope this you liked this post. Please leave a comment if you think this information was useful or you want to know more about YAML :)

--

--

Maria Valcam
Quiqup Engineering

Engineer with an MBA. I am interested in Business, Doversity and Engineering.