YAML reusable variables with case-specific values

3.7k views Asked by At

Is it possible in .yml config to have dynamic properties in variables that are set depending on a particular case. For example:

MY_VAR: &MY_VAR
  keys:
   key2: blahblahblah
   key3: blahblahblah  # only apply this for section2, not section1

section1: 
 var: *MY_VAR

section2:  # this case needs key3 set, otherwise everything else is the same 
 var: *MY_VAR
1

There are 1 answers

2
Anthon On

YAML's anchors (&MY_VAR) and references (*MY_VAR) are in the specification to prevent duplication, but also to allow serialisation of objects that occur multiple times in a hierarchy, and to allow them to be deserialized so that they again point to the same structure in memory.

This is not some string level macro facility with parameters and/or conditions. In your example, if you set MY_VAR->key1 you also change the value of section1->var->key1

Of course an application can interpret the values it loads (e.g. on complex strings that form scalar for the key in a mapping), but for that there is no facility in the YAML specification. That has to be (and can be) done at the application level.