Hidden reusable blocks in YAML

Viewed 3924

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"]
2 Answers

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

Related