Azure DevOps loop a complex object

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

One thought on “Azure DevOps loop a complex object

Leave a message please

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.