YAML Anchoring edit

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 😃