为什么在通过 Terraform 设置 VPC 和 EC2 后无法 ping 通我的 EC2 实例?

Why can I not ping my EC2 instance when I've set up the VPC and EC2 via Terraform?

我通过 Terraform 进行了设置,其中包括一个 VPC、一个 public 子网和一个带有安全组的 EC2 实例。我正在尝试 ping EC2 实例但超时。

我努力确保的几件事:

我不确定我在这里错过了什么。

我的 tf 文件看起来像(编辑以反映最新更改):


resource "aws_vpc" "foobar" {
  cidr_block = "10.0.0.0/16"
}

resource "aws_internet_gateway" "foobar_gateway" {
  vpc_id = aws_vpc.foobar.id
}

/*
Public subnet
*/
resource "aws_subnet" "foobar_subnet" {
  vpc_id = aws_vpc.foobar.id
  cidr_block = "10.0.1.0/24"
}

resource "aws_route_table" "foobar_routetable" {
  vpc_id = aws_vpc.foobar.id

  route {
    cidr_block = "0.0.0.0/0"
    gateway_id = aws_internet_gateway.foobar_gateway.id
  }
}

resource "aws_route_table_association" "foobar_routetable_assoc" {
  subnet_id = aws_subnet.foobar_subnet.id
  route_table_id = aws_route_table.foobar_routetable.id
}

/*
Web
*/
resource "aws_security_group" "web" {
  name = "vpc_web"
  vpc_id = aws_vpc.foobar.id

  ingress {
    protocol    = -1
    from_port   = 0
    to_port     = 0
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    protocol    = -1
    from_port   = 0
    to_port     = 0
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_network_acl" "main" {
  vpc_id = aws_vpc.foobar.id
  subnet_ids = [aws_subnet.foobar_subnet.id]

  egress {
    protocol   = -1
    rule_no    = 100
    action     = "allow"
    cidr_block = "0.0.0.0/0"
    from_port  = 0
    to_port    = 0
  }

  ingress {
    protocol   = -1
    rule_no    = 100
    action     = "allow"
    cidr_block = "0.0.0.0/0"
    from_port  = 0
    to_port    = 0
  }
}

resource "aws_instance" "web-1" {
  ami = "ami-0323c3dd2da7fb37d"
  instance_type = "t2.micro"
  subnet_id = aws_subnet.foobar_subnet.id
  associate_public_ip_address = true
}

resource "aws_eip" "web-1" {
  instance = aws_instance.web-1.id
  vpc = true
}

为什么我在通过 Terraform 设置 VPC 和 EC2 后无法 ping 通我的 EC2 实例?

为什么要在安全组规则中添加 self 参数。 terraform 的文档声明 If true, the security group itself will be added as a source to this ingress rule. 这基本上意味着只有该安全组才能访问该实例。请删除它并尝试。

编辑:请参阅下面的评论以了解解决问题的步骤

允许所有流量通过安全组不会对实例启用 ping。您需要添加特定的安全规则 - 如下图所示以启用 ping 请求。

请记住,AWS 已单独制定此规则以确保您知道自己在做什么。能够从世界任何地方 ping 实例会使您的实例容易受到试图通过暴力破解各种 IP 地址来查找实例的人的攻击。

因此,建议谨慎更改此规则。