Не удается подключиться через SSH к виртуальной машине Azure

#azure #terraform #azure-virtual-machine

#azure #terraform #azure-virtual-machine

Вопрос:

Я создал виртуальную машину Azure с помощью Terraform:

 resource "azurerm_network_security_group" "aks-nfs-sg" {
  name                = "aks-nfs-sg"
  location            = data.azurerm_resource_group.resources.location
  resource_group_name = data.azurerm_resource_group.resources.name

  security_rule {
    name                       = "Allow SSH"
    priority                   = 100
    direction                  = "Inbound"
    access                     = "Allow"
    protocol                   = "Tcp"
    source_port_range          = "22"
    destination_port_range     = "*"
    source_address_prefix      = "*"
    destination_address_prefix = "*"
  }

  tags = {
    environment = "Production"
  }
}

resource "azurerm_network_interface_security_group_association" "aks-nfs" {
  network_interface_id      = azurerm_network_interface.aks-nfs-nic.id
  network_security_group_id = azurerm_network_security_group.aks-nfs-sg.id
}

resource "azurerm_public_ip" "aks-nfs-public-ip" {
  name                = "aks-nfs-public-ip"
  location            = data.azurerm_resource_group.resources.location
  resource_group_name = data.azurerm_resource_group.resources.name
  allocation_method   = "Static"

  tags = {
    environment = "Production"
  }
}

resource "azurerm_network_interface" "aks-nfs-nic" {
  name                = "aks-nfs-nic"
  location            = data.azurerm_resource_group.resources.location
  resource_group_name = data.azurerm_resource_group.resources.name

  ip_configuration {
    name                          = "aks-nfs-ip"
    subnet_id                     = azurerm_subnet.aks-default.id
    private_ip_address_allocation = "Dynamic"
    public_ip_address_id          = azurerm_public_ip.aks-nfs-public-ip.id
  }
}

resource "azurerm_virtual_machine" "aks-nfs-vm" {
  name                             = "aks-nfs"
  location                         = data.azurerm_resource_group.resources.location
  resource_group_name              = data.azurerm_resource_group.resources.name
  network_interface_ids            = [azurerm_network_interface.aks-nfs-nic.id]
  vm_size                          = "Standard_DS1_v2"
  delete_os_disk_on_termination    = true
  delete_data_disks_on_termination = false

  storage_image_reference {
    publisher = "Canonical"
    offer     = "UbuntuServer"
    sku       = "16.04-LTS"
    version   = "latest"
  }

  storage_os_disk {
    name              = "aks-nfs-os"
    caching           = "ReadWrite"
    create_option     = "FromImage"
    managed_disk_type = "Standard_LRS"
  }

  os_profile {
    computer_name  = "aks-nfs"
    admin_username = "theuser"
    admin_password = var.nfs-admin-password
  }

  os_profile_linux_config {
    disable_password_authentication = false

    ssh_keys {
      key_data = file("~/.ssh/thesuer/aks-nfs.pub")
      path     = "/home/theuser/.ssh/authorized_keys"
    }
  }
  tags = {
    environment = "production"
  }
}
 

Но время ожидания SSH истекло. Он складывается на этом:

 OpenSSH_8.1p1, LibreSSL 2.7.3
debug1: Reading configuration data /Users/user/.ssh/config
debug1: /Users/user/.ssh/config line 65: Applying options for ssh-key
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 47: Applying options for *
debug1: Connecting to xx.xx.xx.xxx [xx.xx.xx.xxx] port 22.
debug1: Connection established.
debug1: identity file /Users/user/.ssh/aks-nfs type 0
debug1: identity file /Users/user/.ssh/aks-nfs-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_8.1
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.2p2 Ubuntu-4ubuntu2.10
debug1: match: OpenSSH_7.2p2 Ubuntu-4ubuntu2.10 pat OpenSSH_7.0*,OpenSSH_7.1*,OpenSSH_7.2*,OpenSSH_7.3*,OpenSSH_7.4*,OpenSSH_7.5*,OpenSSH_7.6*,OpenSSH_7.7* compat 0x04000002
debug1: Authenticating to 51.13.36.135:22 as 'xxx-user'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: algorithm: curve25519-sha256@libssh.org
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:qYLAJ4VU/K6Yg5HZwfhBgq0/yZ qTugDHFzPlhRWfiSEQ
debug1: Host 'xx.xx.xx.xxx' is known and matches the ECDSA host key.
debug1: Found key in /Users/user/.ssh/known_hosts:316
debug1: rekey out after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: rekey in after 134217728 blocks
debug1: Will attempt key: /Users/user/.ssh/xxx/aks-nfs RSA SHA256:Nj MtW5gdvVgT62CzMnfnwGsjMjlEH2fMkfpZdl9VOh2E explicit
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<rsa-sha2-256,rsa-sha2-512>
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,password
debug1: Next authentication method: publickey
debug1: Offering public key: /Users/user/.ssh/xxx/aks-nfs RSA SHA256:Nj MtW5gdvVgfT62CzMnnwGsfjMjlEH2MkfpZdl9VOh2E explicit
debug1: Server accepts key: /Users/user/.ssh/xxx/aks-nfs RSA SHA256:Nj MtW5gdvVgT62CzfMnnwGsjMjlEHf2MkfpZdl9VOh2E explicit
debug1: Authentication succeeded (publickey).
Authenticated to xx.xx.xx.xxx ([xx.xx.xx.xxx]:22).
debug1: channel 0: new [client-session]
debug1: Requesting no-more-sessions@openssh.com
debug1: Entering interactive session.
debug1: pledge: network
debug1: client_input_global_request: rtype hostkeys-00@openssh.com want_reply 0
debug1: Sending environment.
debug1: Sending env LANG = en_US.UTF-8
 

Почему это так? И как я могу, наконец, подключиться к виртуальной машине.

Ответ №1:

Я протестировал ваш код в своей среде, и он успешно развертывается, но при выполнении SSH он выдает ошибку с истечением времени ожидания соединения.

Сначала я изменил его, используя azurerm_linux_virtual_machine вместо azurerm_virtual_machine документации as Terraform, упомянутой ниже, но это все равно не удалось.

azurerm_virtual_machine Ресурс был заменен azurerm_linux_virtual_machine azurerm_windows_virtual_machine ресурсами и . Существующий azurerm_virtual_machine ресурс будет по-прежнему доступен во всех версиях 2.x, однако он находится в состоянии «замороженной функции» для поддержания совместимости — вместо azurerm_linux_virtual_machine этого в ресурсы и будут добавлены новые функциональные azurerm_windows_virtual_machine возможности.

Итак, в качестве решения я снова протестировал, удалив NSG rule и NSG association with NIC используя приведенный ниже код, и все прошло успешно. Вам не нужно добавлять SSH-порт в NSG, поскольку по умолчанию Azure проверяет, открыта ли ОС Windows RDP , и будет ли Linux открыт SSH порт.

Код:

 provider "azurerm" {
  features{}
}

data "azurerm_resource_group" "example" {
  name     = "ansumantest"
}

resource "azurerm_virtual_network" "example" {
  name                = "example-network"
  address_space       = ["10.0.0.0/16"]
  location            = data.azurerm_resource_group.example.location
  resource_group_name = data.azurerm_resource_group.example.name
}

resource "azurerm_subnet" "example" {
  name                 = "internal"
  resource_group_name  = data.azurerm_resource_group.example.name
  virtual_network_name = azurerm_virtual_network.example.name
  address_prefixes     = ["10.0.2.0/24"]
}
resource "azurerm_public_ip" "aks-nfs-public-ip" {
  name                = "aks-nfs-public-ip"
  location            = data.azurerm_resource_group.example.location
  resource_group_name = data.azurerm_resource_group.example.name
  allocation_method   = "Dynamic"

  tags = {
    environment = "Production"
  }
}

resource "azurerm_network_interface" "example" {
  name                = "example-nic"
  location            = data.azurerm_resource_group.example.location
  resource_group_name = data.azurerm_resource_group.example.name

  ip_configuration {
    name                          = "internal"
    subnet_id                     = azurerm_subnet.example.id
    public_ip_address_id = azurerm_public_ip.aks-nfs-public-ip.id
    private_ip_address_allocation = "Dynamic"
  }
}

resource "azurerm_ssh_public_key" "example" {
  name                = "ansuman-sshkey"
  resource_group_name = data.azurerm_resource_group.example.name
  location            = data.azurerm_resource_group.example.location
  public_key          = file("~/.ssh/id_rsa.pub")
}

resource "azurerm_linux_virtual_machine" "example" {
  name                = "example-machine"
  resource_group_name = data.azurerm_resource_group.example.name
  location            = data.azurerm_resource_group.example.location
  size                = "Standard_F2"
  admin_username      = "adminuser"
  network_interface_ids = [
    azurerm_network_interface.example.id,
  ]

  admin_ssh_key {
    username   = "adminuser"
    public_key = azurerm_ssh_public_key.example.public_key
  }

  os_disk {
    caching              = "ReadWrite"
    storage_account_type = "Standard_LRS"
  }

  source_image_reference {
    publisher = "Canonical"
    offer     = "UbuntuServer"
    sku       = "16.04-LTS"
    version   = "latest"
  }
}
 

Примечание: я использую версию Terraform и 1.0.11 версию поставщика azurerm v2.88.1 в Windows.

Вывод:

введите описание изображения здесь

Используемая команда SSH : ssh -i C:Usersuser.sshid_rsa adminuser@20.xxx.xx.245

введите описание изображения здесь

Примечание: Пожалуйста, убедитесь, что SSH-сервер OpenSSH и агент аутентификации OpenSSH запущены на вашем локальном компьютере.