Ensure AWS EC2 Instances Are Not Exposed to the Public


Amazon Elastic Compute Cloud (EC2) provides scalable compute resources in the cloud. While there are use cases where EC2 instances need to be publicly accessible (e.g., web servers), many instances should not be directly exposed to the internet for security reasons. Such exposure could make the instance a potential target for unauthorized access, data breaches, and other malicious activities.


1. Identify Publicly Accessible EC2 Instances:

AWS Management Console:
  • Navigate to the EC2 Dashboard.
  • In the Instances section, view the Public IPv4 address column. If an instance has a public IP address, it might be publicly accessible.
  • Check the security groups associated with these instances for rules that allow unrestricted inbound access.

List EC2 instances with associated public IP addresses:

aws ec2 describe-instances --query 'Reservations[*].Instances[?PublicIpAddress!=null].[InstanceId,PublicIpAddress]' --output table

2. Modify Security Group Rules:

AWS Management Console:
  • Navigate to the EC2 Dashboard.
  • In the navigation pane, choose Security Groups.
  • Identify and select the security group associated with the EC2 instance.
  • Review the Inbound rules for any that allow unrestricted access ( and modify or delete as necessary.

To revoke unrestricted inbound access for a specific security group:

aws ec2 revoke-security-group-ingress --group-id [SECURITY_GROUP_ID] --protocol tcp --port [PORT_NUMBER] --cidr

Replace [SECURITY_GROUP_ID] with the security group ID and [PORT_NUMBER] with the port you want to restrict.


If using Terraform to define security groups, ensure the cidr_blocks argument does not contain "" unless it's explicitly required:

resource "aws_security_group" "example" {
  # ... other configurations ...

  ingress {
    from_port   = [PORT_NUMBER]
    to_port     = [PORT_NUMBER]
    protocol    = "tcp"
    cidr_blocks = ["trusted_ip/32"]  # Replace 'trusted_ip/32' with your trusted CIDR block

  # ... other configurations ...

Replace [PORT_NUMBER] with the port number and trusted_ip/32 with a trusted IP address or CIDR block.

3. Regularly Monitor and Audit:

  • Periodically review the EC2 instances and their associated security groups to ensure there is no unwanted public exposure.
  • Consider using AWS Config or other monitoring tools to detect and alert on EC2 instances with unrestricted inbound access.


Always follow the principle of least privilege when configuring access to EC2 instances. Avoid exposing EC2 instances to the public unless absolutely necessary. If public access is required, always ensure that only specific ports necessary for the application are open, and regularly review and audit the security group configurations. Consider using a bastion host or AWS Systems Manager Session Manager for accessing instances in a secure manner.