yamlaliasdirected-graph

YAML - Assigning alias to anchor alternatives


In YAML, we are not allowed to assign an alias to an anchor. How can I acheieve similar functionality so that I can use one generic key throughout the YAML file while only needing to make an update in one location?

t_shirt_sizes:
  &t_shirt_xs EXTRA_SMALL
  &t_shirt_sm SMALL
  &t_shirt_md MEDIUM
  &t_shirt_lg LARGE
  &t_shirt_xl EXTRA_LARGE

t_shirt:
  &t_shirt_size *t_shirt_md


# Use the *t_shirt_size further down the YAML file

store:
  order_shirt_sizes: *t_shirt_size

Solution

  • This is possible:

    t_shirt:
      &t_shirt_size EXTRA_SMALL
    

    It fulfils your requirement to only need a single change to change the size everywhere. If you need the indirection, the closest thing you can do is

    t_shirt:
      &t_shirt_size [ *t_shirt_md ]
    

    Then you'd need to handle the size value as 1-value sequence during loading.

    YAML serializes a graph of directed nodes. Using an alias makes another connection to the referenced node, therefore does not create a new node and thus it cannot be anchored. The purpose of anchors & aliases is to be able to serialize cyclic graphs.