How to create an EC2 with VPC in CDK
Start with installing the EC2 package, run this command in your terminal:
npm install @aws-cdk/aws-ec2
Once installed, import the package on top of your stack:
import * as ec2 from '@aws-cdk/aws-ec2';
To use the EC2 instance we need to create or import a VPC. For this example we are going to create a new VPC with public and isolated subnets.
The EC2 instance will be placed in one of the public subnets.
const vpc = new ec2.Vpc(this, 'MyVpc', {
});
If you create a new VPC, be aware that the CDK will create Nat Gateways for you that costs quite a lot in the long run.
Add natGateways:0 to your VPC to not deploy any Nat Gateways.
const vpc = new ec2.Vpc(this, 'MyVpc', {
natGateways: 0,
});
Create a new security group. With this setup the instance will have no inbound permission and allow all outbound connections.
const securityGroup = new ec2.SecurityGroup(this, 'sg', {
vpc: vpc
});
And add the EC2 instance, here is the code to use the latest AWS Linux 2 AMI (Amazon Machine Image).
The instance type here is T3.micro and can be easily changed in the instanceType property.
Per default, will the EC2 machine now be placed in the isolated/private subnet of our newly created VPC.
const ec2Instance = new ec2.Instance(this,'ec2Instance', {
instanceType: ec2.InstanceType.of(ec2.InstanceClass.T3, ec2.InstanceSize.MICRO),
machineImage: new ec2.AmazonLinuxImage(),
vpc: vpc
securityGroup: securityGroup
})
And thats it, with these components you have your EC2 instance up and running.
Here is the complete code copy-paste ready for you:
import * as cdk from '@aws-cdk/core';
import * as ec2 from '@aws-cdk/aws-ec2';
export class Ec2Stack extends cdk.Stack {
constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const vpc = new ec2.Vpc(this, 'MyVpc', {
natGateways: 0,
});
const securityGroup = new ec2.SecurityGroup(this, 'sg', {
vpc: vpc
});
const ec2Instance = new ec2.Instance(this,'ec2Instance', {
instanceType: ec2.InstanceType.of(ec2.InstanceClass.T3, ec2.InstanceSize.MICRO),
machineImage: new ec2.AmazonLinuxImage(),
vpc: vpc
securityGroup: securityGroup
})
}
}