Hidden reusable blocks in YAML
Docker Compose file format 3.4 adds support for extension fields: top-level keys starting with x- that are ignored by Docker Compose and the Docker engine.
For example:
version: '3.4'
x-default: &default
image: some/image
services:
dashboard:
<<: *default
command: run dashboard
ports: ["3000:3000"]
Source: “Don’t Repeat Yourself with Anchors, Aliases and Extensions in Docker Compose Files” by King Chung Huang https://link.medium.com/N5DFdiC3F0
This is not possible in YAML 1.2 (or any former version). The reasoning behind this is that YAML has been designed to be a serialization language, not a configuration language.
The Anchor/Alias construct is nice for serializing cyclic data structures. It was never intended to be used for declaring variables that will be used in multiple places. So currently, the only way to create a reusable structure which can be used in multiple places it to define the structure at the first place where it is used. For example:
services:
dashboard:
<<: &default
image: some/image
command: run dashboard
ports: ["3000:3000"]
some_other_service:
<<: *default
other_props: ...
Also, be aware that the merge key <<
is not part of the YAML spec and only defined as additional feature for YAML 1.1. It is not defined for YAML 1.2 and will be explicitly deprecated for upcoming YAML 1.3.
We (as in: the people currently working on YAML 1.3) are aware of this missing feature and plan to provide a better solution with YAML 1.3.