Skip to content

[VM] az vm delete: raise ResourceNotFoundError when VM or resource group does not exist - #33795

Open
a0x1ab with Copilot wants to merge 3 commits into
devfrom
copilot/resolve-az-vm-delete-error
Open

[VM] az vm delete: raise ResourceNotFoundError when VM or resource group does not exist#33795
a0x1ab with Copilot wants to merge 3 commits into
devfrom
copilot/resolve-az-vm-delete-error

Conversation

Copilot AI commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

Related command
az vm delete

Description

az vm delete silently exits with code 0 when the target VM or resource group does not exist. Azure's REST API returns HTTP 204 for DELETE on non-existent resources (idempotent), so the CLI treated it as success — misleading users and automation pipelines.

Changes:

  • vm/operations/vm.py: Added VMDelete class extending _VMDelete that overrides pre_operations to call VMShow before deletion. If the VM is not found (HTTP 404), raises ResourceNotFoundError with a descriptive message.
  • vm/commands.py: Registers VMDelete in the command table to override the auto-generated vm delete command.
  • vm/tests/latest/test_custom_vm_commands.py: Unit tests covering the non-existent VM path and the happy path.

Testing Guide

# Before: exits 0 silently
az vm delete --resource-group nonexistent-rg -n nonexistent-vm --yes

# After: raises ResourceNotFoundError
# ERROR: The VM 'nonexistent-vm' under resource group 'nonexistent-rg' was not found.

History Notes

[VM] az vm delete: Raise ResourceNotFoundError when the specified VM or resource group does not exist.


This checklist is used to make sure that common guidelines for a pull request are followed.

@azure-client-tools-bot-prd

Copy link
Copy Markdown

Hi @copilot,
Since the current milestone time is less than 7 days, this pr will be reviewed in the next milestone.

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
There may be pipelines that require an authorized user to comment /azp run to run.

Copilot AI changed the title [WIP] Fix az vm delete command to return error for non-existent resources [VM] az vm delete: raise ResourceNotFoundError when VM or resource group does not exist Jul 27, 2026
Copilot AI requested a review from a0x1ab July 27, 2026 06:58
@azure-client-tools-agent

Copy link
Copy Markdown

Live test results — azdev test --live --series (changed test files only)

PASS

Selectors: test_custom_vm_commands (module)
PR head ref: copilot/resolve-az-vm-delete-error
PR head sha: 27cc6b6b68af09a502f91da51f3187d8af2b08e3
PR base ref: dev
New test files in PR: false

Changed test files run
src/azure-cli/azure/cli/command_modules/vm/tests/latest/test_custom_vm_commands.py

Workflow run: https://github.com/Azure/issue-sentinel/actions/runs/30244731207

Last 80 lines of azdev output

=============
| Run Tests |
=============


=====================
| Discovering Tests |
=====================

/home/runner/work/issue-sentinel/issue-sentinel/azure-cli/src/azure-cli/azure/cli/command_modules/identity/tests/latest/test_identity.py:18: SyntaxWarning: invalid escape sequence '\{'
  'resource_restriction_compute': '\{"providers":\["Microsoft.Compute"\]\}',
/home/runner/work/issue-sentinel/issue-sentinel/azure-cli/src/azure-cli/azure/cli/command_modules/identity/tests/latest/test_identity.py:19: SyntaxWarning: invalid escape sequence '\{'
  'resource_restriction_empty': '\{"providers":\[\]\}'
