Reputation: 51
I have a YAML file which has several different keys that I want to provide the same value for. Additionally, I want this value to be easily configurable.
See YAML for my specific use-case below:
---
# Options for attribute_value
att_value_1: &att_value_1
att_value_2: &att_value_2
# There could be more options...
# This is where the constant is being set.
attribute_value: &attribute_value *att_value1
items:
- name: item1
attributes:
attribute_for_item1: *attribute_value
- name: item2
attributes:
attribute_for_item2: *attribute_value
Here is a simplified YAML which demonstrates the problem:
---
foo: &foo "Hello World!"
bar: &bar *foo
Error (it's complaining about the first line that has "Hello World!" on it):
(<unknown>): did not find expected key while parsing a block mapping at line 2 column 1
I expect the value to propagate.
Upvotes: 5
Views: 8750
Reputation: 39638
Error (it's complaining about the first line that has "Hello World!" on it):
You have to tell us which YAML implementation you're using. PyYAML and NimYAML both correctly report that the error is in the third line; the second line is okay.
I expect the value to propagate.
There is nothing in the specification that backs this expectation. The spec says:
Note that an alias node must not specify any properties or content, as these were already specified at the first occurrence of the node.
Properties are anchors and tags. You cannot put an anchor on an alias node since it already has an anchor.
In your example,
---
foo: &foo "Hello World!"
bar: &bar *foo
&bar
is completely superfluous since you already can refer to the "Hello World"
node via *foo
and therefore, there is no point in introducing &bar
.
To answer your question: You cannot reference a YAML anchor from another YAML anchor, because a YAML anchor is not a node. YAML represents a graph, i.e. nodes and directed edges. Anchors and aliases are used to reference the same node multiple times (not to copy values as you might think). This also means that everything within a YAML file is content. There is no such thing as variable declarations.
It seems you are using the wrong tool for your use-case. To configure YAML files with external values, you would typically use a templating engine (SaltStack and Ansible use Jinja for example) and generate your YAML file from a template. You could supply your options in another YAML file. This would clearly separate the configuration options from the content.
Upvotes: 1