21

Just getting up to speed with YAML and want to confirm whether it's possible to utilise its anchor (&) and reference (*) functionality across separate files or separate documents within one file. For example, for the latter:

--- # Document A
Lunch: &lunch01     # Already thinking of lunch ;-)
    - BBQ Chicken
    - Sirloin Steak
    - Roast Beef
    - Salmon
...

--- # Document B
Monday:    *lunch01
Tuesday:   closed
Wednesday: *lunch01
Thursday:  closed
Friday:    *lunch01
...

(Apologies if my syntax is incorrect, still trying to convert across from thinking in terms of arrays and dictionaries.)

Does this work? Or would I go about this by merging the data within my programming language of choice at run time?

2 Answers2

8

I am not an expert on YAML, but from my experience, this doesn't work. I am using PyYAML, and the parser throws an error when reaching the reference, complaining about an "undefined alias".

So you will have to merge the data at runtime.

  • 2
    It appears that you're right, reading into [this post](http://code.google.com/p/snakeyaml/issues/detail?id=32) backs it up somewhat. –  Jun 18 '12 at 11:17
1

Per YAML's spec, there's no way to do that. but...

This is possible with yq's explode operator if you're using a single file with multiple documents:

cat <<EOF | yq 'explode(.)' 
---
Lunch: &lunch01
    - BBQ Chicken
    - Sirloin Steak
    - Roast Beef
    - Salmon

---
Monday:    *lunch01
Tuesday:   closed
Wednesday: *lunch01
Thursday:  closed
Friday:    *lunch01
EOF

I've came across a problem like that when creating a Kubernetes manifest with a lot of repeating fields, and yq integrated beautifully on my workflow!

arthur simas
  • 132
  • 5