You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Terraform部署Azure Linux VM时remote exec报错找不到私钥怎么解决

解决Terraform Windows环境remote exec SSH密钥读取错误方案

核心配置写法

直接在remote-exec的connection块中使用如下配置,适配Windows PowerShell的路径解析规则:

resource "azurerm_linux_virtual_machine" "example" {
  # 你的VM原有配置保持不变
  name                = "example-vm"
  resource_group_name = azurerm_resource_group.example.name
  location            = azurerm_resource_group.example.location
  size                = "Standard_D2s_v3"
  admin_username      = "azureuser"
  admin_ssh_key {
    username   = "azureuser"
    public_key = file("~/.ssh/id_rsa.pub")
  }
  network_interface_ids = [azurerm_network_interface.example.id]
  os_disk {
    caching              = "ReadWrite"
    storage_account_type = "Premium_LRS"
  }
  source_image_reference {
    publisher = "Canonical"
    offer     = "0001-com-ubuntu-server-jammy"
    sku       = "22_04-lts"
    version   = "latest"
  }

  provisioner "remote-exec" {
    inline = [
      "sudo apt-get update -y",
      "sudo apt-get install -y your-package-name" # 替换为实际要安装的软件包
    ]

    connection {
      type        = "ssh"
      host        = self.public_ip_address
      user        = self.admin_username
      # 关键配置:pathexpand自动适配Windows用户目录路径,file读取私钥内容
      private_key = file(pathexpand("~/.ssh/id_rsa"))
      timeout     = "10m"
    }
  }
}

必须完成的Windows环境校验

  • 私钥必须为OpenSSH格式:如果使用PuTTY生成的.ppk格式密钥,需打开PuTTYgen,点击「Conversions」→「Export OpenSSH key」导出无密码的OpenSSH格式私钥,存储到C:\Users\你的用户名\.ssh\id_rsa路径
  • 私钥权限配置:右键私钥文件→「属性」→「安全」→「高级」,禁用继承,删除所有其他用户/组的权限,仅保留当前登录的Windows用户拥有「读取」权限
  • 路径确认:如果私钥不在默认.ssh目录,直接写绝对路径即可,示例:private_key = file(pathexpand("C:/my-secrets/ssh-private-key")),注意路径用正斜杠/或者双反斜杠\\

临时调试方案:测试阶段可以直接将私钥文本复制到private_key字段值中,验证连接正常后再换回文件读取方式,避免明文密钥泄露。

内容的提问来源于stack exchange,提问作者esngsrj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 15:06:00