How to Create an AWS EC2 Instance Using CDK and Python

AWS Security: Handling Sophisticated Attacks & Collaborating with Authorities

Written by

in

Here’s a simple guide to help you set up an EC2 instance using the AWS Cloud Development Kit (CDK). Follow these steps to get your web server up and running smoothly.

First, ensure you have the necessary tools installed on your computer. You’ll need Node.js and npm since they are required for CDK. Also, install Python 3.x and the AWS CLI. Make sure to configure the AWS CLI with your credentials so you can access your AWS account.

Next, you should install the AWS CDK globally on your system. Open your terminal and run:

npm install -g aws-cdk

After the CDK is installed, you need to prepare your AWS account for CDK deployment. Run the following command in your terminal:

cdk bootstrap

This command sets up the basic infrastructure in your account and runs only once per account and region.

Now, let’s create a new project for your EC2 instance. In your terminal, make a new directory and initialize the project:

mkdir my-ec2-project
cd my-ec2-project
cdk init app –language python

Activate a virtual environment to manage dependencies:

python -m venv .venv

On Windows, activate with:

.venv\Scripts\activate

On macOS or Linux, use:

source .venv/bin/activate

Install the required Python dependencies:

pip install -r requirements.txt

You will also need to add the EC2 module to handle Amazon EC2 resources:

pip install aws-cdk.aws-ec2

Now, open the main stack file, usually located at my_ec2_project/my_ec2_project_stack.py, and replace its content with code that defines your network and instance:

python
from aws_cdk import (
Stack,
aws_ec2 as ec2,
aws_iam as iam,
)
from constructs import Construct

class MyEc2ProjectStack(Stack):
def init(self, scope: Construct, id: str, kwargs) -> None:
super().init(scope, id,
kwargs)

    # Create a Virtual Private Cloud (VPC)
    vpc = ec2.Vpc(self, "MyVPC",
                  max_azs=2,
                  nat_gateways=0,
                  subnet_configuration=[
                      ec2.SubnetConfiguration(
                          name="public",
                          subnet_type=ec2.SubnetType.PUBLIC,
                      )
                  ])

    # Create a security group to allow SSH and HTTP
    security_group = ec2.SecurityGroup(self, "SecurityGroup",
                                         vpc=vpc,
                                         description="Allow SSH and HTTP",
                                         allow_all_outbound=True)
    security_group.add_ingress_rule(
        ec2.Peer.any_ipv4(),
        ec2.Port.tcp(22),
        "Allow SSH access from anywhere"
    )
    security_group.add_ingress_rule(
        ec2.Peer.any_ipv4(),
        ec2.Port.tcp(80),
        "Allow HTTP access from anywhere"
    )

    # Define an IAM role for the EC2 instance
    role = iam.Role(self, "EC2Role",
                    assumed_by=iam.ServicePrincipal("ec2.amazonaws.com"))
    role.add_managed_policy(
        iam.ManagedPolicy.from_aws_managed_policy_name("AmazonSSMManagedInstanceCore")
    )

    # Create the EC2 instance
    instance = ec2.Instance(self, "MyInstance",
                            vpc=vpc,
                            instance_type=ec2.InstanceType("t2.micro"),
                            machine_image=ec2.AmazonLinuxImage(
                                generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2),
                            security_group=security_group,
                            role=role,
                            vpc_subnets=ec2.SubnetSelection(
                                subnet_type=ec2.SubnetType.PUBLIC),
                            key_name="my-key-pair")  # Replace with your key pair name

    # Add commands to install and start a web server
    instance.add_user_data(
        "yum update -y",
        "yum install -y httpd",
        "systemctl start httpd",
        "systemctl enable httpd",
        "echo '<h1>My Web Server</h1>' > /var/www/html/index.html"
    )

Before deploying, make sure to replace "my-key-pair" with your actual key pair name. This key is needed to access your instance via SSH.

Finally, to deploy your setup, run these commands in your terminal:

cdk synth
cdk deploy

The cdk synth command converts your code into a CloudFormation template, and cdk deploy sends it to AWS to create the resources.

When you’re done testing, you can remove all resources by running:

cdk destroy

This setup creates a basic network with a public EC2 instance, security rules for SSH and HTTP, and installs a simple web server. This is a great foundation for hosting web applications on AWS.