Terraform - SSH 配置程序无法连接

Terraform - SSH Provisioner Failing to Connect

我正在创建 aws_instance 资源和 运行 配置程序,但 SSH 连接从未成功。

这是我的资源代码:

resource "aws_instance" "pos" {
  ami           = "ami-c58c1dd3"
  instance_type = "m4.xlarge"
  subnet_id = "${var.subnet_id_1}"
  key_name        = "${var.key_name}"

  connection {
    type = "ssh"
    user        = "ec2-user"
    private_key = "${file(var.private_key_path)}"
    host = "aws_instance.instance.private_ip"
  } 

  provisioner "remote-exec" {
    inline = [
      "sudo yum install nginx -y",
      "sudo service nginx start"
    ]
  }
}

在创建过程中,我不断重复以下输出:

aws_instance.pos (remote-exec): Connecting to remote host via SSH...
aws_instance.pos (remote-exec):   Host: aws_instance.insance.private_ip
aws_instance.pos (remote-exec):   User: ec2-user
aws_instance.pos (remote-exec):   Password: false
aws_instance.pos (remote-exec):   Private key: true
aws_instance.pos (remote-exec):   Certificate: false
aws_instance.pos (remote-exec):   SSH Agent: false
aws_instance.pos (remote-exec):   Checking Host Key: false
aws_instance.pos: Still creating... [40s elapsed]

SSH 连接从未成功,最终我必须终止该命令。但是,EC2 实例已成功创建,我可以使用私钥(PEM 文件)从我的本地计算机通过 SSH 登录。

我也试过在主机字段中使用 self.public_ip,但产生了相同的结果。我如何连接到 EC2 实例并在创建期间配置它?

您可以尝试使用以下代码。它对我有用。 Terraform 在创建实例和 运行 命令后能够连接到实例。

resource "aws_instance" "pos" {
  ami           = "ami-c58c1dd3"
  instance_type = "m4.xlarge"
  subnet_id = "${var.subnet_id_1}"
  key_name = "XYZ"

  provisioner "remote-exec" {
  connection {
    type = "ssh"
    user = "ec2-user"
    host = "${aws_instance.pos.public_ip}"
    private_key = "${file("<Absolute-Path-to-file>/XYZ.pem")}"
    agent = false
    timeout = "2m"
  }

    inline = [
      "sudo yum install nginx -y",
      "sudo service nginx start"
    ]
  }
}

确保 key_name 应该与 private_key 文件匹配。这是为了确保您在连接实例时使用与创建实例时使用的相同的密钥。

还有一件事,在您的实例正在使用的安全组中允许端口 22。

您没有正确插入 IP 地址输出,所以只是使用 "aws_instance.insance.private_ip".

的字符串文字

相反,您想通过将其包装在 ${} 中来对其进行插值。不幸的是,如果你这样做,你会从 Terraform 得到一个错误,说它找不到资源 aws_instance.instance 因为你还没有定义它。相反,您应该使用 self 关键字直接从资源访问属性:

resource "aws_instance" "pos" {
  ami           = "ami-c58c1dd3"
  instance_type = "m4.xlarge"
  subnet_id = "${var.subnet_id_1}"
  key_name        = "${var.key_name}"

  connection {
    type = "ssh"
    user        = "ec2-user"
    private_key = "${file(var.private_key_path)}"
    host = "${self.private_ip}"
  } 

  provisioner "remote-exec" {
    inline = [
      "sudo yum install nginx -y",
      "sudo service nginx start"
    ]
  }
}