Revolutionizing Azure Resource Lifecycle with Terraform v1.7.0: Introducing the 'Removed' Block

Copper Contributor

Context:

Let's say you have an Azure environment managed by Terraform, and it includes several Azure Virtual Machines (VMs). Over time, you decide to decommission a VM, but you don't want to destroy it immediately. Instead, you prefer to remove it from Terraform's state management while keeping the VM intact in Azure for archival or auditing purposes.

Traditional Approach:

Previously, you would have to use terraform state rm to manually remove the VM from the state file, a process that can be error-prone and lacks the visibility of Terraform's planning phase.

Using the removed Block:

With the new removed block, you can now handle this scenario more elegantly and safely. Here's how you might write the Terraform configuration for this:

 

 

resource "azurerm_virtual_machine" "example_vm" {
  # ... (VM configuration details) ...
}

# New 'removed' block usage
removed {
  from = azurerm_virtual_machine.example_vm

  lifecycle {
    destroy = false
  }
}

 

 

Explanation:

  • The azurerm_virtual_machine.example_vm represents an existing Azure VM in your Terraform configuration.
  • The removed block is used to indicate that this VM should be removed from Terraform's state management.
  • The destroy = false within the lifecycle sub-block tells Terraform not to destroy the actual VM in Azure when applying this change.

Benefits:

  • Safety and Predictability: You can run terraform plan to see how this change will impact your infrastructure without any immediate effect on the actual resources.
  • Ease of Use: This approach is more intuitive and reduces the risk of manual errors compared to using terraform state rm.
  • Better State Management: It provides a declarative way to manage the lifecycle of resources, aligning with Terraform's philosophy.

Conclusion:

This example demonstrates how the removed block can be used to manage Azure resources more effectively. It offers a safer and more predictable way to handle resource lifecycles, especially for resources that are being decommissioned but not immediately destroyed.

 

0 Replies