Review EC2 subnet and security-group selection

Configure EC2 network placement explicitly.

Description

When an EC2 subnet is omitted, AWS selects a default subnet from an available default VPC. Omitting security groups attaches the VPC’s default group. Omitted settings do not mean placement outside a VPC.

Potential impact

Defaults that do not fit the workload can lead to unintended connectivity or shared policies.

Remediation

Specify subnet_id and vpc_security_group_ids from the same VPC, then check routing and the actual security-group rules.

Examples

The examples add explicit subnet and security-group references to a configuration relying on defaults. 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]
}

References