Using variables in YAML files


I learned an awesome YAML feature today, the ability to use variables in YAML files.

I’m not talking about application variables, but blocks of re-usable YAML which you can reference later on in your file.

Searching online, you won’t find much information on this, but it is in the official YAML specification.

Let’s have a look at this amazing YAML (relatively unknown) feature!

The Node Anchor in YAML

In YAML, we have something called a Node Anchor.

An anchor is denoted by the & indicator. It marks a node for future reference. An alias node can then be used to indicate additional inclusions of the anchored node. An anchored node need not be referenced by any alias nodes; in particular, it is valid for all nodes to be anchored.

YAML example

Take a look at this YAML file.

    # Create 2 new roles
    # assign an anchor name using the `&`
    admin_roles: &admin_roles [ROLE_SUPER_ADMIN, ROLE_ADMIN]
    public_roles: &public_roles [ROLE_GUEST, ROLE_USER]

        # We can reference the anchor with a `*` (asterisk)
        - { path: ^/admin, role: *admin_roles }

We can use the ampersand & character to create a named anchor, that we can then reference later on with an asterisk *.


Anchor names must not contain the [, ], {, } and , characters.

This came in use when I had to create some elasticsearch mappings that were being duplicated all over the place. I managed to slim the configuration files down quite significantly using this method, which as you can imagine, also made the code more manageable.