🖥️

EC2 - Virtual Servers

EC2 là gì?

Amazon EC2 (Elastic Compute Cloud) cung cấp máy chủ ảo có thể scale theo nhu cầu. Bạn chỉ trả tiền cho những gì sử dụng.

💡 Instance Types phổ biến:
t3.micro: Free tier, dev/test
t3.medium: Small production
m5.large: General purpose
c5.xlarge: CPU-intensive

Launch EC2 với AWS CLI

# Cài đặt AWS CLI
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip && sudo ./aws/install

# Configure credentials
aws configure
# AWS Access Key ID: AKIA...
# AWS Secret Access Key: xxx
# Default region: ap-southeast-1

# Launch EC2 instance
aws ec2 run-instances \
    --image-id ami-0c55b159cbfafe1f0 \
    --instance-type t3.micro \
    --key-name my-key-pair \
    --security-group-ids sg-xxx \
    --subnet-id subnet-xxx \
    --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=MyServer}]'

# List instances
aws ec2 describe-instances --query 'Reservations[*].Instances[*].[InstanceId,State.Name,PublicIpAddress]'
📦

S3 - Object Storage

S3 Operations

# Tạo bucket
aws s3 mb s3://my-unique-bucket-name

# Upload file
aws s3 cp local-file.txt s3://my-bucket/path/
aws s3 sync ./local-folder s3://my-bucket/folder/

# Download file
aws s3 cp s3://my-bucket/file.txt ./local/

# List objects
aws s3 ls s3://my-bucket/

# Xóa bucket (phải rỗng)
aws s3 rb s3://my-bucket --force

S3 với Python (boto3)

import boto3
from botocore.exceptions import ClientError

s3 = boto3.client('s3')

# Upload file
def upload_file(file_path, bucket, object_name=None):
    if object_name is None:
        object_name = file_path
    
    try:
        s3.upload_file(file_path, bucket, object_name)
        print(f"Uploaded {file_path} to {bucket}/{object_name}")
    except ClientError as e:
        print(f"Error: {e}")
        return False
    return True

# Generate presigned URL
def create_presigned_url(bucket, object_name, expiration=3600):
    try:
        url = s3.generate_presigned_url(
            'get_object',
            Params={'Bucket': bucket, 'Key': object_name},
            ExpiresIn=expiration
        )
    except ClientError as e:
        print(f"Error: {e}")
        return None
    return url

# List objects
response = s3.list_objects_v2(Bucket='my-bucket', Prefix='images/')
for obj in response.get('Contents', []):
    print(f"{obj['Key']} - {obj['Size']} bytes")

Lambda - Serverless

📘 Serverless là gì?

AWS Lambda cho phép chạy code mà không cần quản lý server. Chỉ trả tiền khi function được gọi. Scale tự động.

Python Lambda Function

# lambda_function.py
import json

def lambda_handler(event, context):
    """
    AWS Lambda handler function
    
    Args:
        event: Input data (JSON)
        context: Runtime information
    
    Returns:
        API Gateway response format
    """
    
    # Parse request body
    body = json.loads(event.get('body', '{}'))
    name = body.get('name', 'World')
    
    response = {
        'statusCode': 200,
        'headers': {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        },
        'body': json.dumps({
            'message': f'Xin chào, {name}!',
            'requestId': context.aws_request_id
        })
    }
    
    return response
⚠️ Cold Start: Lambda function có thể mất 100ms-1s để "warm up" nếu không được gọi thường xuyên. Dùng Provisioned Concurrency để giảm.

Deploy với SAM CLI

# template.yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Globals:
  Function:
    Timeout: 30
    Runtime: python3.11

Resources:
  HelloFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: lambda_function.lambda_handler
      CodeUri: ./src
      Events:
        HelloApi:
          Type: Api
          Properties:
            Path: /hello
            Method: post
# Deploy
sam build
sam deploy --guided
📋

CloudFormation - IaC

Infrastructure as Code

CloudFormation cho phép định nghĩa infrastructure bằng YAML/JSON. Dễ version control, reproducible, và automatable.

# vpc-stack.yaml
AWSTemplateFormatVersion: '2010-09-09'
Description: 'VPC with public subnet'

Parameters:
  EnvironmentName:
    Type: String
    Default: dev

Resources:
  VPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.0.0.0/16
      EnableDnsHostnames: true
      Tags:
        - Key: Name
          Value: !Sub ${EnvironmentName}-vpc

  PublicSubnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
      CidrBlock: 10.0.1.0/24
      MapPublicIpOnLaunch: true
      AvailabilityZone: !Select [0, !GetAZs '']

  InternetGateway:
    Type: AWS::EC2::InternetGateway

Outputs:
  VpcId:
    Value: !Ref VPC
    Export:
      Name: !Sub ${EnvironmentName}-VpcId

🔗 Tài nguyên bổ sung

AWS Documentation
AWS Free Tier
Dịch vụ Cloud - Không Gian AI