Terraform创建Azure Linux虚拟机失败:镜像不存在错误求助
问题场景
我跟着YouTube教程学习Terraform+Azure,在视频约53分钟处编写以下代码创建Linux虚拟机时触发错误:
resource "azurerm_linux_virtual_machine" "mtc-vm" { name = "mtc-vm" resource_group_name = azurerm_resource_group.mtc-rg.name location = azurerm_resource_group.mtc rg.location size = "Standard_B1s" admin_username = "adminuser" network_interface_ids = [azurerm_network_interface.mtc-nic.id] admin_ssh_key { username = "adminuser" public_key = file("~/.ssh/mtcazurekey.pub") } os_disk { caching = "ReadWrite" storage_account_type = "Standard_LRS" } source_image_reference { publisher = "Canonical" offer = "UbuntuServer" sku = "18.04-LTS" version = "latest" } tags = { "environment" = "dev" } }
错误信息
Error: creating Linux Virtual Machine: (Name "mtc-vm" / Resource Group "mtc-resources"): compute.VirtualMachinesclient#CreateOrUpdate: Failure sending request: StatusCode=404 -- Original Error: Code="Platform ImageNotFound" Message="The platform image 'Canonical:UbuntuServer:16.04 LTS:latest' is not available. Verify that all fields in the storage profile are correct. For more details about storage profile information, please refer to https://aka.ms/storageprofile" target="imageReference"
with azurerm_linux_virtual_machine.mtc-vm, on main.tf line 97, in resource "azurerm_linux_virtual_machine" "mtc-vm" : 97: resource "azurerm_linux_virtual_machine" "mtc-vm" {
问题分析与修复方案
- location字段拼写错误:代码中
azurerm_resource_group.mtc rg.location存在空格,应该改为azurerm_resource_group.mtc-rg.location。这个错误会导致Terraform无法正确获取资源组的区域,可能触发默认区域的镜像查找,而该区域没有代码中指定的镜像。 - 镜像版本问题:错误提示中显示的是16.04 LTS镜像找不到,而代码里写的是18.04-LTS,说明要么18.04-LTS在目标区域已停止提供,要么拼写错误导致匹配到了旧版本。建议更换为当前Azure支持的Ubuntu LTS版本,比如20.04-LTS或22.04-LTS。
修正后的代码
resource "azurerm_linux_virtual_machine" "mtc-vm" { name = "mtc-vm" resource_group_name = azurerm_resource_group.mtc-rg.name location = azurerm_resource_group.mtc-rg.location size = "Standard_B1s" admin_username = "adminuser" network_interface_ids = [azurerm_network_interface.mtc-nic.id] admin_ssh_key { username = "adminuser" public_key = file("~/.ssh/mtcazurekey.pub") } os_disk { caching = "ReadWrite" storage_account_type = "Standard_LRS" } source_image_reference { publisher = "Canonical" offer = "UbuntuServer" sku = "20.04-LTS" version = "latest" } tags = { "environment" = "dev" } }
额外验证方法
可以通过Azure CLI命令查看当前区域可用的Ubuntu镜像,确认正确的sku参数:
az vm image list --publisher Canonical --offer UbuntuServer --all --output table
内容的提问来源于stack exchange,提问作者EngineerX

