Description
If you omit subnet_id, EC2 selects an available default subnet. If you omit security groups, EC2 uses the VPC’s default security group.
Potential impact
These defaults can place workloads that need separate access rules on a shared network.
Remediation
Set subnet_id and vpc_security_group_ids to resources in the same VPC. Check the subnet routes and group rules. Changing an existing instance’s subnet replaces the instance. Review the Terraform plan and preserve any data you need before applying it.
Examples
Use an AMI valid in the target Region.
Before
hcl
resource "aws_instance" "example" {
ami = "ami-003634241a8fcdec0"
instance_type = "t2.micro"
}
After
hcl
resource "aws_instance" "example" {
ami = "ami-003634241a8fcdec0"
instance_type = "t2.micro"
subnet_id = aws_subnet.instance.id
vpc_security_group_ids = [aws_security_group.instance.id]
}