Terraform AWS-无法连接到EC2实例(SSH端口无法从外部访问)

Terraform AWS-无法连接到EC2实例(SSH端口无法从外部访问)

我正在尝试为自己构建一个小型 EC2 实例,该实例将启动到具有 EIB、子网/互联网网关和安全组的 VPC 中。

main.tf

resource "aws_instance" "live" {
  ami = "ami-060e472760062f83f"
  instance_type = "t2.nano"
  key_name = "xxx"

  network_interface {
    device_index = 0
    network_interface_id = aws_network_interface.multi-ip.id
  }
}

resource null_resource "ansible_web" {
  depends_on = [
    aws_elasticache_cluster.redis,
    aws_internet_gateway.gw,
    aws_instance.live
  ]

  provisioner "local-exec" {
    command = "ANSIBLE_HOST_KEY_CHECKING=false ansible-playbook -u ubuntu --private-key './xxx.pem' -i '${aws_instance.live.public_dns},' ansible/main.yml"
  }
}

安全组network.tf

resource "aws_security_group" "all-outbound-traffic" {
  name        = "all-outbound-traffic-group"
  description = "Allow traffic to leave the AWS instance"
  vpc_id      = aws_vpc.default.id

  tags = {
    Name = "Outbound Traffic Security Group"
  }

  egress {
    from_port = 0
    to_port   = 0
    protocol  = "-1"
    cidr_blocks = [aws_vpc.default.cidr_block]
  }
}

resource "aws_security_group" "ssh-group" {
  name        = "ssh-access-group"
  description = "Allow traffic to port 22 (SSH)"
  vpc_id      = aws_vpc.default.id

  tags = {
    Name = "SSH Access Security Group"
  }

  ingress {
    description = "SSH to VPC"
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = [aws_vpc.default.cidr_block]
  }
}

网络节点network.tf

resource "aws_vpc" "default" {
  cidr_block = "10.0.0.0/16"
  enable_dns_hostnames = true
  enable_dns_support   = true

  tags = {
    Name = "tf-default"
  }
}

resource "aws_internet_gateway" "gw" {
  vpc_id = aws_vpc.default.id

  tags = {
    Name = "tf-default"
  }
}

resource "aws_subnet" "default" {
  vpc_id            = aws_vpc.default.id
  cidr_block        = "10.0.0.0/16"

  tags = {
    Name = "tf-default"
  }
}

resource "aws_network_interface" "multi-ip" {
  subnet_id   = aws_subnet.default.id
  security_groups = [
    aws_security_group.http-group.id,
    aws_security_group.https-group.id,
    aws_security_group.ssh-group.id,
    aws_security_group.all-outbound-traffic.id,
  ]
}

resource "aws_eip_association" "eip_assoc" {
  depends_on = [
    aws_instance.live,
    aws_eip.lb
  ]

  instance_id = aws_instance.live.id
  allocation_id = aws_eip.lb.id
  network_interface_id = aws_network_interface.multi-ip.id
}

resource "aws_eip" "lb" {
  vpc = true
  network_interface         = aws_network_interface.multi-ip.id
  //associate_with_private_ip = aws_instance.live.private_ip
  depends_on                = [aws_internet_gateway.gw]
}

terraform 能够基本正确地构建所有设置,并且在我的 AWS 控制台中,一切似乎都连接正确。

EC2 -> VPC -> 子网 -> 具有安全组的网络接口

据我所知,我应该启动一个带有私有子网的 VPC,该子网绑定到 EIB 模块提供的静态 IP 地址。但是,如果我尝试通过 ssh 进入机器,它会超时,这让我相信我错误地设置了 SG。我做错了什么?

相关内容