This is a subject that I have not found much or any documentation on, so I wanted to share what I did. When creating the parameters to pass into a Template it can get very long, plus when two arrays depend on each other it can get very complex, so ironically a complex object makes this simple.
For my example I have a template where I would like to process Virtual Machines(VM) and its associated Disk if it has one. Therefore I need the VMs name and the Disk name for each, which can be done in many other ways, but this is for a specific example.
You could pass in the parameters as lists for VM names and Disk names as per below example, but then if a VM doesn’t have a disk or has many disk, the indexes would not line up.
- Name: virtualMachineNames
Type: object
Default: ['vm1','vm2']
- Name: diskNames
Type: object
Default: ['vm1Disk1','vm1Disk2','vm2Disk1']
Instead the object can be just that, but the catch I found is you can’t define a strict format. Therefore, I would suggest adding a comment to the file to demo a example format. In the below example I have added a default version just for this demo.
- Name: virtualMachines
Type: object
Default:
- Vm:
Name: 'vm1'
Disks: ['vm1Disk1','vm1Disk2']
- Vm:
Name: 'vm2'
Disks: ['vm2Disk1'']
You can keep all of you properties on one level, which removes the ‘vm’ part and still do the looping below, but for prettiness and as close to a JSON object, I like doing it like this.
We then can loop through these properties just like we would a list of items, and then we access the properties like an object.
- ${{ each vm in parameters.virtualMachines }}:
- task: AzureCLI@2
displayName: Check ${{ vm.name }} Disks
Using this ${{ vm.name }} you can get VM name but how to fetch disk names?
If I have to print in below format:
vm1: vm1Disk1
vm1: vm1Disk2
vm2: vm2Disk1
LikeLike
You would then use the other property name e.g. ${{ vm.disk }}
LikeLike