Hunter Kohler
Hunter Kohler

Reputation: 2735

Pre-declare an excluded header of anchors in yaml?

I was wondering if there was a way to predeclare anchors in yaml without including them in the final representation. This would make code much more clear. For example: reused segments in a verbose yaml file. I imagine something like this (though it doesn't work):

&anch1 "string1"
&anch2 "string2"
&anch3 key1: ["arr"]
       key2: {name: "obj"}

prototype:
    name: "stack_overflow"
    str: *anch1
    default_str: *anch2
    <<: *anch3

to be equal to something of this sort in json:

{
   "prototype": {
        "name": "stack_overflow",
        "str": "string1",
        "default_str": "string2",
        "key1": ["arr"],
        "key2": {"name": "obj"}
    }
}

Thanks so much.

Upvotes: 0

Views: 443

Answers (1)

flyx
flyx

Reputation: 39768

No. From the YAML perspective, there is no need for this: Anchors & aliases are used for referring to the same node multiple times. Therefore, there will always be a first occurrence of the node which can be anchored, and subsequent occurrences can use an alias.

From a user perspective, anchors & aliases can be used a bit like variables. While this works, it is not the intended use case and therefore poorly supported (e.g. you can't concatenate an alias value with other scalar content).

This problem is usually solved by using a templating engine. Many power users of YAML (Ansible, SaltStack etc) use some templating engine to pre-process the YAML before parsing it.

Upvotes: 1

Related Questions