Skip to content

Fix destroy command failure for environments in Created state - #53

Merged
josecelano merged 5 commits into
mainfrom
copilot/fix-destroy-command-created-state
Oct 27, 2025
Merged

josecelano merged 5 commits into
mainfrom
copilot/fix-destroy-command-created-state

Conversation

Copilot AI commented Oct 27, 2025 •

Copy link
Copy Markdown
Contributor

Fix Destroy Command: Handle Created State Gracefully ✅

Issue: #X (Subissue 8/10 of Epic #34)
Status: ✅ Complete - Ready for Merge


Summary

This PR fixes a critical bug where the destroy command failed when attempting to destroy environments in the Created state. The command unconditionally tried to destroy OpenTofu infrastructure that was never provisioned, resulting in "No such file or directory" errors.

Solution

The fix uses a simple and reliable approach: check if the OpenTofu build directory exists before attempting infrastructure destruction. If the directory doesn't exist, infrastructure destruction is skipped.

Changes Made

Files Modified:

  • src/application/command_handlers/destroy.rs - Core fix for destroy command
  • src/presentation/commands/create/mod.rs - Fixed pre-existing doctest bug
  1. Added should_destroy_infrastructure() helper function

    • Checks if environment.tofu_build_dir().exists()
    • Returns true if infrastructure should be destroyed, false otherwise
  2. Updated execute_destruction_with_tracking()

    • Made infrastructure destruction conditional based on directory existence
    • Added clear logging for both cases (destroying vs skipping)
    • State file cleanup always happens regardless
  3. Added 3 comprehensive unit tests

    • it_should_skip_infrastructure_destruction_when_tofu_build_dir_does_not_exist - Tests Created state handling
    • it_should_attempt_infrastructure_destruction_when_tofu_build_dir_exists - Tests Provisioned state (regression)
    • it_should_clean_up_state_files_regardless_of_infrastructure_state - Tests cleanup always happens
  4. Fixed doctest in create command module

    • Updated example to use correct function signature with CreateAction enum
    • Was referencing non-existent handle() function instead of handle_create_command()

Test Results

  • ✅ 974 existing tests pass - No regressions
  • ✅ 3 new unit tests added - Total of 46 destroy-related tests
  • ✅ 199 doctests pass - Including the fixed create command doctest
  • ✅ All linters pass - markdown, yaml, toml, cspell, clippy, rustfmt, shellcheck
  • ✅ Manual testing successful - Verified fix works as expected
  • ✅ Code review passed - All feedback addressed

Before and After

Aspect Before (Bug) After (Fixed)
Behavior Command fails with error Command succeeds
Error Message "Failed to start command 'tofu destroy': No such file or directory" None
Log Output Error traces "Skipping infrastructure destruction (environment was never provisioned)"
Environment State Transitions to DestroyFailed Transitions to Destroyed
User Experience Confusing, requires manual cleanup Clear, works as expected

Implementation Details

Why Directory Existence Check Works:

  • OpenTofu creates the build directory during provisioning
  • If the directory doesn't exist, no infrastructure was provisioned
  • Works reliably across all states and edge cases
  • Handles manual directory deletion gracefully
  • Maintains idempotency

Backward Compatibility:

  • ✅ Environments with provisioned infrastructure → Infrastructure destruction attempted (existing behavior preserved)
  • ✅ Environments in Created state → Infrastructure destruction skipped (new behavior, fixes current failure)
  • ✅ State file cleanup → Always happens (existing behavior preserved)

Architecture Compliance

  • ✅ Follows DDD layer separation (Application layer)
  • ✅ Uses existing error handling patterns
  • ✅ Maintains command handler pattern
  • ✅ Provides clear, actionable logging
  • ✅ No breaking changes to existing workflows
Original prompt

This section details on the original issue you should resolve

<issue_title>[Subissue 8/10] Fix Destroy Command: Handle Created State Gracefully</issue_title>
<issue_description># Fix Destroy Command: Handle Created State Gracefully

Epic Subissue: 8 of 9
Issue: #X (to be assigned)
Parent Epic: #34 - Create Environment Command
Related: Destroy Command Handler, Destroy Presentation Layer, Subissue 9 (Fix Working Directory Support - to be created)

Overview

Fix a critical bug in the destroy command where it fails when attempting to destroy environments in the Created state. The command unconditionally tries to destroy OpenTofu infrastructure that was never provisioned, causing the operation to fail with "No such file or directory" errors.

This bug prevents users from cleaning up newly created environments that were never provisioned, forcing manual cleanup or confusing error messages.

Note: This issue focuses only on the Created state handling bug. A separate issue (Subissue 9) will address the working directory parameter support. For manual testing in this issue, use the default working directory (environments in ./data/) to avoid the working directory bug.

Goals

  • Fix destroy command to handle Created state environments gracefully
  • Skip infrastructure destruction for environments that were never provisioned
  • Maintain backward compatibility with provisioned environment destruction
  • Add comprehensive tests for both Created and Provisioned state scenarios

🏗️ Architecture Requirements

DDD Layer: Application (command logic)
Module Path: src/application/command_handlers/destroy.rs
Pattern: Command Handler Pattern

Module Structure Requirements

  • Follow DDD layer separation (see docs/codebase-architecture.md)
  • Application layer handles state-aware logic
  • Use existing error handling patterns with .help() methods

Architectural Constraints

  • Destroy command handler must be state-aware
  • Infrastructure destruction should only happen when infrastructure exists
  • Error handling follows project conventions (see docs/contributing/error-handling.md)
  • Maintain idempotency of destroy operation

