Is it possible to use variables in azure pipelines yml that extends from template(which contains variables)?

1k views Asked by At

I would like to use variables in my Azure pipeline yaml to be able to map some values between azure and terraform. Also using extends in my yaml referring to a template in another repo in the project(it contains variables).Now I am getting error in the pipeline that 'variables' is already defined

(This question is already addressed here but could not get a good answer there.Due to lack of points, I could not comment and ask for updates there. Therefore asking again Use variables in azure pipelines yml that extends from template possible?)

pipeline.yaml

parameters:
- name: vm
  displayName: Choose a vm
  type: string
  default: vm1
  values:
  - vm1
  - vm2
  - vm3

variables:
  ${{ each value in parameters.env }}:
  TF_VAR_ENV: ${{ value }}

trigger: none

resources:
  repositories:
  - repository: templates
    type: git
    name: team-templates

extends:
  template: pipelines/templates/pipeline-team-test.yaml@templates
  parameters:
    stagesVersion: 2

Error in pipeline: __built-in-schema.yml (Line: 40, Col: 11): 'variables' is already defined

expecting: Able to use variables in both template and pipeline yaml. Is this possible??

1

There are 1 answers

0
ste-fu On

Using and extending templates is a method of composing a pipeline from other blocks of yaml, with the different files being compiled together before running.

Variables can be defined at root, stage and job level. When you use the extends keyword here you are still at the root level, so because the pipeline-team-test.yaml file also defines a variables block, that causes the error that you see.

The usual way round this is to pass in the value you want to set via the parameters, as every template, whether stages, jobs or steps can accept parameters and use them accordingly. You can also set default parameter values in the template so you don't need to refactor every single other pipeline using the template.

The parameters can be mapped to variables in subsequent stages or jobs if you need them to be variables, or to derive variables from them, but in answer to your "expecting", you are effectively declaring the same element twice in yaml at the same level, so it just won't work.