Skip to main content

Terraform Has No clean Command? Build Your Own

Updated 2 min readMarkdown
Terraform Has No clean Command? Build Your Own

If you frequently test Terraform configurations, local files and downloaded providers can accumulate. Coming from Maven, I missed having a simple mvn clean equivalent.

Terraform doesn't provide a built-in terraform clean command, so I created a small shell function called tfclean.

Disclaimer

Use tfclean carefully. It permanently deletes the listed files from the current working directory.

The .terraform.lock.hcl file records provider selections and checksums. Keeping it is generally recommended, especially in shared projects. Delete it only when you deliberately want to regenerate provider selections.

Deleting Terraform state files does not destroy the actual infrastructure. It can leave Terraform unable to manage existing resources safely.

If you need to destroy test infrastructure, run terraform destroy before running tfclean, while the state file is still available. Use this function primarily in disposable test environments.

The solution

Add the appropriate version to your shell configuration file.

For Bash (~/.bashrc):

# Terraform Cleanup Utility (tfclean)
tfclean() {
    rm -rf .terraform .terraform.tfstate.lock.info terraform.tfstate tfplan terraform.tfstate.backup

    read -r -p "Delete .terraform.lock.hcl too? [y/N] " answer

    if [[ "$answer" =~ ^[Yy]$ ]]; then
        rm -f .terraform.lock.hcl
        echo "Lock file deleted."
    else
        echo "Lock file kept."
    fi

    echo "Terraform cleanup complete."
}

For Zsh (~/.zshrc):

# Terraform Cleanup Utility (tfclean)
tfclean() {
    rm -rf .terraform .terraform.tfstate.lock.info terraform.tfstate tfplan terraform.tfstate.backup

    echo -n "Delete .terraform.lock.hcl too? [y/N] "
    read -r answer

    if [[ "$answer" =~ ^[Yy]$ ]]; then
        rm -f .terraform.lock.hcl
        echo "Lock file deleted."
    else
        echo "Lock file kept."
    fi

    echo "Terraform cleanup complete."
}

Reload your configuration:

source ~/.bashrc  # Bash
# or
source ~/.zshrc   # Zsh

Run tfclean from your Terraform project directory. It removes the listed artifacts and asks whether to delete .terraform.lock.hcl.

  • y — delete the lock file.
  • n or Enter — keep it.

Why this solution?

A shell function turns a long cleanup command into a single reusable command. Unlike a basic alias, it supports interactive prompts and conditional behavior.

The lock file is optional because not every cleanup should remove it.

2 views

About the author

  • I am a Cloud Engineer driven by curiosity, strong instincts, and attention to detail. Experienced across infrastructure, automation, and operations, with a love for problem-solving, teaching, and building trust. Outside work, I enjoy travel, photography, long drives, swimming, and exploring the blend of art, science, and spirituality.

No comments yet. Be the first to comment.