Ever feel frustrated when dealing with growing event listeners?
You might sigh and think "I don't want to be a YAML engineer".
Configure JSON Schema in VSCode and Jetbrains
This section introduces YAML Anchors and Aliases to help write reusable YAML and improve maintainability.
Before reading further, we recommend two online YAML parsers (both work equally well) to help validate anchor usage:
Before optimization:
main:
push:
- name: amd
runner:
tags: cnb:arch:amd64
services:
- docker
stages:
- name: uname
script: uname -a
- name: hello world
script: echo "hello world"
- name: arm
runner:
tags: cnb:arch:arm64:v8
services:
- docker
stages:
- name: uname
script: uname -a
- name: hello world
script: echo "hello world"
Optimization 1:
# Recommended to prefix anchors with . to avoid being mistaken for branch/tag names
.build_script: &build_script
- name: uname
script: uname -a
- name: hello world
script: echo "hello world"
main:
push:
- name: amd
runner:
tags: cnb:arch:amd64
services:
- docker
stages:
*build_script
- name: arm
runner:
tags: cnb:arch:arm64:v8
services:
- docker
stages:
*build_script
Optimization 2:
# Recommended to prefix anchors with . to avoid being mistaken for branch/tag names
.build_script: &build_script
services:
- docker
stages:
- name: uname
script: uname -a
- name: hello world
script: echo "hello world"
main:
push:
- name: amd
runner:
tags: cnb:arch:amd64
services:
- docker
<<: *build_script
- name: arm
runner:
tags: cnb:arch:arm64:v8
<<: *build_script
We can validate the optimized YAML using online parsers to ensure it meets expectations.
Comparing Optimization 1 and 2 shows different levels of anchor usage granularity, and introduces the << merge key syntax.
We've used three syntax symbols:
&*<< (cannot be used with arrays)Before optimization:
main:
push:
- name: amd
runner:
tags: cnb:arch:amd64
services:
- docker
env:
SSH_USERNAME: username
SSH_PASSWORD: password
SSH_IP: production_ip
stages:
- name: uname
script: uname -a
- name: echo ssh ip
script: echo $SSH_IP
develop:
push:
- name: amd
runner:
tags: cnb:arch:amd64
services:
- docker
env:
SSH_USERNAME: username
SSH_PASSWORD: password
SSH_IP: test_ip
stages:
- name: uname
script: uname -a
- name: echo ssh ip
script: echo $SSH_IP
After optimization:
.services_and_imports: &services_and_imports
services:
- docker
imports:
- ./xxx.yml
.common_envs: &common_envs
SSH_USERNAME: username
SSH_PASSWORD: password
SSH_IP: production_ip
.develop_envs: &develop_envs
DEVELOP: true
.production_envs: &production_envs
PRODUCTION: true
.uname_script: &uname_script
- name: uname
script: uname -a
main:
push:
- name: amd
runner:
tags: cnb:arch:amd64
<<: *services_and_imports
env:
<<:
[
*common_envs,
*production_envs
]
stages:
- *uname_script
- name: echo ssh ip
script: echo $SSH_IP
develop:
push:
- name: amd
runner:
tags: cnb:arch:amd64
env:
<<:
[
*common_envs,
*develop_envs
]
stages:
- *uname_script
- name: echo ssh ip
script: echo $SSH_IP