Friday, July 02, 2021

YAML Anchor, Aliases and Merge Keys

Don’t Repeat Yourself with Anchors, Aliases and Extensions in Docker Compose Files | by King Chung Huang | Medium

definitions: steps: - step: &build-test name: Build and test script: - mvn package artifacts: - target/** pipelines: branches: develop: - step: *build-test main: - step: *build-test


YAML anchors | Bitbucket Cloud | Atlassian Support

definitions: steps: - step: &build-test name: Build and test script: - mvn package artifacts: - target/** pipelines: branches: develop: - step: *build-test main: - step: *build-test

YAML Ain’t Markup Language (YAML™) Version 1.2


YAML Anchor, Aliases and Merge Keys

Some of YAML's properties not in JSON are anchors, aliases and merge keys that can work well together. These allow references and mixins for hashes (not sequences a.k.a. arrays) and are common to reduce repetition of same configuration directives that some files/systems tend to and/or sometimes just because one can

YAML Anchor

&<anchor-name>
YAML 1.2 (3rd Edition) 3.2.2.2. Anchors and Aliases
YAML 1.1 3.2.2.2. Anchors and Aliases
YAML 1.0 4.3.6. Anchor
YAML Alias
*<anchor-name>
YAML 1.2 / 1.1; see above 3.2.2.2. Anchors and Aliases
YAML 1.0 4.4. Alias
YAML Merge Key
<< : *<anchor-name> (one; or:)
<< : [ *<anchor-name>, *<anchor-name>, ... ] (sequence of: [none,] one or multiple)
YAML 1.1 Working Draft Merge Key Language-Independent Type

Anchors need to be before aliasing (e.g. in an alias or merge key), can remain unused and can be re-defined, last one wins at the time of use (flow is from top to bottom).

Example-YAML with AliasesReferences and Merge Keys taken from the Merge Key working draft:

---
- &CENTER { x: 1, y: 2 }
- &LEFT { x: 0, y: 2 }
- &BIG { r: 10 }
- &SMALL { r: 1 }

# All the following maps are equal:

- # Explicit keys
  x: 1
  y: 2
  r: 10
  label: center/big

- # Merge one map
  << : *CENTER
  r: 10
  label: center/big

- # Merge multiple maps
  << : [ *CENTER, *BIG ]
  label: center/big

- # Override
  << : [ *BIG, *LEFT, *SMALL ]
  x: 1
  label: center/big


No comments: