无法访问通过 Terraform 创建的 AWS EC2 公共 IP

时间:2021-04-10 14:22:40

标签: amazon-web-services networking amazon-ec2 terraform

我正在尝试运行 Terraform Up and Running 一书中的第一个 basic examples。除了版本之外,我的 main.tf 几乎与链接中的相同:

provider "aws" {
  region = "us-east-2"
}

resource "aws_instance" "example" {
  ami                    = "ami-0c55b159cbfafe1f0"
  instance_type          = "t2.micro"
  vpc_security_group_ids = [aws_security_group.instance.id]

  user_data = <<-EOF
              #!/bin/bash
              echo "Hello, World" > index.html
              nohup busybox httpd -f -p 8080 &
              EOF

  tags = {
    Name = "terraform-example"
  }
}

resource "aws_security_group" "instance" {

  name = var.security_group_name

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

variable "security_group_name" {
  description = "The name of the security group"
  type        = string
  default     = "terraform-example-instance"
}

output "public_ip" {
  value       = aws_instance.example.public_ip
  description = "The public IP of the Instance"
}

我运行了 terraform apply,一切似乎都已成功创建。但是,当我尝试运行 curl http://<EC2_INSTANCE_PUBLIC_IP>:8080 时,命令挂起。

我在运行示例之前创建了我的 AWS 账户,因此它使用默认网络配置。

路由表有一个条目指向 VPC 的 Internet 网关:

Destination    |      Target      |     Status      |   Propagated
0.0.0.0/0      |     igw-<igwId>  |      active     |      No

网络 ACL 具有默认设置:

Rule number   |    Type    | Protocol  | Port range | Source    | Allow/Deny
100           | All traffic|    All    |    All     | 0.0.0.0/0 |    Allow
*             | All traffic|    All    |    All     | 0.0.0.0/0 |    Deny

我的 Terraform 版本是 v0.14.10

关于如何通过 EC2 的公共 IP 访问实例的服务器的任何想法?

1 个答案:

答案 0 :(得分:0)

TF 程序没有任何问题。我使用我的沙箱帐户验证它并按预期工作。脚本开始工作需要 1-2 分钟,所以可能你测试的太早了。

因此,您遇到的任何困难都不是由于脚本本身造成的。因此,要么您在 SO 上发布的内容不是您的实际代码,要么您以某种方式修改了您的 VPC 配置,从而使该实例无法访问。