YAML Anchoring
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:
people:
- name: 'Chiara'
age: '35'
- name: 'Carlos'
age: '35'
- name: 'Diana'
age: '35'
Every year, you need to go thought this list and update every entrance. It is not very nice, and you may type it wrong to one of them. Instead, you can use anchoring for people that was born the same year:
people:
- 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 now you just need to update once the age for people that was born in 1983.
Merge data
Ok, that works when you want to copy full values... but what if you want to merge values in a dictionary?
Lets say you have triplets working in my company:
people_on_company:
- 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 name.You many want to reference this data instead of writing it 3 times. Well, luckily you can use <<
to merge data:
- &smith_triplet
name: 'Chiara'
age: 35
lastname: 'Smith'
- <<: *smith_triplet
name: 'Carlos'
- <<: *smith_triplet
name: 'Diana'
This resolves to the previous structure.
Conclusion
That is not all about anchoring, there is many more interesting feature in yaml, like Folded Style or Literal Style. You can check YAML Specification to know more about this.
Hope this you liked this post, let me know if it was useful
Thanks @Maria Valero this is like what Regex was to me, before I learned Regex!
I'm happy it was useful
I learned about yaml anchors less than a year ago lol but I have seen some people struggling with this, and it is not difficult to understand
This is amazing, it sounds like basic stuff but I never really knew the full power of anchoring, until now!![:raised_hands: 🙌](/emojione/assets/png/1F64C.png)
And thanks once again for another amazing post, this is exactly the sort stuff we should all be doing, sharing knowledge!![:clap: 👏](/emojione/assets/png/1F44F.png)
I vote this gets reposted to Medium![:white_check_mark: ✅](/emojione/assets/png/2705.png)