1 Answer
- Newest
- Most votes
- Most comments
0
Creating an EC2 Instance with AWS CDK in Python
Setting up the CDK Environment
- Install Prerequisites:
- Install Node.js and npm (required for CDK)
- Install Python 3.x
- Install AWS CLI and configure it with your credentials
- Install AWS CDK:
npm install -g aws-cdk
- 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
- Initialize a new CDK project:
mkdir my-ec2-project
cd my-ec2-project
cdk init app --language python
- Activate the virtual environment:
python -m venv .venv
.venv\Scripts\activate
- Install dependencies:
pip install -r requirements.txt
- 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
- Synthesize the CloudFormation template:
cdk synth
- Deploy the stack:
cdk deploy
- 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
Relevant content
asked a year ago
- AWS OFFICIALUpdated 8 months ago
