I'm using terraform to create a test vm on which to validate a packer built ARM image. In the azurerm_virtual_machine definition uses a storage_image_reference which seems to mean I must create the disk within this resource block.
Creation is fine but when destruction happens, the terraform leaves the disk behind resulting in an error. I'm new to Azure and puzzled because in AWS cleaning up the disk was trivial.
What's the right approach to build a VM from ARM image and have the disk destroyed with the vm?
resource "azurerm_virtual_machine" "this" {
name = local.name_prefix
location = var.location
resource_group_name = module.core.resource_group_name
network_interface_ids = [azurerm_network_interface.this.id]
vm_size = var.vm_size
tags = local.tags
storage_image_reference {
id = data.azurerm_shared_image_version.dev.id
}
storage_os_disk {
name = local.name_prefix
caching = "ReadWrite"
create_option = "FromImage"
managed_disk_type = var.vm_disk_type
}
os_profile {
computer_name = local.name_prefix
admin_username = var.admin_username
}
os_profile_linux_config {
disable_password_authentication = true
ssh_keys {
path = "/home/${var.admin_username}/.ssh/authorized_keys"
key_data = tls_private_key.this.public_key_openssh
}
}
Removing the managed storage OS disk of azure_virtual_machine using terrafrom
To delete an OS disk while destroying the virtual machine we need to opt an option while creating the VM in the portal.
By enabling this while destroying the VM it will make sure the disk also gets deleted.
This operation was performed by delete_os_disk_on_termination = true
parameter. This parameter is specifically designed for terraform only.
When you create an Azure Virtual Machine with Terraform, the OS disk attached to it is a "managed disk." By default. If you forget to specify this in the configuration terraform will not destroy the disk resource and it will still remain in the same RG resulting in spending increase for manual deletion.
In the query you already povisoned the resource so make sure you add this delete_os_disk_on_termination in the provisioning state itself so that it will make sure the Disk get deleted along with VM while running the terraform destroy command.
Refer: