When working with Terraform configurations, it’s essential to keep them modular and maintainable. One way to achieve this is by using modules. This post demonstrates how to refactor an Azure VM Terraform configuration to use modules, without causing any changes to the existing infrastructure. We will also cover how to use the terraform state mv command to update the Terraform state during the refactoring process.
Initial Azure VM Configuration
Here’s the initial Terraform configuration for an Azure VM:
Refactored Configuration with Modules
Here’s the refactored Terraform configuration that uses a module for the Azure VM:
main.tf
vm/variables.tf
vm/main.tf
Updating Terraform State with terraform state mv
After refactoring, use the terraform state mv command to update the Terraform state:
Move the azurerm_virtual_network resource:
Move the azurerm_subnet resource:
Move the azurerm_network_interface resource:
Move the azurerm_linux_virtual_machine resource:
After running these terraform state mv commands, your Terraform state should be updated to match the new module structure. Run terraform init, terraform validate, and terraform plan to verify that your refactored configuration does not cause any changes to your existing infrastructure.
In conclusion, refactoring your Terraform configuration to use modules can help improve maintainability and modularity. Using the terraform state mv command allows you to update your Terraform state during the refactoring process without causing disruptions to your existing infrastructure.