/home/runner/work/issue-sentinel/issue-sentinel/azure-cli/src/azure-cli/azure/cli/command_modules/vm/tests/latest/test_vm_commands.py:13533: SyntaxWarning: invalid escape sequence '\]'
  self.cmd('vmss application set -g {rg} -n {vmss} --app-version-ids {vid1} {vid2} --enable-automatic-upgrade True\]', checks=[

test index updated: /home/runner/.azdev/env_config/home/runner/work/issue-sentinel/issue-sentinel/.venv/test_index/latest.json

Test on modules: test_custom_vm_commands

WARNING: RUNNING TESTS LIVE
The tests are set to run against current profile "latest"
============================= test session starts ==============================
platform linux -- Python 3.12.13, pytest-9.1.1, pluggy-1.6.0 -- /home/runner/work/issue-sentinel/issue-sentinel/.venv/bin/python
cachedir: .pytest_cache
rootdir: /home/runner/work/issue-sentinel/issue-sentinel/azure-cli/src/azure-cli
plugins: xdist-3.8.0, forked-1.6.0
collecting ... collected 8 items

azure-cli/src/azure-cli/azure/cli/command_modules/vm/tests/latest/test_custom_vm_commands.py::TestVmCustom::test_get_access_extension_upgrade_info PASSED [ 12%]
azure-cli/src/azure-cli/azure/cli/command_modules/vm/tests/latest/test_custom_vm_commands.py::TestVmCustom::test_get_extension_instance_name PASSED [ 25%]
azure-cli/src/azure-cli/azure/cli/command_modules/vm/tests/latest/test_custom_vm_commands.py::TestVmCustom::test_get_extension_instance_name_when_type_none PASSED [ 37%]
azure-cli/src/azure-cli/azure/cli/command_modules/vm/tests/latest/test_custom_vm_commands.py::TestVmCustom::test_merge_secrets PASSED [ 50%]
azure-cli/src/azure-cli/azure/cli/command_modules/vm/tests/latest/test_custom_vm_commands.py::TestVMBootLog::test_vm_boot_log_handle_unicode PASSED [ 62%]
azure-cli/src/azure-cli/azure/cli/command_modules/vm/tests/latest/test_custom_vm_commands.py::TestVMBootLog::test_vm_boot_log_init_storage_sdk PASSED [ 75%]
azure-cli/src/azure-cli/azure/cli/command_modules/vm/tests/latest/test_custom_vm_commands.py::TestVMDeletePreOperations::test_pre_operations_raises_error_when_vm_not_found PASSED [ 87%]
azure-cli/src/azure-cli/azure/cli/command_modules/vm/tests/latest/test_custom_vm_commands.py::TestVMDeletePreOperations::test_pre_operations_succeeds_when_vm_exists PASSED [100%]

- generated xml file: /home/runner/work/issue-sentinel/issue-sentinel/test-output/results.xml -
============================== 8 passed in 0.42s ===============================

Posted by agent-assist live-test workflow.

@yonzhan

yonzhan commented Jul 27, 2026

Copy link
Copy Markdown
Collaborator

VM

@azure-client-tools-agent azure-client-tools-agent Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CI Failure Summary

The automated validation pipeline for this PR has 4 failing checks (with 11 checks still pending/queued as of this review, and 65 passing). The live-test workflow for the changed test file(s) already completed successfully.

Failed checks:

Please open the linked Azure Pipelines run logs for each failed check, identify the root cause (likely a test assertion depending on the previous az vm delete behavior/error type, or a recording mismatch caused by switching to ResourceNotFoundError), and update the implementation and/or the affected test cases (including any recorded test fixtures) so all Automation Full Test profiles and the Homebrew Formula check pass. Push a new commit once done.


Posted by agent-assist (autonomous bug-fix pipeline).

@a0x1ab

a0x1ab commented Jul 27, 2026

Copy link
Copy Markdown
Member

@copilot the automated CI and live-test review on this PR found failures. Please look into the requested changes here: #33795 (review) and push a fix.


Posted by agent-assist (autonomous bug-fix pipeline).

Copilot AI commented Jul 27, 2026

Copy link
Copy Markdown
Contributor Author

@copilot the automated CI and live-test review on this PR found failures. Please look into the requested changes here: #3...

Investigated the CI failures and found the root cause: the previous pre_operations approach called VMShow before deletion, which added an extra HTTP GET request. VCR (the test recording framework) consumes each cassette entry once, so the extra GET request caused failures in playback mode since the recordings didn't include it.

Fix (commit fix: use on_204 override): Instead of using pre_operations with VMShow, I now override VirtualMachinesDelete.on_204. When Azure returns HTTP 204 for a DELETE (which happens when the VM doesn't exist — an idempotent delete), the overridden on_204 raises ResourceNotFoundError with the VM name and resource group. This approach:

  • Makes no extra HTTP requests → doesn't affect existing recordings
  • Existing VM deletes return 202 (async) → on_204 is never called → no impact on happy path
  • Non-existent VM deletes return 204 → on_204 is now called → raises ResourceNotFoundError

@azure-client-tools-agent

Copy link
Copy Markdown

Live test results — azdev test --live --series (changed test files only)

PASS

Selectors: test_custom_vm_commands (module)
PR head ref: copilot/resolve-az-vm-delete-error
PR head sha: 4ff2faf768deaea7020e96eb78f1f5a6d5cc5ba3
PR base ref: dev
New test files in PR: false

Changed test files run
src/azure-cli/azure/cli/command_modules/vm/tests/latest/test_custom_vm_commands.py

Workflow run: https://github.com/Azure/issue-sentinel/actions/runs/30249353809

Last 80 lines of azdev output

=============
| Run Tests |
=============


=====================
| Discovering Tests |
=====================

/home/runner/work/issue-sentinel/issue-sentinel/azure-cli/src/azure-cli/azure/cli/command_modules/identity/tests/latest/test_identity.py:18: SyntaxWarning: invalid escape sequence '\{'
  'resource_restriction_compute': '\{"providers":\["Microsoft.Compute"\]\}',
/home/runner/work/issue-sentinel/issue-sentinel/azure-cli/src/azure-cli/azure/cli/command_modules/identity/tests/latest/test_identity.py:19: SyntaxWarning: invalid escape sequence '\{'
  'resource_restriction_empty': '\{"providers":\[\]\}'
/home/runner/work/issue-sentinel/issue-sentinel/azure-cli/src/azure-cli/azure/cli/command_modules/vm/tests/latest/test_vm_commands.py:13533: SyntaxWarning: invalid escape sequence '\]'
  self.cmd('vmss application set -g {rg} -n {vmss} --app-version-ids {vid1} {vid2} --enable-automatic-upgrade True\]', checks=[

test index updated: /home/runner/.azdev/env_config/home/runner/work/issue-sentinel/issue-sentinel/.venv/test_index/latest.json

Test on modules: test_custom_vm_commands

WARNING: RUNNING TESTS LIVE
The tests are set to run against current profile "latest"
============================= test session starts ==============================
platform linux -- Python 3.12.13, pytest-9.1.1, pluggy-1.6.0 -- /home/runner/work/issue-sentinel/issue-sentinel/.venv/bin/python
cachedir: .pytest_cache
rootdir: /home/runner/work/issue-sentinel/issue-sentinel/azure-cli/src/azure-cli
plugins: xdist-3.8.0, forked-1.6.0
collecting ... collected 7 items

azure-cli/src/azure-cli/azure/cli/command_modules/vm/tests/latest/test_custom_vm_commands.py::TestVmCustom::test_get_access_extension_upgrade_info PASSED [ 14%]
azure-cli/src/azure-cli/azure/cli/command_modules/vm/tests/latest/test_custom_vm_commands.py::TestVmCustom::test_get_extension_instance_name PASSED [ 28%]
azure-cli/src/azure-cli/azure/cli/command_modules/vm/tests/latest/test_custom_vm_commands.py::TestVmCustom::test_get_extension_instance_name_when_type_none PASSED [ 42%]
azure-cli/src/azure-cli/azure/cli/command_modules/vm/tests/latest/test_custom_vm_commands.py::TestVmCustom::test_merge_secrets PASSED [ 57%]
azure-cli/src/azure-cli/azure/cli/command_modules/vm/tests/latest/test_custom_vm_commands.py::TestVMBootLog::test_vm_boot_log_handle_unicode PASSED [ 71%]
azure-cli/src/azure-cli/azure/cli/command_modules/vm/tests/latest/test_custom_vm_commands.py::TestVMBootLog::test_vm_boot_log_init_storage_sdk PASSED [ 85%]
azure-cli/src/azure-cli/azure/cli/command_modules/vm/tests/latest/test_custom_vm_commands.py::TestVMDeleteOn204::test_on_204_raises_resource_not_found_error PASSED [100%]

- generated xml file: /home/runner/work/issue-sentinel/issue-sentinel/test-output/results.xml -
============================== 7 passed in 0.42s ===============================

Posted by agent-assist live-test workflow.

@azure-client-tools-agent azure-client-tools-agent Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated Review Summary

Result: PASS ✅

  • Live test (azdev --live): success
  • CI checks: 18/18 passed, 0 failed, 0 pending

All automated validation for this PR has passed. Flipping out of draft for human review.


Posted by agent-assist (autonomous bug-fix pipeline).

@azure-client-tools-agent
azure-client-tools-agent Bot marked this pull request as ready for review July 27, 2026 08:53
@azure-client-tools-agent
azure-client-tools-agent Bot requested a review from a team as a code owner July 27, 2026 08:53
Copilot AI review requested due to automatic review settings July 27, 2026 08:53
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
There may be pipelines that require an authorized user to comment /azp run to run.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Note

Copilot could not run the full agentic suite for this review because it was automatically requested on a bot-authored pull request. Request a review from Copilot under Reviewers to retry with the full agentic suite. Improved support for bot-authored pull requests is coming soon.

Adds a custom vm delete operation to change how HTTP 204 responses are handled, and includes a unit test asserting the new behavior.

Changes:

  • Introduce VMDelete operation overriding the 204-response handler to raise ResourceNotFoundError.
  • Register vm delete to use the new operation implementation.
  • Add a unit test verifying the raised error contains VM and resource group names.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 2 comments.

File Description
src/azure-cli/azure/cli/command_modules/vm/tests/latest/test_custom_vm_commands.py Adds a unit test asserting on_204 raises ResourceNotFoundError.
src/azure-cli/azure/cli/command_modules/vm/operations/vm.py Introduces VMDelete and overrides on_204 to raise ResourceNotFoundError.
src/azure-cli/azure/cli/command_modules/vm/commands.py Registers vm delete to use the new VMDelete operation.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +279 to +287
class VMDelete(_VMDelete):
class VirtualMachinesDelete(_VMDelete.VirtualMachinesDelete):
def on_204(self, session):
from azure.cli.core.azclierror import ResourceNotFoundError
raise ResourceNotFoundError(
"The VM '{}' under resource group '{}' was not found.".format(
str(self.ctx.args.name), str(self.ctx.args.resource_group)
)
)
Comment on lines +217 to +236
class TestVMDeleteOn204(unittest.TestCase):
"""Unit tests for VMDelete.VirtualMachinesDelete.on_204 behavior."""

def test_on_204_raises_resource_not_found_error(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"

# Instantiate the inner operation class with the mocked ctx
vm_delete_op = VMDelete.VirtualMachinesDelete(ctx=ctx)

with self.assertRaises(ResourceNotFoundError) as cm:
vm_delete_op.on_204(session=mock.MagicMock())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

act-observability-squad Auto-Assign Auto assign by bot Compute az vm/vmss/image/disk/snapshot

Projects

None yet

Development

Successfully merging this pull request may close these issues.

az vm delete Command Does Not Return an Error When the Specified Resource Group or Virtual Machine Does Not Exist

5 participants