Variable Reusability
YAML itself supports variable reusability but does not support cross-file variable reuse.
"Cloud Native Build" extends Yaml
with a custom tag called reference
to enable referencing variable values by property path.
This feature can be combined with include to use variables across multiple files.
TIP
- Variables with the same name at the top level will be overridden and not merged.
Local
.cnb.yml
will override variables ininclude
, and variables in later elements of theinclude
array will override earlier ones. reference
supports nested references up to a maximum of 10 levels.
# Example
a.yml
.val1:
echo1: echo hello
.val2:
friends:
- one:
name: tom
say: !reference [.val1, echo1]
.cnb.yml
include:
- ./a.yml
.val3:
size: 100
main:
push:
- stages:
- name: echo hello
script: !reference [.val2, friends, "0", say]
- name: echo size
env:
SIZE: !reference [".val3", "size"]
script: echo my size ${SIZE}
After parsing, it is equivalent to:
main:
push:
- stages:
- name: echo hello
script: echo hello
- name: echo size
env:
SIZE: 100
script: echo my size ${SIZE}
# Advanced Example
You can use the pipeline as a whole configuration reference:
.common-pipeline:
- stages:
- name: echo
script: echo hello
main:
push: !reference [.common-pipeline]
test:
push: !reference [.common-pipeline]
After parsing, it is equivalent to:
main:
push:
- stages:
- name: echo
script: echo hello
test:
push:
- stages:
- name: echo
script: echo hello
# VSCode Configuration
To avoid errors in VSCode when writing YAML files with custom tag reference
,
you can configure the following settings after installing the VSCode YAML
extension:
setting.json
{
"yaml.customTags": ["!reference sequence"]
}
TIP
To prevent the YAML extension from treating the first-level variable name
as a branch name based on the Schema
and showing an error,
you can prefix the first-level variable name with a .
(dot), for example: .var
.
← include