The CDK Construct Library for AWS::EC2 providing high-level constructs for EC2 instances, VPCs, subnets, security groups, and networking infrastructure.
npx @tessl/cli install tessl/npm-aws-cdk--aws-ec2@1.204.0The AWS CDK EC2 module provides comprehensive TypeScript constructs for Amazon EC2 (Elastic Compute Cloud) services within the AWS CDK v1 framework. It enables infrastructure-as-code for EC2 instances, VPCs, subnets, security groups, and networking components with strong typing and high-level abstractions.
npm install @aws-cdk/aws-ec2import * as ec2 from "@aws-cdk/aws-ec2";
import { Vpc, Instance, SecurityGroup } from "@aws-cdk/aws-ec2";For CommonJS:
const ec2 = require("@aws-cdk/aws-ec2");
const { Vpc, Instance, SecurityGroup } = require("@aws-cdk/aws-ec2");import * as ec2 from "@aws-cdk/aws-ec2";
import * as cdk from "@aws-cdk/core";
export class MyStack extends cdk.Stack {
constructor(scope: cdk.Construct, id: string) {
super(scope, id);
// Create a VPC with public and private subnets
const vpc = new ec2.Vpc(this, "MyVpc", {
maxAzs: 2,
natGateways: 1,
});
// Create a security group
const securityGroup = new ec2.SecurityGroup(this, "WebSG", {
vpc,
description: "Security group for web servers",
});
securityGroup.addIngressRule(
ec2.Peer.anyIpv4(),
ec2.Port.tcp(80),
"Allow HTTP traffic"
);
// Launch an EC2 instance
const instance = new ec2.Instance(this, "WebServer", {
vpc,
instanceType: ec2.InstanceType.of(
ec2.InstanceClass.T3,
ec2.InstanceSize.MICRO
),
machineImage: ec2.MachineImage.latestAmazonLinux(),
securityGroup,
});
}
}The AWS CDK EC2 module is organized around several key components:
Comprehensive VPC creation and management with public, private, and isolated subnets. Supports custom CIDR blocks, availability zone distribution, and NAT gateway configuration.
class Vpc extends Resource implements IVpc {
constructor(scope: Construct, id: string, props?: VpcProps);
readonly vpcId: string;
readonly vpcCidrBlock: string;
readonly availabilityZones: string[];
readonly publicSubnets: ISubnet[];
readonly privateSubnets: ISubnet[];
readonly isolatedSubnets: ISubnet[];
readonly internetGatewayId?: string;
selectSubnets(selection?: SubnetSelection): SelectedSubnets;
addGatewayEndpoint(id: string, options: GatewayVpcEndpointOptions): GatewayVpcEndpoint;
addInterfaceEndpoint(id: string, options: InterfaceVpcEndpointOptions): InterfaceVpcEndpoint;
}
interface VpcProps {
readonly cidr?: string;
readonly maxAzs?: number;
readonly subnetConfiguration?: SubnetConfiguration[];
readonly natGateways?: number;
readonly natGatewayProvider?: NatProvider;
readonly vpnGateway?: boolean;
readonly enableDnsHostnames?: boolean;
readonly enableDnsSupport?: boolean;
}EC2 instance management with support for user data, security groups, instance types, and machine images.
class Instance extends Resource implements IInstance {
constructor(scope: Construct, id: string, props: InstanceProps);
readonly instanceId: string;
readonly instanceAvailabilityZone: string;
readonly instancePrivateDnsName: string;
readonly instancePrivateIp: string;
readonly instancePublicDnsName: string;
readonly instancePublicIp: string;
readonly connections: Connections;
addUserData(...commands: string[]): void;
addSecurityGroup(securityGroup: ISecurityGroup): void;
}
interface InstanceProps {
readonly vpc: IVpc;
readonly instanceType: InstanceType;
readonly machineImage: IMachineImage;
readonly securityGroup?: ISecurityGroup;
readonly keyName?: string;
readonly userData?: UserData;
readonly role?: iam.IRole;
readonly vpcSubnets?: SubnetSelection;
}Network security management through security groups with ingress and egress rules.
class SecurityGroup extends Resource implements ISecurityGroup {
constructor(scope: Construct, id: string, props: SecurityGroupProps);
readonly securityGroupId: string;
readonly securityGroupVpcId: string;
readonly connections: Connections;
addIngressRule(peer: IPeer, connection: Port, description?: string, remoteRule?: boolean): void;
addEgressRule(peer: IPeer, connection: Port, description?: string, remoteRule?: boolean): void;
}
interface SecurityGroupProps {
readonly vpc: IVpc;
readonly description?: string;
readonly allowAllOutbound?: boolean;
readonly disableInlineRules?: boolean;
}Machine image selection and management for various operating systems including Amazon Linux, Ubuntu, Windows, and custom AMIs.
abstract class MachineImage {
static latestAmazonLinux(props?: AmazonLinuxImageProps): IMachineImage;
static latestWindows(version: WindowsVersion): IMachineImage;
static genericLinux(amiMap: {[region: string]: string}, props?: GenericLinuxImageProps): IMachineImage;
static fromSsmParameter(parameterName: string, props?: GenericSSMParameterImageProps): IMachineImage;
abstract getImage(scope: Construct): MachineImageConfig;
}
interface IMachineImage {
getImage(scope: Construct): MachineImageConfig;
}Subnet management including public, private, and isolated subnets with routing configuration.
abstract class Subnet extends Resource implements ISubnet {
readonly subnetId: string;
readonly availabilityZone: string;
readonly ipv4CidrBlock: string;
readonly routeTable: IRouteTable;
addRoute(id: string, options: AddRouteOptions): void;
}
class PublicSubnet extends Subnet implements IPublicSubnet {
constructor(scope: Construct, id: string, props: PublicSubnetProps);
addDefaultInternetRoute(gatewayId: string, gateway: IDependable): void;
}
class PrivateSubnet extends Subnet implements IPrivateSubnet {
constructor(scope: Construct, id: string, props: PrivateSubnetProps);
addDefaultNatRoute(natGatewayId: string): void;
}VPC endpoint management for AWS services including gateway endpoints for S3/DynamoDB and interface endpoints for other services.
class GatewayVpcEndpoint extends VpcEndpoint implements IGatewayVpcEndpoint {
constructor(scope: Construct, id: string, props: GatewayVpcEndpointProps);
static fromGatewayVpcEndpointId(scope: Construct, id: string, gatewayVpcEndpointId: string): IGatewayVpcEndpoint;
}
class InterfaceVpcEndpoint extends VpcEndpoint implements IInterfaceVpcEndpoint {
constructor(scope: Construct, id: string, props: InterfaceVpcEndpointProps);
readonly vpcEndpointDnsEntries: string[];
readonly vpcEndpointNetworkInterfaceIds: string[];
}EBS volume management including volume types, encryption, and device mapping.
class Volume extends Resource implements IVolume {
constructor(scope: Construct, id: string, props: VolumeProps);
readonly volumeId: string;
readonly availabilityZone: string;
readonly encryptionKey?: kms.IKey;
grantAttachVolume(grantee: iam.IGrantable, instances?: IInstance[]): iam.Grant;
grantDetachVolume(grantee: iam.IGrantable, instances?: IInstance[]): iam.Grant;
}
interface EbsDeviceOptions {
readonly deleteOnTermination?: boolean;
readonly iops?: number;
readonly volumeSize?: number;
readonly volumeType?: EbsDeviceVolumeType;
readonly encrypted?: boolean;
readonly kmsKey?: kms.IKey;
}Launch template management for advanced EC2 instance configuration.
class LaunchTemplate extends Resource implements ILaunchTemplate {
constructor(scope: Construct, id: string, props?: LaunchTemplateProps);
readonly launchTemplateId: string;
readonly launchTemplateName: string;
readonly versionNumber: string;
}
interface LaunchTemplateProps {
readonly launchTemplateName?: string;
readonly machineImage?: IMachineImage;
readonly instanceType?: InstanceType;
readonly userData?: UserData;
readonly securityGroup?: ISecurityGroup;
readonly keyName?: string;
readonly role?: iam.IRole;
readonly blockDevices?: BlockDevice[];
}Network ACL management for subnet-level security controls.
class NetworkAcl extends Resource implements INetworkAcl {
constructor(scope: Construct, id: string, props: NetworkAclProps);
readonly networkAclId: string;
addEntry(id: string, options: CommonNetworkAclEntryOptions): NetworkAclEntry;
}
interface CommonNetworkAclEntryOptions {
readonly cidr: AclCidr;
readonly ruleNumber: number;
readonly traffic: AclTraffic;
readonly direction?: TrafficDirection;
readonly ruleAction?: RuleAction;
}User data and CloudFormation init support for instance initialization.
abstract class UserData {
static forLinux(options?: LinuxUserDataOptions): UserData;
static forWindows(): UserData;
static custom(content: string): UserData;
abstract addCommands(...commands: string[]): void;
abstract addOnExitCommands(...commands: string[]): void;
abstract addSignalOnExitCommand(resource: Resource): void;
abstract render(): string;
}VPN connection management including site-to-site VPN and client VPN endpoints.
class VpnConnection extends Resource implements IVpnConnection {
constructor(scope: Construct, id: string, props: VpnConnectionProps);
readonly vpnId: string;
readonly customerGatewayId: string;
readonly customerGatewayIp: string;
readonly customerGatewayAsn: number;
}
class ClientVpnEndpoint extends Resource {
constructor(scope: Construct, id: string, props: ClientVpnEndpointProps);
readonly endpointId: string;
readonly dnsName: string;
addAuthorizationRule(id: string, props: ClientVpnAuthorizationRuleProps): ClientVpnAuthorizationRule;
addRoute(id: string, props: ClientVpnRouteProps): ClientVpnRoute;
}VPC Flow Logs capture network traffic information for monitoring and troubleshooting.
class FlowLog extends Resource implements IFlowLog {
constructor(scope: Construct, id: string, props: FlowLogProps);
readonly flowLogId: string;
static fromFlowLogId(scope: Construct, id: string, flowLogId: string): IFlowLog;
}
interface IFlowLog extends IResource {
readonly flowLogId: string;
}
interface FlowLogProps {
readonly resourceType: FlowLogResourceType;
readonly trafficType?: FlowLogTrafficType;
readonly destination?: FlowLogDestination;
readonly logFormat?: string[];
readonly maxAggregationInterval?: FlowLogMaxAggregationInterval;
}
abstract class FlowLogDestination {
static toCloudWatchLogs(logGroup: logs.ILogGroup, iamRole?: iam.IRole): FlowLogDestination;
static toS3(bucket: s3.IBucket, keyPrefix?: string): FlowLogDestination;
}
enum FlowLogMaxAggregationInterval {
ONE_MINUTE = 60,
TEN_MINUTES = 600
}
enum FlowLogTrafficType {
ACCEPT = 'ACCEPT',
ALL = 'ALL',
REJECT = 'REJECT'
}
enum FlowLogResourceType {
VPC = 'VPC',
SUBNET = 'Subnet',
NETWORK_INTERFACE = 'NetworkInterface'
}Advanced instance initialization using CloudFormation Init.
class CloudFormationInit {
static fromElements(...elements: InitElement[]): CloudFormationInit;
static fromConfig(config: InitConfig): CloudFormationInit;
static fromConfigSets(props: ConfigSetProps): CloudFormationInit;
addConfig(configName: string, config: InitConfig): void;
addConfigSet(configSetName: string, configNames: string[]): void;
}
class InitConfig {
constructor(elements: InitElement[]);
add(...elements: InitElement[]): void;
}
abstract class InitElement {
static package(): InitPackage;
static file(fileName: string, options: InitFileOptions): InitFile;
static service(serviceName: string, options?: InitServiceOptions): InitService;
static command(key: string, options: InitCommandOptions): InitCommand;
}
interface InitFileOptions {
readonly mode?: string;
readonly owner?: string;
readonly group?: string;
readonly serviceRestartHandles?: InitServiceRestartHandle[];
}
interface InitServiceOptions {
readonly enabled?: boolean;
readonly ensureRunning?: boolean;
readonly serviceRestartHandle?: InitServiceRestartHandle;
}
interface InitCommandOptions {
readonly cwd?: string;
readonly env?: Record<string, string>;
readonly ignoreErrors?: boolean;
readonly testCmd?: string;
}CDK Aspects for enforcing security best practices across EC2 resources.
abstract class RequireImdsv2Aspect implements IAspect {
constructor(props?: RequireImdsv2AspectProps);
abstract visit(node: IConstruct): void;
}
interface RequireImdsv2AspectProps {
readonly suppressWarnings?: boolean;
}
class InstanceRequireImdsv2Aspect extends RequireImdsv2Aspect {
constructor(props?: RequireImdsv2AspectProps);
visit(node: IConstruct): void;
}
class LaunchTemplateRequireImdsv2Aspect extends RequireImdsv2Aspect {
constructor(props?: RequireImdsv2AspectProps);
visit(node: IConstruct): void;
}interface IVpc extends IResource {
readonly vpcId: string;
readonly vpcCidrBlock: string;
readonly availabilityZones: string[];
readonly publicSubnets: ISubnet[];
readonly privateSubnets: ISubnet[];
readonly isolatedSubnets: ISubnet[];
selectSubnets(selection?: SubnetSelection): SelectedSubnets;
}
interface ISubnet extends IResource {
readonly subnetId: string;
readonly availabilityZone: string;
readonly ipv4CidrBlock: string;
readonly routeTable: IRouteTable;
}
interface ISecurityGroup extends IResource, IPeer {
readonly securityGroupId: string;
readonly connections: Connections;
addIngressRule(peer: IPeer, connection: Port, description?: string): void;
addEgressRule(peer: IPeer, connection: Port, description?: string): void;
}interface IInstance extends IResource {
readonly instanceId: string;
readonly instanceAvailabilityZone: string;
readonly instancePrivateIp: string;
readonly instancePublicIp: string;
readonly connections: Connections;
}
class InstanceType {
static of(instanceClass: InstanceClass, instanceSize: InstanceSize): InstanceType;
readonly toString: string;
}
enum InstanceClass {
T2 = "t2",
T3 = "t3",
T3A = "t3a",
M5 = "m5",
M5A = "m5a",
C5 = "c5",
R5 = "r5",
// ... many more instance classes
}
enum InstanceSize {
NANO = "nano",
MICRO = "micro",
SMALL = "small",
MEDIUM = "medium",
LARGE = "large",
XLARGE = "xlarge",
// ... various xlarge sizes
}