DEV Community

Cover image for TL;DR YAML anchors
dejanualex
dejanualex

Posted on

TL;DR YAML anchors

Two main components: Anchor & which defines a chunk of configuration and Alias * used to refer to that chunk elsewhere.

Simple example, create dwarfs.yaml:

cat<<EOF>dwarfs.yaml - &dwarf Gimli - Dain - Thorin - *dwarf - Balin - *dwarf EOF 
Enter fullscreen mode Exit fullscreen mode

When an YAML parser reads dwarfs.yaml the alias will render the value identified by the anchor.

An anchor can be referenced by multiple aliases, and also we can merge maps (to add more values, or override existing ones) i.e.

cat<<EOF>dwarfs.yaml # anchor Gloin: &dwarf_basics role: Member hood_color: white skills: &skills_base - battle - mining # alias and merge map Oin: <<: *dwarf_basics role: Leader EOF 
Enter fullscreen mode Exit fullscreen mode

In dwarfs.yaml file, Gloin is being used as base definition. Oin uses << as key, which indicates that key-values from another mapping should be merged. Important note role value will be override in Oin.

Top comments (0)