in cdk/src/lib/instance-stack.ts [27:98]
constructor(scope: Construct, id: string, props: InstanceStackProps) {
super(scope, id, props);
// Step 2: Prepare the enclave-enabled parent instance
const vpc = ec2.Vpc.fromLookup(this, `DefaultVPC-${props.instanceName}`, { isDefault: true })
const securityGroup = new ec2.SecurityGroup(this, `InstanceSecurityGroup-${props.instanceName}`, {
vpc,
description: 'Allow SSH (TCP port 22) and HTTP/HTTPS (TCP ports 80/443) in',
allowAllOutbound: true
});
securityGroup.addIngressRule(ec2.Peer.anyIpv4(), ec2.Port.tcp(80), 'Allow HTTP Access');
securityGroup.addIngressRule(ec2.Peer.anyIpv4(), ec2.Port.tcp(443), 'Allow HTTPS Access');
if (props.allowSSHPort) {
securityGroup.addIngressRule(ec2.Peer.anyIpv4(), ec2.Port.tcp(22), 'Allow SSH Access');
}
// Configure user data (startup commands) based on AMI type and server type
const userData = ec2.UserData.custom(this.getUserDataConfig(props));
// Configure instance type
const instanceType = new ec2.InstanceType(props.instanceType);
const isArm = instanceType.architecture === ec2.InstanceArchitecture.ARM_64;
// Configure AMI
const machineImage = new ec2.AmazonLinuxImage({
generation: props?.amiType === 'AL2'
? ec2.AmazonLinuxGeneration.AMAZON_LINUX_2
: ec2.AmazonLinuxGeneration.AMAZON_LINUX_2023,
cpuType: isArm
? ec2.AmazonLinuxCpuType.ARM_64
: ec2.AmazonLinuxCpuType.X86_64
});
// Step 2 & Step 6 - Create the enclave-enabled instance with the attached role/instance profile
const instance = new ec2.Instance(this, props?.instanceName!, {
instanceType: instanceType,
machineImage: machineImage,
vpc: vpc,
vpcSubnets: { subnetType: ec2.SubnetType.PUBLIC },
securityGroup: securityGroup,
keyPair: ec2.KeyPair.fromKeyPairName(this, `KeyPair-${props.instanceName}`, props?.keyPairName!),
instanceProfile: props.instanceProfile,
enclaveEnabled: true,
blockDevices: [
{
deviceName: '/dev/xvda',
volume: ec2.BlockDeviceVolume.ebs(
8, // Default volume size
{
encrypted: props.encryptVolume,
}
),
},
],
userData: userData
});
// Outputs: Instance Information
new cdk.CfnOutput(this, 'InstanceId', { value: instance.instanceId });
new cdk.CfnOutput(this, 'InstancePublicIP', { value: instance.instancePublicIp });
new cdk.CfnOutput(this, 'InstancePublicDnsName', { value: instance.instancePublicDnsName });
new cdk.CfnOutput(this, 'keyPairName', { value: props?.keyPairName });
new cdk.CfnOutput(this, 'serverType', { value: props?.serverType })
new cdk.CfnOutput(this, 'amiType', { value: props?.amiType })
if (props.allowSSHPort){
new cdk.CfnOutput(this, 'SSH connection string', { value: `ssh -i ${props?.keyPairName!}.pem ec2-user@${instance.instancePublicDnsName}` });
} else {
new cdk.CfnOutput(this, 'AWS SSM connection string', { value: `aws ssm start-session --target ${instance.instanceId}` });
}
}