Azure-Samples/virtual-machines-python-manage

Detach Data Disk on line 155 in examples.py is not doing anything

nkv16786 opened this issue · 5 comments

Detach data disk

    print('\nDetach Data Disk')
    data_disks = virtual_machine.storage_profile.data_disks
    data_disks[:] = [disk for disk in data_disks if disk.name != 'mydatadisk1']
    async_vm_update = compute_client.virtual_machines.create_or_update(
        GROUP_NAME,
        VM_NAME,
        virtual_machine
    )
    virtual_machine = async_vm_update.result()

Yes it does detach the disk. Why do you think it doesn't?

vm.storage_profile.data_disks.remove()

We have to use this along with your code to remove
Please correct me if i am wrong

No, this line is doing it:
data_disks[:] = [disk for disk in data_disks if disk.name != 'mydatadisk1']

This means:

  • [:] : replace in place, in the same list
  • if disk.name != 'mydatadisk1'] same list as before, but without disk 'mydatadisk1'

If you want to use remove, you will have to find the element before:

for disk in vm.storage_profile.data_disks:
    if disk.name == 'mydatadisk1':
        break
else:
    disk = None
if disk:
    vm.storage_profile.data_disks.remove(disk)

That's longer than the one line version. And don't try to remove while iterating on the list :)

Ok thanks for clarifying :)

No problem :)