1
votes

I am writing a TF script to launch an EC2 instance into an existing VPC. I have seen some examples where the script assigns the subnet id using a variable from another part of the script where the VPC and subnet was created. Instead of using subnet_id = "${aws_subnet.main-public-1.id}" as was shown in that example, I tried putting the actual subnet id from an existing subnet in an existing vpn, both of which were made using the console, like this:

subnet_id = "subnet-xxxxx"

and applied the security group the same way. But when the EC instance got stood up, it was in the default VPC with the default security group. Why did this happen? How do I launch the EC2 into an existing VPC and subnet with existing security groups?

Here is the full script

EC2.tf

provider "aws" {
  profile    = "default"
  region     = var.region
}

resource "aws_instance" "WindowsBox" {
  ami           = "ami-xxxxx"
  instance_type = "t2.medium"
  key_name = aws_key_pair.keypair.key_name

  subnet_id = "subnet-xxxxx"
  vpc_security_group_ids = ["sg-xxxxx"]

  tags = {
    Name ="WindowsBox"
  }
}

resource "aws_eip" "ip" {
    vpc = true
    instance = aws_instance.WindowsBox.id
}

resource "aws_key_pair" "keypair" {
  key_name = "WindowsBox-keypair"
  public_key = file("./kp/WindowsBox-keypair.pub")
}

Variables.tf

variable "region" {
  default = "us-east-2"
}
1

1 Answers

0
votes

The security group that you are using to create the instance should also exist inside the VPC. I think that's not the case here.

I would check the VPC id of the security group is matching with the VPC id of the subnet.

Hope this helps