Skip to main content
HIGHEC2Security

EC2 Instance Public IP

ec2-instance-public-ip

What this rule checks

Detects EC2 instances whose NetworkInterfaces specify AssociatePublicIpAddress=true, exposing the instance directly to the internet.

How to fix it

  1. 1Set AssociatePublicIpAddress to false on the NetworkInterface
  2. 2Place the instance in a private subnet and use a NAT Gateway / VPC endpoint for outbound
  3. 3Use an ALB / NLB in a public subnet to front the workload instead
FlaggedThe instance is placed in a public subnet with associatePublicIpAddress true, giving it an internet-routable IP.
import { aws_ec2 as ec2 } from 'aws-cdk-lib';

const vpc = new ec2.Vpc(this, 'Vpc');

new ec2.Instance(this, 'Instance', {
  vpc,
  vpcSubnets: { subnetType: ec2.SubnetType.PUBLIC },
  instanceType: ec2.InstanceType.of(ec2.InstanceClass.T3, ec2.InstanceSize.MICRO),
  machineImage: ec2.MachineImage.latestAmazonLinux2023(),
  associatePublicIpAddress: true,
});
FixedThe instance runs in a private subnet with no public IP, reaching the internet only outbound through a NAT gateway.
import { aws_ec2 as ec2 } from 'aws-cdk-lib';

const vpc = new ec2.Vpc(this, 'Vpc');

new ec2.Instance(this, 'Instance', {
  vpc,
  vpcSubnets: { subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS },
  instanceType: ec2.InstanceType.of(ec2.InstanceClass.T3, ec2.InstanceSize.MICRO),
  machineImage: ec2.MachineImage.latestAmazonLinux2023(),
  associatePublicIpAddress: false,
});

CDK Insights pinpoints the exact file and line in your CDK source for every finding, so you can jump straight to the fix.

Affected resource types

AWS::EC2::Instance

Compliance frameworks

SOC2HIPAAPCI-DSSCISNIST

AWS documentation

Read the AWS guidance

Intentional? Suppress this finding

Sometimes a flag is deliberate โ€” a genuinely public endpoint, say. You can dismiss ec2-instance-public-ip and the reason is kept in the report, not silently hidden.

In .cdk-insights.json:

{
  "ignoreRules": [
    { "id": "ec2-instance-public-ip", "reason": "Why this is intentional" }
  ]
}

Or inline in your CDK code:

Validations.of(scope).acknowledge({
  id: 'cdk-insights::ec2-instance-public-ip',
  reason: 'Why this is intentional',
});

Use the rule ID ec2-instance-public-ip shown above โ€” not the CDK-* ID from SARIF / GitHub code scanning. To dismiss every finding on one construct instead, use ignorePaths. Suppression docs โ†’

Catch this in your stack

$ npx cdk-insights scan

CDK Insights runs this and 118+ other rules locally against your synthesised CDK app โ€” free, no account, your code never leaves your machine.

More EC2 rules