I need to pass a collection of environment variables to a yml template so that those variables can be used for one of its task.
I developed this sample yml template named my-new-template.yml:
parameters:
- name: envTests
type: object
default: []
steps:
- powershell: |
Write-Host "$env:variable1"
displayName: 'Display environment'
env:
${{ parameters.envTests }}
where practically I pass the collection as an object input parameter named envTests and then this object is passed as it is to the env group of my powershell task.
The solution was taken from this SO thread Set environment variables into azure devops pipelines step from template.
In my main pipeline I call that template this way:
- job: Job1
pool:
vmImage: 'ubuntu-latest'
steps:
- checkout: none
- template: my-new-template.yml
parameters:
envTests:
- name: variabile1
value: valuevariabile1
- name: variabile2
value: valueVariabile2
- template: my-new-template.yml
I make two calls just to see that build is not broken if no environment variables are provided. It seems good to me but I got this exception
my-new-template.yml (Line: 12, Col: 5): A sequence was not expected
Could someone please tell me what I’m doing wrong? Thanks a lot
2
Answers
In the main YAML you can change to like as below to fix the issue.
EDIT:
If you want conditionally execute the
powershell
task based on the length of parameter ‘envTests
‘ in the template YAML, you can add the conditional like as below in the template YAML.See below example:
A1
, thepowershell
task is executed as the values are provided to the parameter ‘envTests
‘.A2
, thepowershell
task is not executed as no values are provided to the parameter ‘envTests
‘.This is a slight variation of Bright Ran’s answer.
This might not be needed for this particular scenario, but in case you need to pass environment variables to a task that has some default variables, you can do something like this:
my-new-template.yml
azure-pipeline.yml
Running the pipeline: