我已经使用Terraform在Azure上成功创建了一个VM作为资源组的一部分 . 下一步是在新机器中ssh并运行一些命令 . 为此,我创建了一个配置器作为VM资源的一部分并设置了SSH连接:
resource "azurerm_virtual_machine" "helloterraformvm" {
name = "terraformvm"
location = "West US"
resource_group_name = "${azurerm_resource_group.helloterraform.name}"
network_interface_ids = ["${azurerm_network_interface.helloterraformnic.id}"]
vm_size = "Standard_A0"
storage_image_reference {
publisher = "Canonical"
offer = "UbuntuServer"
sku = "14.04.2-LTS"
version = "latest"
}
os_profile {
computer_name = "hostname"
user = "some_user"
password = "some_password"
}
os_profile_linux_config {
disable_password_authentication = false
}
provisioner "remote-exec" {
inline = [
"sudo apt-get install docker.io -y"
]
connection {
type = "ssh"
user = "some_user"
password = "some_password"
}
}
}
如果我运行“terraform apply”,它似乎进入无限循环尝试ssh失败,反复重复此日志:
azurerm_virtual_machine.helloterraformvm (remote-exec): Connecting to remote host via SSH...
azurerm_virtual_machine.helloterraformvm (remote-exec): Host:
azurerm_virtual_machine.helloterraformvm (remote-exec): User: testadmin
azurerm_virtual_machine.helloterraformvm (remote-exec): Password: true
azurerm_virtual_machine.helloterraformvm (remote-exec): Private key: false
azurerm_virtual_machine.helloterraformvm (remote-exec): SSH Agent: true
我确定我做错了什么,但我不知道它是什么:(
编辑:
我已经尝试在没有配置器的情况下设置这台机器,我可以使用给定的用户名/密码来SSH连接到它 . 但是我需要在Azure门户中查找主机名,因为我不知道如何从Terraform中检索它 . 令人怀疑日志中的“Host:”行是空的,所以我想知道它是否与此有关?
更新:
我尝试过不同的东西,比如在连接中指明主机名
host = "${azurerm_public_ip.helloterraformip.id}"
和
host = "${azurerm_public_ip.helloterraformips.ip_address}"
如文档中所示,但没有成功 .
我也尝试过使用ssh-keys代替密码,但结果相同 - 无限循环的连接尝试,没有明确的错误消息,因为它没有连接 .
2 回答
我已成功完成这项工作 . 我改变了几件事:
给
connection
的主机名 .正确配置SSH密钥 - 它们需要未加密 .
从
provisioner
元素中取出connection
元素 .这是完整的Terraform文件,替换SSH密钥等数据:
根据您的描述,Azure Custom Script Extension是您的选择 .
删除
provisioner "remote-exec"
而不是下面的:注意:命令由root用户执行,请勿使用
sudo
.更多信息请参考此链接:azurerm_virtual_machine_extension .
有关可能的扩展名列表,您可以使用Azure CLI命令
az vm extension image list -o table
更新:以上示例仅支持单个命令 . 如果需要多个命令 . 就像你的VM上的安装docker一样,你需要
将其另存为名为script.sh的文件,并将其保存到Azure存储帐户或GitHub(该文件应该是公共的) . 修改如下的terraform文件: