How to Create an AWS-CDK EC2 Instance

And one that Defaults to IPV6

Introducing a Scalable EC2 Configuration with AWS CDK

In today’s rapidly changing technology landscape, ensuring that your infrastructure is not only robust but also scalable is a must. Building a flexible environment that can grow with your needs is essential for supporting modern applications.

That’s why I’m excited to share a practical solution that leverages the power of AWS Cloud Development Kit (AWS CDK) to create a tailored EC2 instance configuration. This code, written in TypeScript, lays the groundwork for a highly scalable and easily managed infrastructure.

What Does It Do?

The code provides a step-by-step guide to setting up an EC2 instance on AWS with specific configurations, including:

  • User Data Scripting: Automating the installation of essential packages and files, such as Node.js and Elastic Agent.
  • IAM Roles & Security Groups: Ensuring secure access to the EC2 instance and integrating with Amazon’s System Manager.
  • IPv6 Configuration: Demonstrating how to enable IPv6 support within your VPC.
  • Auto Scaling: Implementing an Auto Scaling Group to allow the system to dynamically adjust to the demands, scaling in and out as needed.

Why Is It Important?

This approach offers a clean, programmatic way to define cloud resources, making it easier to manage, scale, and replicate environments. By harnessing the power of AWS CDK, we’re moving away from manual configurations and error-prone scripting, embracing a more maintainable and version-controlled way of defining our cloud infrastructure.

Whether you’re a seasoned cloud engineer or just getting started with AWS, this guide offers a clear path to understanding and implementing a versatile EC2 setup. The provided code is not just an abstract example; it’s a practical tool that can be adapted to various real-world scenarios.

So, without further ado, let’s dive into the code and explore how to create your customized EC2 instance with AWS CDK!

Step 1 – Import Necessary Modules for AWS-CDK EC2 Instance:

Before creating the stack, import the necessary AWS CDK and AWS modules.

TypeScript
import * as cdk from 'aws-cdk-lib/core';
import * as iam from 'aws-cdk-lib/aws-iam';
import { Tags, Fn } from 'aws-cdk-lib';
import { AmazonLinuxCpuType, MachineImage, UserData } from 'aws-cdk-lib/aws-ec2';
import * as autoscaling from 'aws-cdk-lib/aws-autoscaling';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import { Construct } from 'constructs';

Step 2 – Create User Data:

Define a user data script to install necessary packages and files for the EC2 instance.

TypeScript
const userData = UserData.forLinux();
userData.addCommands(
   // Your command list here...
);

Step 3 – Create IAM Role:

Define an IAM role that the EC2 instance will assume. This will allow access to SSM (System Manager) and EC2 services.

TypeScript
const role = new iam.Role(this, 'InstanceRole', {
  assumedBy: new iam.CompositePrincipal(new iam.ServicePrincipal('ec2.amazonaws.com'), new iam.ServicePrincipal('ssm.amazonaws.com'))
});
role.addManagedPolicy(iam.ManagedPolicy.fromAwsManagedPolicyName('AmazonSSMManagedEC2InstanceDefaultPolicy'));

Step 4 – Create a Security Group:

Define a security group to control the inbound and outbound traffic for the EC2 instance.

TypeScript
const ssmSecurityGroup = new ec2.SecurityGroup(this, 'SSMSecurityGroup', {
  vpc: ipv6Vpc, // Make sure to define the VPC
  allowAllIpv6Outbound: true
});

Step 5 – Create a Launch Template:

Define a launch template with all the necessary parameters for the EC2 instance including the role, security group, instance type, and user data.

TypeScript
const launchTemplate = new ec2.LaunchTemplate(this, 'LaunchTemplate', {
  // Configuration parameters
  //...
  role: role,
  securityGroup: ssmSecurityGroup,
  userData: userData,
});

Step 6 – Create an Auto Scaling Group:

Finally, create an Auto Scaling Group with the previously defined launch template. This ensures that the EC2 instances can scale in and out based on the defined capacity.

TypeScript
new autoscaling.AutoScalingGroup(this, 'ASG', {
  vpc: ipv6Vpc,
  launchTemplate: launchTemplate,
  maxCapacity: 1,
  minCapacity: 1,
  desiredCapacity: 1,
  vpcSubnets: ipv6Vpc.selectSubnets({
    subnetType: ec2.SubnetType.PRIVATE_ISOLATED
  })
});

Step 7 – Export the Stack Class:

This stack can now be used within your CDK application.

TypeScript
export class Ec2Stack extends cdk.Stack {
  // The constructor and above code here...
}

Notes – AWS-CDK EC2 Instance:

  • In the above code, ipv6Vpc is referenced but not defined. You should define this variable by creating a VPC with IPv6 support, or replace it with an existing VPC with IPv6 enabled in your account.

Now, you can use this class in your main application file to create the EC2 stack with the specified configurations.

Elsewhere On TurboGeek:  Sidestep the Pitfalls: 15 CDK Common Mistakes & How to Avoid Them

Richard.Bailey

Richard Bailey, a seasoned tech enthusiast, combines a passion for innovation with a knack for simplifying complex concepts. With over a decade in the industry, he's pioneered transformative solutions, blending creativity with technical prowess. An avid writer, Richard's articles resonate with readers, offering insightful perspectives that bridge the gap between technology and everyday life. His commitment to excellence and tireless pursuit of knowledge continues to inspire and shape the tech landscape.

You may also like...

1 Response

  1. 25/08/2023

    […] Let’s consider a simple AWS CDK App written in TypeScript: […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Translate ยป