Core Component of EC2 - krdheeraj51/aws-labs GitHub Wiki

VPC (Virtual Private Cloud):

  • A VPC is a virtual network dedicated to your AWS account. It is logically isolated from other virtual networks in the AWS cloud
  • When creating a VPC with CDK, you define its configuration, including the number of Availability Zones (max_azs) and subnet configurations (public, private)
  • Public subnets have direct access to the internet, while private subnets do not, often using a NAT Gateway for outbound traffic

Security Groups:

  • Security Groups act as virtual firewalls that control the inbound and outbound traffic for your EC2 instances
  • You define rules that specify which traffic is allowed, based on protocols, ports, and source/destination IP addresses
  • In your example, a security group allows SSH access (port 22)

User Data:

  • User data is a script that is executed when the EC2 instance is launched
  • It's commonly used to automate software installation, configuration, and service startup
  • Your example uses user data to install and start the Apache HTTP server

EC2 Instance:

  • The ec2.Instance construct defines the EC2 instance itself.
  • Key properties include:
    • instance_type: Specifies the hardware configuration of the instance (e.g., t2.micro)
    • machine_image: Defines the operating system and base software (e.g., Amazon Linux).Consider using Amazon Linux 2023 AMI for better price-performance and security
    • vpc: Associates the instance with a VPC.
    • security_group: Attaches the security group to the instance.
    • user_data: Provides the user data script to execute.

VPC Creation: The code initializes a new VPC with public and private subnets. max_azs=2 ensures high availability by distributing resources across two Availability Zones.

  • Security Group: A security group named "MySecurityGroup" is created within the VPC, configured to allow outbound traffic and SSH access on port 22.
  • User Data: The script updates the package list, installs the Apache web server, and starts the service.
  • EC2 Instance: The EC2 instance is created, specifying the instance type, machine image, VPC, security group, and user data.

Security Best Practices

  • Restrict SSH access to specific IP ranges instead of ec2.Peer.any_ipv4().
  • Consider using AWS Systems Manager (SSM) for access instead of SSH keys.
  • Enforce Instance Metadata Service Version 2 (IMDSv2)
  • Encrypt EBS volumes.
  • Place instances in private subnets.