user577537
user577537

Reputation:

Can YAML anchors/references occur across files/documents?

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?

Upvotes: 21

Views: 7799

Answers (2)

arthur simas
arthur simas

Reputation: 726

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!

Upvotes: 3

Bastien Gorissen
Bastien Gorissen

Reputation: 96

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.

Upvotes: 8

Related Questions