I am trying to define a reusable block in a docker-compose.yml
file in a way that the reusable block definition itself is NOT included in the final (evaluated) YAML.
I know how to define a reusable block with this syntax:
services:
default: &default
image: some/image
dashboard:
<<: *default
command: run dashboard
ports: ["3000:3000"]
But, the above also creates an entry named default
under services, which I would like to avoid. In other words, I need the final YAML result to only include dashboard
under the services
property.
Is this possible with YAML? I was unable to find any reference that discusses this structure clearly enough.
Intuitively, I have tried some variations of the below, but it also did not work.
services:
&default:
image: some/image
dashboard:
<<: *default
command: run dashboard
ports: ["3000:3000"]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With