• About Us
  • Contact Us
  • Advertise
  • Privacy Policy
  • Guest Post
No Result
View All Result
Digital Phablet
  • Home
  • NewsLatest
  • Technology
    • Education Tech
    • Home Tech
    • Office Tech
    • Fintech
    • Digital Marketing
  • Social Media
  • Gaming
  • Smartphones
  • AI
  • Reviews
  • Interesting
  • How To
  • Home
  • NewsLatest
  • Technology
    • Education Tech
    • Home Tech
    • Office Tech
    • Fintech
    • Digital Marketing
  • Social Media
  • Gaming
  • Smartphones
  • AI
  • Reviews
  • Interesting
  • How To
No Result
View All Result
Digital Phablet
No Result
View All Result

Home » How to Create an AWS EC2 Instance Using CDK and Python

How to Create an AWS EC2 Instance Using CDK and Python

Emily Smith by Emily Smith
January 25, 2026
in How To
Reading Time: 4 mins read
A A
AWS Security: Handling Sophisticated Attacks & Collaborating with Authorities
ADVERTISEMENT

Select Language:

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.

ADVERTISEMENT

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

ADVERTISEMENT

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:

ADVERTISEMENT

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.

ChatGPT ChatGPT Perplexity AI Perplexity Gemini AI Logo Gemini AI Grok AI Logo Grok AI
Google Banner
ADVERTISEMENT
Emily Smith

Emily Smith

Emily is a digital marketer in Austin, Texas. She enjoys gaming, playing guitar, and dreams of traveling to Japan with her golden retriever, Max.

Related Posts

AI

Ant CEO Han Xinyi Sends Company-Wide Note: Reject Small Wins, Launch AI Incentive Plan

February 2, 2026
World's Top 50 Countries by GDP (PPP)

1.  China – $43.4 Trillion
2.  United Sta
Infotainment

Top 50 Countries by GDP PPP in 2023

February 2, 2026
Wildest Outfits at the 2026 Grammys: Chappell Roan’s Bold Gown
Entertainment

Wildest Outfits at the 2026 Grammys: Chappell Roan’s Bold Gown

February 2, 2026
BMW Names Christian Ach as New China President and CEO
Business

BMW Names Christian Ach as New China President and CEO

February 2, 2026
Next Post
Mrbeast YouTube Subscriber Growth Over the Years 

2012: 22
2013: 612
2014: 1,60

MrBeast's YouTube Subscriber Growth Over the Years

  • About Us
  • Contact Us
  • Advertise
  • Privacy Policy
  • Guest Post

© 2026 Digital Phablet

No Result
View All Result
  • Home
  • News
  • Technology
    • Education Tech
    • Home Tech
    • Office Tech
    • Fintech
    • Digital Marketing
  • Social Media
  • Gaming
  • Smartphones

© 2026 Digital Phablet