Anti-Patterns to Avoid

  • ❌ Assuming infrastructure always exists for all states
  • ❌ Breaking changes to existing destroy behavior for provisioned environments
  • ❌ Silent failures (always log when skipping infrastructure destruction)

Specifications

Current Behavior (Incorrect)

When destroying an environment in the Created state (never provisioned), the destroy command unconditionally attempts to run OpenTofu destroy operations:

// src/application/command_handlers/destroy.rs (execute_destruction_with_tracking)
fn execute_destruction_with_tracking(...) -> Result<...> {
    // Step 1: Destroy infrastructure via OpenTofu
    Self::destroy_infrastructure(opentofu_client)  // ❌ Fails for Created state
        .map_err(|e| (e, DestroyStep::DestroyInfrastructure))?;

    // Step 2: Clean up state files
    Self::cleanup_state_files(environment)
        .map_err(|e| (e, DestroyStep::CleanupStateFiles))?;

    Ok(())
}

This causes errors like:

Failed to start command 'tofu destroy -var-file=variables.tfvars -auto-approve': 
No such file or directory (os error 2)

The environment transitions to DestroyFailed state with this error context:

{
  "DestroyFailed": {
    "context": { ... },
    "state": {
      "context": {
        "failed_step": "DestroyInfrastructure",
        "error_kind": "CommandExecution",
        "error_summary": "Command execution failed: Failed to start command 'tofu destroy ...",
        ...
      }
    }
  }
}

Expected Behavior

The destroy command should be state-aware and skip infrastructure destruction for environments that never had infrastructure provisioned:

fn execute_destruction_with_tracking(
    environment: &Environment<Destroying>,
    opentofu_client: &Arc<OpenTofuClient>,
) -> Result<(), (DestroyCommandHandlerError, DestroyStep)> {
    // Only attempt infrastructure destruction if infrastructure was provisioned
    // States that had infrastructure: Provisioned, Configured, Released, Running
    // States that never had infrastructure: Created
    if should_destroy_infrastructure(environment) {
        info!(
            environment = %environment.name(),
            "Destroying provisioned infrastructure"
        );
        Self::destroy_infrastructure(opentofu_client)
            .map_err(|e| (e, DestroyStep::DestroyInfrastructure))?;
    } else {
        info!(
            environment = %environment.name(),
            "Skipping infrastructure destruction (environment was n...

</details>

- Fixes torrust/torrust-tracker-deployer#50

<!-- START COPILOT CODING AGENT TIPS -->
---

✨ Let Copilot coding agent [set things up for you](https://github.com/torrust/torrust-tracker-deployer/issues/new?title=✨+Set+up+Copilot+instructions&body=Configure%20instructions%20for%20this%20repository%20as%20documented%20in%20%5BBest%20practices%20for%20Copilot%20coding%20agent%20in%20your%20repository%5D%28https://gh.io/copilot-coding-agent-tips%29%2E%0A%0A%3COnboard%20this%20repo%3E&assignees=copilot) — coding agent works faster and does higher quality work when set up for your repo.

Copilot AI changed the title [WIP] Fix destroy command to handle created state gracefully Fix destroy command failure for environments in Created state Oct 27, 2025
Copilot AI requested a review from josecelano October 27, 2025 12:11
@josecelano

Copy link
Copy Markdown
Member

@copilot the testing workflow is failing:

failures:

---- src/presentation/commands/create/mod.rs - presentation::commands::create (line 22) stdout ----
error[E0425]: cannot find function `handle` in module `create`
 --> src/presentation/commands/create/mod.rs:27:25
  |
8 | if let Err(e) = create::handle(
  |                         ^^^^^^ not found in `create`
  |
help: consider importing this function
  |
2 + use torrust_tracker_deployer_lib::presentation::commands::destroy::handle;
  |
help: if you import `handle`, refer to it directly
  |
8 - if let Err(e) = create::handle(
8 + if let Err(e) = handle(
  |

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0425`.
Couldn't compile the test.

failures:
    src/presentation/commands/create/mod.rs - presentation::commands::create (line 22)

test result: FAILED. 198 passed; 1 failed; 1 ignored; 0 measured; 0 filtered out; finished in 40.50s

error: doctest failed, to rerun pass `-p torrust-tracker-deployer --doc`
Error: Process completed with exit code 101.

Copilot AI commented Oct 27, 2025

Copy link
Copy Markdown
Contributor Author

@copilot the testing workflow is failing:

...

Fixed in commit 0d9c043. The doctest was using an incorrect function signature - updated to use CreateAction enum with the correct handle_create_command() function. All 199 doctests now pass.

- Update all test fixtures to use absolute SSH key paths via CARGO_MANIFEST_DIR
- Fix E2E tests to use correct CLI structure: 'create environment' instead of 'create'
- Resolves test failures caused by relative path resolution issues
- Fixes ProcessRunner to include 'environment' subcommand in cargo run invocation

All 974 library tests and 4 E2E tests now pass successfully.
@josecelano
josecelano force-pushed the copilot/fix-destroy-command-created-state branch from 0d9c043 to 3e6fc3e Compare October 27, 2025 16:10
- Update doctest example to use CreateAction enum
- Correct function name from 'handle' to 'handle_create_command'
- Add proper imports for PathBuf and CreateAction
- Ensures doctest compiles and runs successfully

@josecelano josecelano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

ACK 668bf0b

@josecelano
josecelano marked this pull request as ready for review October 27, 2025 16:22
@josecelano
josecelano merged commit 3615e24 into main Oct 27, 2025
@josecelano
josecelano deleted the copilot/fix-destroy-command-created-state branch April 15, 2026 16:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants