Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/azure-cli/azure/cli/command_modules/vm/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,8 +181,9 @@ def load_command_table(self, _):
g.generic_update_command('update', getter_name='get_vm_to_update_by_aaz', setter_name='update_vm', setter_type=compute_custom, command_type=compute_custom, supports_no_wait=True, validator=process_vm_update_namespace)
g.wait_command('wait', getter_name='get_instance_view', getter_type=compute_custom)

from .operations.vm import VMCapture
from .operations.vm import VMCapture, VMDelete
self.command_table['vm capture'] = VMCapture(loader=self)
self.command_table['vm delete'] = VMDelete(loader=self)

with self.command_group('vm availability-set') as g:
g.custom_command('create', 'create_av_set', table_transformer=deployment_validate_table_format, supports_no_wait=True, exception_handler=handle_template_based_exception)
Expand Down
17 changes: 16 additions & 1 deletion src/azure-cli/azure/cli/command_modules/vm/operations/vm.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from azure.cli.core.aaz import AAZStrType
from ..aaz.latest.vm import (Show as _VMShow, ListSizes as _VMListSizes, Patch as _VMPatch,
Update as _VMUpdate, Capture as _VMCapture, Create as _VMCreate,
ListUsage as _VMListUsage)
ListUsage as _VMListUsage, Delete as _VMDelete)
from .._vm_utils import IdentityType

logger = get_logger(__name__)
Expand Down Expand Up @@ -265,6 +265,21 @@ def _output(self, *args, **kwargs):
return result, next_link


class VMDelete(_VMDelete):
def pre_operations(self):
from azure.cli.core.azclierror import ResourceNotFoundError
args = self.ctx.args
show_cmd = VMShow(cli_ctx=self.cli_ctx)
try:
show_cmd(command_args={"resource_group": str(args.resource_group), "vm_name": str(args.name)})
except ResourceNotFoundError as e:
raise ResourceNotFoundError(
"The VM '{}' under resource group '{}' was not found.".format(
str(args.name), str(args.resource_group)
)
) from e


def convert_show_result_to_snake_case(result):
new_result = {}
if "id" in result:
Expand Down

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -15186,6 +15186,93 @@ interactions:
status:
code: 200
message: ''
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
CommandName:
- vm delete
Connection:
- keep-alive
ParameterSetName:
- -g -n -y
User-Agent:
- AZURECLI/2.86.0 azsdk-python-core/1.39.0 Python/3.12.10 (Windows-11-10.0.26200-SP0)
method: GET
uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/cli_vm_vmss_extension_autoupgrade_000001/providers/Microsoft.Compute/virtualMachines/vm1000002?api-version=2026-04-01
response:
body:
string: "{\r\n \"name\": \"vm1000002\",\r\n \"id\": \"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/cli_vm_vmss_extension_autoupgrade_000001/providers/Microsoft.Compute/virtualMachines/vm1000002\",\r\n
\ \"type\": \"Microsoft.Compute/virtualMachines\",\r\n \"location\": \"eastus\",\r\n
\ \"tags\": {},\r\n \"identity\": {\r\n \"type\": \"SystemAssigned\",\r\n
\ \"principalId\": \"790ab855-19fa-48fb-bab9-4c9a4046f5a2\",\r\n \"tenantId\":
\"ed94de55-1f87-4278-9651-525e7ba467d6\"\r\n },\r\n \"properties\": {\r\n
\ \"hardwareProfile\": {\r\n \"vmSize\": \"Standard_D2s_v3\"\r\n },\r\n
\ \"provisioningState\": \"Succeeded\",\r\n \"vmId\": \"7cadb1ba-f002-4889-812d-0db5467ef2f0\",\r\n
\ \"storageProfile\": {\r\n \"imageReference\": {\r\n \"publisher\":
\"canonical\",\r\n \"offer\": \"0001-com-ubuntu-server-focal\",\r\n
\ \"sku\": \"20_04-lts-gen2\",\r\n \"version\": \"latest\",\r\n
\ \"exactVersion\": \"20.04.202505200\"\r\n },\r\n \"osDisk\":
{\r\n \"osType\": \"Linux\",\r\n \"name\": \"vm1000002_OsDisk_1_63fbe82de9c6449ea15f5f0a74381c36\",\r\n
\ \"createOption\": \"FromImage\",\r\n \"caching\": \"ReadWrite\",\r\n
\ \"managedDisk\": {\r\n \"storageAccountType\": \"Premium_LRS\",\r\n
\ \"id\": \"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/cli_vm_vmss_extension_autoupgrade_000001/providers/Microsoft.Compute/disks/vm1000002_OsDisk_1_63fbe82de9c6449ea15f5f0a74381c36\"\r\n
\ },\r\n \"deleteOption\": \"Detach\",\r\n \"diskSizeGB\":
30\r\n },\r\n \"dataDisks\": [],\r\n \"diskControllerType\":
\"SCSI\"\r\n },\r\n \"osProfile\": {\r\n \"computerName\": \"vm1000002\",\r\n
\ \"adminUsername\": \"azureuser\",\r\n \"linuxConfiguration\": {\r\n
\ \"disablePasswordAuthentication\": false,\r\n \"provisionVMAgent\":
true,\r\n \"patchSettings\": {\r\n \"patchMode\": \"ImageDefault\",\r\n
\ \"assessmentMode\": \"ImageDefault\"\r\n }\r\n },\r\n
\ \"secrets\": [],\r\n \"allowExtensionOperations\": true,\r\n \"requireGuestProvisionSignal\":
true\r\n },\r\n \"securityProfile\": {\r\n \"uefiSettings\": {\r\n
\ \"secureBootEnabled\": true,\r\n \"vTpmEnabled\": true\r\n
\ },\r\n \"securityType\": \"TrustedLaunch\"\r\n },\r\n \"networkProfile\":
{\"networkInterfaces\":[{\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/cli_vm_vmss_extension_autoupgrade_000001/providers/Microsoft.Network/networkInterfaces/vm1000002VMNic\"}]},\r\n
\ \"timeCreated\": \"2026-05-07T07:51:58.7197975+00:00\"\r\n },\r\n \"etag\":
\"\\\"2\\\"\",\r\n \"resources\": [\r\n {\r\n \"name\": \"GuestAttestation\",\r\n
\ \"id\": \"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/cli_vm_vmss_extension_autoupgrade_000001/providers/Microsoft.Compute/virtualMachines/vm1000002/extensions/GuestAttestation\",\r\n
\ \"type\": \"Microsoft.Compute/virtualMachines/extensions\",\r\n \"location\":
\"eastus\",\r\n \"properties\": {\r\n \"autoUpgradeMinorVersion\":
true,\r\n \"provisioningState\": \"Succeeded\",\r\n \"enableAutomaticUpgrade\":
true,\r\n \"publisher\": \"Microsoft.Azure.Security.LinuxAttestation\",\r\n
\ \"type\": \"GuestAttestation\",\r\n \"typeHandlerVersion\":
\"1.0\"\r\n }\r\n }\r\n ]\r\n}"
headers:
cache-control:
- no-cache
content-length:
- '3127'
content-type:
- application/json; charset=utf-8
date:
- Thu, 07 May 2026 07:55:31 GMT
etag:
- '"2"'
expires:
- '-1'
pragma:
- no-cache
strict-transport-security:
- max-age=31536000; includeSubDomains
x-cache:
- CONFIG_NOCACHE
x-content-type-options:
- nosniff
x-ms-need-to-refresh-epl-cache:
- 'False'
x-ms-ratelimit-remaining-resource:
- Microsoft.Compute/LowCostGetSubscriptionMaximum;23997,Microsoft.Compute/LowCostGetResource;27
x-ms-ratelimit-remaining-subscription-global-reads:
- '3749'
x-msedge-ref:
- 'Ref A: 2B2F61C3E3CA46908CD516E9EC75D521 Ref B: SG2AA1040520042 Ref C: 2026-05-07T07:55:31Z'
status:
code: 200
message: ''
- request:
body: null
headers:
Expand Down Expand Up @@ -15353,6 +15440,93 @@ interactions:
status:
code: 200
message: ''
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
CommandName:
- vm delete
Connection:
- keep-alive
ParameterSetName:
- -g -n -y
User-Agent:
- AZURECLI/2.86.0 azsdk-python-core/1.39.0 Python/3.12.10 (Windows-11-10.0.26200-SP0)
method: GET
uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/cli_vm_vmss_extension_autoupgrade_000001/providers/Microsoft.Compute/virtualMachines/vm2000003?api-version=2026-04-01
response:
body:
string: "{\r\n \"name\": \"vm2000003\",\r\n \"id\": \"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/cli_vm_vmss_extension_autoupgrade_000001/providers/Microsoft.Compute/virtualMachines/vm2000003\",\r\n
\ \"type\": \"Microsoft.Compute/virtualMachines\",\r\n \"location\": \"eastus\",\r\n
\ \"tags\": {},\r\n \"identity\": {\r\n \"type\": \"SystemAssigned\",\r\n
\ \"principalId\": \"c8a79030-ee52-4881-9aba-53922efa5981\",\r\n \"tenantId\":
\"ed94de55-1f87-4278-9651-525e7ba467d6\"\r\n },\r\n \"properties\": {\r\n
\ \"hardwareProfile\": {\r\n \"vmSize\": \"Standard_D2s_v3\"\r\n },\r\n
\ \"provisioningState\": \"Succeeded\",\r\n \"vmId\": \"ccdb1f8a-dc46-4866-9071-3f8c1133b12a\",\r\n
\ \"storageProfile\": {\r\n \"imageReference\": {\r\n \"publisher\":
\"canonical\",\r\n \"offer\": \"0001-com-ubuntu-server-focal\",\r\n
\ \"sku\": \"20_04-lts-gen2\",\r\n \"version\": \"latest\",\r\n
\ \"exactVersion\": \"20.04.202505200\"\r\n },\r\n \"osDisk\":
{\r\n \"osType\": \"Linux\",\r\n \"name\": \"vm2000003_OsDisk_1_129a906a88db45899526463794e60456\",\r\n
\ \"createOption\": \"FromImage\",\r\n \"caching\": \"ReadWrite\",\r\n
\ \"managedDisk\": {\r\n \"storageAccountType\": \"Premium_LRS\",\r\n
\ \"id\": \"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/cli_vm_vmss_extension_autoupgrade_000001/providers/Microsoft.Compute/disks/vm2000003_OsDisk_1_129a906a88db45899526463794e60456\"\r\n
\ },\r\n \"deleteOption\": \"Detach\",\r\n \"diskSizeGB\":
30\r\n },\r\n \"dataDisks\": [],\r\n \"diskControllerType\":
\"SCSI\"\r\n },\r\n \"osProfile\": {\r\n \"computerName\": \"vm2000003\",\r\n
\ \"adminUsername\": \"azureuser\",\r\n \"linuxConfiguration\": {\r\n
\ \"disablePasswordAuthentication\": false,\r\n \"provisionVMAgent\":
true,\r\n \"patchSettings\": {\r\n \"patchMode\": \"ImageDefault\",\r\n
\ \"assessmentMode\": \"ImageDefault\"\r\n }\r\n },\r\n
\ \"secrets\": [],\r\n \"allowExtensionOperations\": true,\r\n \"requireGuestProvisionSignal\":
true\r\n },\r\n \"securityProfile\": {\r\n \"uefiSettings\": {\r\n
\ \"secureBootEnabled\": true,\r\n \"vTpmEnabled\": true\r\n
\ },\r\n \"securityType\": \"TrustedLaunch\"\r\n },\r\n \"networkProfile\":
{\"networkInterfaces\":[{\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/cli_vm_vmss_extension_autoupgrade_000001/providers/Microsoft.Network/networkInterfaces/vm2000003VMNic\"}]},\r\n
\ \"timeCreated\": \"2026-05-07T07:54:16.1775515+00:00\"\r\n },\r\n \"etag\":
\"\\\"2\\\"\",\r\n \"resources\": [\r\n {\r\n \"name\": \"GuestAttestation\",\r\n
\ \"id\": \"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/cli_vm_vmss_extension_autoupgrade_000001/providers/Microsoft.Compute/virtualMachines/vm2000003/extensions/GuestAttestation\",\r\n
\ \"type\": \"Microsoft.Compute/virtualMachines/extensions\",\r\n \"location\":
\"eastus\",\r\n \"properties\": {\r\n \"autoUpgradeMinorVersion\":
true,\r\n \"provisioningState\": \"Succeeded\",\r\n \"enableAutomaticUpgrade\":
false,\r\n \"publisher\": \"Microsoft.Azure.Security.LinuxAttestation\",\r\n
\ \"type\": \"GuestAttestation\",\r\n \"typeHandlerVersion\":
\"1.0\"\r\n }\r\n }\r\n ]\r\n}"
headers:
cache-control:
- no-cache
content-length:
- '3128'
content-type:
- application/json; charset=utf-8
date:
- Thu, 07 May 2026 07:56:05 GMT
etag:
- '"2"'
expires:
- '-1'
pragma:
- no-cache
strict-transport-security:
- max-age=31536000; includeSubDomains
x-cache:
- CONFIG_NOCACHE
x-content-type-options:
- nosniff
x-ms-need-to-refresh-epl-cache:
- 'False'
x-ms-ratelimit-remaining-resource:
- Microsoft.Compute/LowCostGetSubscriptionMaximum;23997,Microsoft.Compute/LowCostGetResource;27
x-ms-ratelimit-remaining-subscription-global-reads:
- '3749'
x-msedge-ref:
- 'Ref A: 2B2F61C3E3CA46908CD516E9EC75D521 Ref B: SG2AA1040520042 Ref C: 2026-05-07T07:55:31Z'
status:
code: 200
message: ''
- request:
body: null
headers:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -214,5 +214,54 @@ def __init__(self, is_linux, version):
self.type_handler_version = version


class TestVMDeletePreOperations(unittest.TestCase):
"""Unit tests for VMDelete.pre_operations behavior."""

def test_pre_operations_raises_resource_not_found_error_when_vm_missing(self):
from azure.cli.core.azclierror import ResourceNotFoundError
from azure.cli.command_modules.vm.operations.vm import VMDelete

cli_ctx = DummyCli()
vm_delete = VMDelete(cli_ctx=cli_ctx)

# Simulate the ctx that would be set during command execution
ctx = mock.MagicMock()
ctx.args.name = "nonexistent-vm"
ctx.args.resource_group = "nonexistent-rg"
vm_delete.ctx = ctx

mock_show_instance = mock.MagicMock()
mock_show_instance.side_effect = ResourceNotFoundError("VM not found")
with mock.patch(
'azure.cli.command_modules.vm.operations.vm.VMShow',
return_value=mock_show_instance,
):
with self.assertRaises(ResourceNotFoundError) as cm:
vm_delete.pre_operations()

self.assertIn("nonexistent-vm", str(cm.exception))
self.assertIn("nonexistent-rg", str(cm.exception))

def test_pre_operations_succeeds_when_vm_exists(self):
from azure.cli.core.azclierror import ResourceNotFoundError
from azure.cli.command_modules.vm.operations.vm import VMDelete

cli_ctx = DummyCli()
vm_delete = VMDelete(cli_ctx=cli_ctx)

ctx = mock.MagicMock()
ctx.args.name = "existing-vm"
ctx.args.resource_group = "existing-rg"
vm_delete.ctx = ctx

mock_show_instance = mock.MagicMock()
with mock.patch(
'azure.cli.command_modules.vm.operations.vm.VMShow',
return_value=mock_show_instance,
):
# Should not raise
vm_delete.pre_operations()


if __name__ == '__main__':
unittest.main()
Loading