如何使用Terraform在Azure虚拟机上创建SSH密钥?

时间:2019-09-13 18:11:49

标签: azure terraform

我想使用Terraform在Azure虚拟机上创建新的SSH密钥吗?

我尝试过但是没用。

provisioner "remote-exec" {
  inline = [
      "sudo apt-get update",
      "cat /dev/zero | ssh-keygen -q -N ''"
  ]
}
}

出现此错误。

azurerm_virtual_machine.terraform-app-VM: Still creating... [5m30s elapsed]
azurerm_virtual_machine.terraform-app-VM (remote-exec): Connecting to remote host via SSH...
azurerm_virtual_machine.terraform-app-VM (remote-exec):   Host:
azurerm_virtual_machine.terraform-app-VM (remote-exec):   User: root
azurerm_virtual_machine.terraform-app-VM (remote-exec):   Password: false
azurerm_virtual_machine.terraform-app-VM (remote-exec):   Private key: false
azurerm_virtual_machine.terraform-app-VM (remote-exec):   Certificate: false
azurerm_virtual_machine.terraform-app-VM (remote-exec):   SSH Agent: true
azurerm_virtual_machine.terraform-app-VM (remote-exec):   Checking Host Key: false
azurerm_virtual_machine.terraform-app-VM: Still creating... [5m40s elapsed]


Error: timeout - last error: SSH authentication failed (root@:22): ssh: handshake failed: ssh: unable to authenticate, attempted methods [none publickey], no supported methods remain

1 个答案:

答案 0 :(得分:0)

您应该使用resource "azurerm_virtual_machine_extension"。它不需要SSH密钥。像这样:

resource "azurerm_virtual_machine_extension" "test" {
  name                 = "<some_name>"
  location             = "<resource_group_location>"
  resource_group_name  = "${azurerm_resource_group.<resource_group>.name}"
  virtual_machine_name = "${azurerm_virtual_machine.<vm>.name}"
  publisher            = "Microsoft.Azure.Extensions"
  type                 = "CustomScript"
  type_handler_version = "2.0"

  settings = <<SETTINGS
    {
        "commandToExecute": "<your_command>"
    }
SETTINGS
}

注意,这只是单个命令执行。如果要执行多个命令,则可以创建一个Shell脚本,将其上传(这样可以公开访问)并执行以下操作:

resource "azurerm_virtual_machine_extension" "test" {
  name                 = "<some_name>"
  location             = "<resource_group_location>"
  resource_group_name  = "${azurerm_resource_group.<resource_group>.name}"
  virtual_machine_name = "${azurerm_virtual_machine.<vm>.name}"
  publisher            = "Microsoft.Azure.Extensions"
  type                 = "CustomScript"
  type_handler_version = "2.0"

  settings = <<SETTINGS
    {
    "fileUris": ["https://url/to/file/<file>.sh"],
    "commandToExecute": "sh <file>.sh"
    }
SETTINGS
}