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
- 1Set AssociatePublicIpAddress to false on the NetworkInterface
- 2Place the instance in a private subnet and use a NAT Gateway / VPC endpoint for outbound
- 3Use an ALB / NLB in a public subnet to front the workload instead
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,
});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::InstanceIntentional? 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 scanCDK Insights runs this and 118+ other rules locally against your synthesised CDK app โ free, no account, your code never leaves your machine.