无法使用 Terraform 启动 EC2

Cant lunch EC2 with Terraform

正在尝试使用新的 vpc、rtb、igw 和子网创建新的基础设施 在这个创建的子网中,我想部署一个 EC2,但我遇到了网络问题

我仔细检查过,子网和 sg 连接到同一个 VPC

即时通讯出错:

Error: Error launching source instance: InvalidParameter: 
Security group sg-0d1250aeb8fa894ef and subnet subnet-628e252e belong to different networks

代码:

  region     = "eu-central-1"
  access_key = "X"
  secret_key = "X"
}

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

resource "aws_subnet" "subnet-1" {
  vpc_id     = aws_vpc.vpc.id
  cidr_block = "10.0.1.0/24"
}

resource "aws_internet_gateway" "gw" {
  vpc_id = aws_vpc.vpc.id
}

resource "aws_route_table" "rtb" {
  vpc_id = aws_vpc.vpc.id

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

resource "aws_security_group" "terra-sg" {
  name        = "terra-sg"
  description = "Allow SSH inbound traffic"
  vpc_id      = aws_vpc.vpc.id

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

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

resource "aws_instance" "ec2" {
  ami                         = "ami-00f22f6155d6d92c5"
  instance_type               = "t2.micro"
  associate_public_ip_address = true
  key_name = "X"
  vpc_security_group_ids = [aws_security_group.terra-sg.id]
}

您需要为您的实例指定子网 ID:

resource "aws_instance" "ec2" {
  ami                         = "ami-00f22f6155d6d92c5"
  instance_type               = "t2.micro"
  associate_public_ip_address = true
  key_name = "X"
  vpc_security_group_ids = [aws_security_group.terra-sg.id]
  subnet_id = aws_subnet.subnet-1.id
}