无法通过 SSH 进入 Terraform 创建的 EC2 实例

无法通过 SSH 进入 Terraform 创建的 EC2 实例

在 Ubuntu 18.04 上使用 Terraform v1.0.11

terraform apply完成下面的操作后main.tf,并等待实例通过检查(然后再等一分钟)后,尝试 SSH 时遇到了障碍。

$ ssh -v -i ~/.ssh/toydeploy.pem [email protected]
OpenSSH_7.6p1 Ubuntu-4ubuntu0.5, OpenSSL 1.0.2n  7 Dec 2017
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug1: Connecting to 18.144.125.224 [18.144.125.224] port 22.
debug1: connect to address 18.144.125.224 port 22: Connection timed out
ssh: connect to host 18.144.125.224 port 22: Connection timed out

我已经使用相同的 AMI 和密钥对手动启动了一个实例,并且可以通过 SSH 连接。比较控制台中的网络和安全设置,我注意到的唯一区别是手动部署的实例使用的是默认 VPC,并且“应答私有资源 DNS 名称”显示手动部署的实例为“IPv4 (A)”,而 Terraformed 实例为“-”。两者似乎都无害,但我可能错了。

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 3.27"
    }
  }
}

provider "aws" {
  profile = "default"
  region  = "us-west-1"
}

variable "cidr_vpc" {
  description = "CIDR block for VPC"
  default     = "10.1.0.0/16"
}

variable "cidr_subnet" {
  description = "CIDR block for subnet"
  default     = "10.1.0.0/20"
}

resource "aws_vpc" "toydeploy-vpc" {
  cidr_block           = var.cidr_vpc
  enable_dns_hostnames = true
  enable_dns_support   = true
}

resource "aws_subnet" "toydeploy-subnet" {
  vpc_id     = aws_vpc.toydeploy-vpc.id
  cidr_block = var.cidr_subnet
}

resource "aws_security_group" "toydeploy-sg" {
  name   = "toydeploy-sg"
  vpc_id = aws_vpc.toydeploy-vpc.id

  ingress {
    from_port = 22
    to_port   = 22
    protocol  = "tcp"
    cidr_blocks = [
      "0.0.0.0/0"
    ]
  }

  # Terraform removes the default rule, so we re-add it.
  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_instance" "toydeploy" {
  ami                         = "ami-083f68207d3376798" # Ubuntu 18.04
  instance_type               = "t2.micro"
  security_groups             = ["${aws_security_group.toydeploy-sg.id}"]
  subnet_id                   = aws_subnet.toydeploy-subnet.id
  associate_public_ip_address = true
  key_name                    = "toydeploy"
}

如果下面没有出现任何问题并且您可以向我指出一个可行的示例,我将不胜感激。

解决

仔细检查后发现,路由表仅针对子网进行路由,而不是 0.0.0.0/0。添加以下内容解决了该问题。

resource "aws_internet_gateway" "toydeploy-ig" {
  vpc_id = aws_vpc.toydeploy-vpc.id
}

resource "aws_route_table" "toydeploy-rt" {
  vpc_id = aws_vpc.toydeploy-vpc.id
  route {
    cidr_block = "0.0.0.0/0"
    gateway_id = aws_internet_gateway.toydeploy-ig.id
  }
}

resource "aws_route_table_association" "toydeploy-rta" {
  subnet_id      = aws_subnet.toydeploy-subnet.id
  route_table_id = aws_route_table.toydeploy-rt.id
}

答案1

连接超时通常表示网络问题。请检查:

  • 安全组/NACL 在端口 22 上对您的 IP 开放
  • VPC 有互联网网关
  • 子网有通向互联网网关的路由
  • 实例具有公共 IP
  • 路由设置正确

这是您尝试连接时的关键行,告诉您发生了什么

ssh: connect to host 18.144.125.224 port 22: Connection timed out

相关内容