Review public IP assignment for EC2 instances

Do not assign public IP addresses to EC2 instances that do not need direct internet connectivity.

Description

A public IP lets an EC2 instance communicate directly with the internet when routing and security groups permit it. If associate_public_ip_address is omitted, subnet settings and other configuration affect assignment, so make the intended setting explicit.

Potential impact

An unnecessary public IP combined with permissive network settings can expose the instance to external scanning and attacks.

Remediation

If direct public access is unnecessary, set associate_public_ip_address = false and use a private subnet. Design required inbound traffic through a load balancer and outbound connectivity through NAT or VPC endpoints.

Examples

The examples explicitly disable automatic public IPv4 assignment. Configure routing and security groups separately.

Before

hcl
resource "aws_instance" "example" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t3.micro"

  tags = {
    Name = "HelloWorld"
  }
}

After

hcl
resource "aws_instance" "example" {
  ami                         = data.aws_ami.ubuntu.id
  associate_public_ip_address = false
  instance_type               = "t3.micro"

  tags = {
    Name = "HelloWorld"
  }
}

References