Azure Pipeline variable when to use explicit name and value attributes

Viewed 149

This doc mentions two ways to create a yml variable.

Explicit use of name and value attributes

variables:
- name: myvariable
  value: myvalue

Another approach is a short-hand key: value approach.

variables:
  myvariable: myvalue

I have noticed that if you're using variables for a template reference, you need to be explicit about the name and value. This will work.

variables:
- name: localTargetEnvironment
  value: dev 
- name: variablesTemplatePath
  value: ../shared/variables-${{ variables.localTargetEnvironment }}.yml    
- template: ${{ variables.variablesTemplatePath }} 

But this will not work.

variables: 
  variablesTemplatePath: ../shared/variables-${{ variables.localTargetEnvironment }}.yml
- template: ${{ variables.variablesTemplatePath }} 

When/why would I use one approach over another?

2 Answers

YAML has two kinds of collection nodes: sequences and mappings. When you use -, you indicate a sequence item. Sequence items are the content of sequences.

You use sequences when the identifying attribute of the contained values is their position. For example, for jobs, you have a first job, a second job and so on. Their order is meaningful and important.

Mappings on the other hand are collections that contain key-value-pairs. The key usually being a scalar (i.e. a textual value, like pool or vmImage) and the value being any kind of YAML node. For mappings, the identifying attribute of a value is its key. For example for variables, their order is not important, but their name is.

In addition, yaml pipeline is strict with yaml format, thus you should not use sequences nodes and mappings node for variables in the same time, which will cause parsing error. See: Question about the hypens in a YAML file, when to use for details.

You could add the filed extends and then try it again. Such as below:

    variables: 
      localTargetEnvironment: test
      variablesTemplatePath: test/${{ variables.localTargetEnvironment }}.yml
    
    extends:
      template: ${{ variables.variablesTemplatePath }} 

Result:

enter image description here

Related