Cant lunch EC2 with Terraform

Viewed 83

Trying to create a new infrastructure with new vpc,rtb,igw and subnet in this created subnet i want to deploy an EC2 but im having Problems with networking

i doubled checked and subnet & sg are connected to the same VPC

ERROR IM GETTING :

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

Code :

  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]
}

1 Answers

You need to specify the subnet ID for your instance:

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
}
Related