I have a PowerShell script in my Azure DevOps pipeline:
- task: PowerShell@2
displayName: Get_records
inputs:
targetType: 'inline'
script: |
<...>
$records.Records
$records.Records is some variable which contains array of records. I need to use this data this way: for each record in this array I need to perfome several tasks within one job. Something like this:
stages:
- stage: stage_1
jobs:
- job: Job_1
- task: PowerShell@2
displayName: Get_records
inputs:
targetType: 'inline'
script: |
<..getting this records..>
$records.Records
- ${{each records in variables.records.Records}}:
- task: not_powershell
displayName: name1
inputs:
AsyncOperation: true
MaxAsyncWaitTime: '60'
- task: not_powershell
displayName: name2
inputs:
AsyncOperation: true
MaxAsyncWaitTime: '60'
How can I do that? There are a couple questions about this:
- How to use '$records.Records' variable in foreach loop? Must I save variable before using? If yes - how to save an array?
- If it is imposible to do it this way, probably there are some ways around, for example use several stages, jobs... etc?
CodePudding user response:
No, you can't. It only works for parameters, not variables:
This is because:
- before it runs, the yaml is parsed and compiled into a pipeline structure, with all the stages, jobs and tasks defined. This is the point when the loop condition is evaluated, and the loop is expanded into multiple stages/jobs/tasks.
- dynamic runtime variables are not yet available at compile-time, so they cannot be used at this point to define the each loop.
- at runtime, when the dynamic variable is available, the pipeline structure is already fixed, so it is not possible to add extra tasks at this point.
Workaround
You can't loop over a dynamic array variable in the pipeline; but one place you can do so is within a task, for example within a powershell script:
- task: PowerShell@2
displayName: Loop Over Records
inputs:
targetType: 'inline'
script: |
# first, get the records
ForEach ($record in $records.Records) {
# do something with $record
}
That isn't as powerful as a pipeline loop, with all the different types of non-powershell tasks available, but it might be the only way to loop over this array.