I want to programmatically generate a yaml file using Python that looks as follows(This is a part of the yaml file, the values of the nested blocks, like the count of it, key:value, etc would be coming as an input. FYI).
main_: &MAIN
key: value
nested_1: &nested1
<<: *MAIN
key: value
nested_2: &nested2
<<: *MAIN
key: value
I have tried using ruamel.yaml.comments.CommentedMap and some of its methods like yaml_set_anchor and add_yaml_merge. Here is the code that I have written:
data['main_'] = main_ = cm(key=value)
main_.yaml_set_anchor('MAIN')
for n in nested:
# Here n would be 'nested_1','nested_2', and so on..
data[n] = nested_ = cm(key=value)
nested_.yaml_set_anchor(n)
nested_.add_yaml_merge([(0,main_)])
When this gets executed, what I get in the output is this:
main_: &MAIN
key: value
nested_1: ---> Anchor Missing Here
<<: *MAIN
key: value
nested_2: ---> Anchor Missing Here
<<: *MAIN
key: value
The line in code does not have any effect. This is probably because the second anchor is not yet merged.
nested_.yaml_set_anchor(n)
So, I try something like this:
for n in nested:
# Here n would be 'nested_1','nested_2', and so on..
data[n] = nested_ = cm(key=value)
nested_.yaml_set_anchor(n)
nested_.add_yaml_merge([(0,main_)])
nested_.add_yaml_merge([(0,nested_)]). ---> Merged to self
And I get this in return:
main_: &MAIN
key: value
nested_1: &nested1
<<: [*MAIN, *NESTED1]
key: value
nested_2: &nested2
<<: [*MAIN, *NESTED2]
key: value
Both of them get merged. I do not know how to proceed further with these nested anchors/references.