Variable Reusability

YAML itself supports variable reusability but does not support cross-file variable reuse.

CNB enables referencing variable values along property paths using custom YAML tag reference, which can be combined with include for cross-file usage.

TIP

  1. Variables with the same name at the top level will be overridden and not merged. Local .cnb.yml will override variables in include, and variables in later elements of the include array will override earlier ones.
  2. 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

# VS Code Configuration

To avoid errors in VS Code when writing YAML files with custom tag reference, you can configure the following settings after installing the VS Code 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.