Skip to content

How to create EC2 instance via CDK in python language?

0

I want create a EC2 instance via CDK in python language but before I have to setup CDK envirnoment for my AWS account. I will do it via Window laptop and VS code. Can you please give me step by step information and provide CDK code in python language for create EC2 instance.

asked 10 months ago260 views

1 Answer
0

Creating an EC2 Instance with AWS CDK in Python

Setting up the CDK Environment

  1. Install Prerequisites:
  • Install Node.js and npm (required for CDK)
  • Install Python 3.x
  • Install AWS CLI and configure it with your credentials
  1. Install AWS CDK:
npm install -g aws-cdk
  1. Bootstrap CDK in your AWS Account:
cdk bootstrap

This creates the necessary infrastructure for CDK to manage resources in your account. You only need to do this once per account/region.

Creating a CDK Project for EC2

  1. Initialize a new CDK project:
mkdir my-ec2-project
cd my-ec2-project
cdk init app --language python
  1. Activate the virtual environment:
python -m venv .venv
.venv\Scripts\activate
  1. Install dependencies:
pip install -r requirements.txt
  1. Add EC2 dependencies:
pip install aws-cdk.aws-ec2

Python Code for Creating an EC2 Instance

Edit the file my_ec2_project/my_ec2_project_stack.py with the following code:

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, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)

# Create a 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
security_group = ec2.SecurityGroup(self, "SecurityGroup",
vpc=vpc,
description="Allow SSH (TCP port 22) and HTTP (TCP port 80)",
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"
)

# Create a role for the EC2 instance
role = iam.Role(self, "EC2Role",
assumed_by=iam.ServicePrincipal("ec2.amazonaws.com")
)

# Add managed policy to the role
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 or create one
)

# Add user data to install a web server
instance.add_user_data(
"yum update -y",
"yum install -y httpd",
"systemctl start httpd",
"systemctl enable httpd",
"echo '<html><body><h1>Hello from CDK!</h1></body></html>' > /var/www/html/index.html"
)

Deploy the Stack

  1. Synthesize the CloudFormation template:
cdk synth
  1. Deploy the stack:
cdk deploy
  1. Clean up when done:
cdk destroy

This code creates:

  • A VPC with public subnets
  • A security group allowing SSH and HTTP traffic
  • An IAM role for the EC2 instance
  • An EC2 instance running Amazon Linux 2
  • User data that installs and configures a basic web server

Remember to replace "my-key-pair" with your actual key pair name or create one before deploying.
Sources
Community | Bootstrapping an Amazon EC2 Instance Using User-data to Run a Python Web App
Instance — AWS Cloud Development Kit 2.234.0 documentation
ec2_setup.py - AWS Code Sample

answered 10 months ago

EXPERT

reviewed 10 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.