I'm using azure-sdk-for-python to create and delete VMs.
https://github.com/Azure/azure-sdk-for-python
http://azure-sdk-for-python.readthedocs.io/en/latest/
I've successfully managed to write the code to create and delete my VMs using the resource manager approach (not the classic).
The basic to create a VM can be seen here: http://azure-sdk-for-python.readthedocs.io/en/latest/resourcemanagementcomputenetwork.html
I'm not worried about deleting the resource group and the storage account, as I'm using the same for all my VMs.
To delete a the created VM I have something like this:
# 1. Delete the virtual machine
result = compute_client.virtual_machines.delete(
group_name,
vm_name
)
result.wait()
# 2. Delete the network interface
result = network_client.network_interfaces.delete(
group_name,
network_interface_name
)
result.wait()
# 3. Delete the ip
result = network_client.public_ip_addresses.delete(
group_name,
public_ip_address_name
)
result.wait()
As some know the data disks are not deleted along with its VM. I know it can be done with the Azure CLI: https://azure.microsoft.com/en-us/documentation/articles/storage-azure-cli/
azure storage blob delete -a <storage_account_name> -k <storage_account_key> -q vhds <data_disk>.vhd
But I don't know how to do it programmatically with azure-sdk-for-python. And I didn't want to depend on the Azure CLI as the rest of my code is using the python sdk.
I would appreciate some help on how to do it.
Thanks
You can leverage the Azure ComputeManagementClient's disks APIs to obtain list of disks associated with a VM and then iterate over them to delete the disks. Here's some sample code to achieve the same:
def delete_vm(self, vm_name, nic_name, group_name):
# Delete VM
print('Delete VM {}'.format(vm_name))
try:
async_vm_delete = self.compute_client.virtual_machines.delete(group_name, vm_name)
async_vm_delete.wait()
net_del_poller = self.network_client.network_interfaces.delete(group_name, nic_name)
net_del_poller.wait()
disks_list = self.compute_client.disks.list_by_resource_group(group_name)
disk_handle_list = []
for disk in disks_list:
if vm_name in disk.name:
async_disk_delete = self.compute_client.disks.delete(self.group_name, disk.name)
async_disk_handle_list.append(async_disk_delete)
print("Queued disks will be deleted now...")
for async_disk_delete in disk_handle_list:
async_disk_delete.wait()
except CloudError:
print('A VM delete operation failed: {}'.format(traceback.format_exc()))
return False
print("Deleted VM {}".format(vm_name))
return True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With