[P5] Construcs: Hiểu Và Sử Dụng AWS CDK L1 Constructs cơ bản

Fri, November 15, 2024 - 4 min read View Count
AWS CDK Deployment Process

Xem những bài viết cùng series

Giới thiệu

AWS Cloud Development Kit (CDK) là một framework mạnh mẽ cho phép bạn định nghĩa infrastructure dưới dạng code. Trong bài viết này, chúng ta sẽ tìm hiểu chi tiết về L1 constructs - các building block cơ bản nhất của AWS CDK, thông qua việc xây dựng một VPC infrastructure hoàn chỉnh.

L1 Constructs Là Gì?

L1 constructs là các component cấp thấp nhất trong CDK, mapping 1-1 với các CloudFormation resources. Chúng có một số đặc điểm quan trọng:

  • Tên luôn bắt đầu bằng prefix “Cfn” (ví dụ: CfnVPC, CfnSubnet)
  • Map trực tiếp với CloudFormation resource types
  • Được tạo tự động từ CloudFormation specification
  • Yêu cầu hiểu biết chi tiết về từng resource type

Cấu Trúc Của Một L1 Construct

Mọi L1 construct đều được khởi tạo với 3 thành phần chính:

  1. scope: Parent của construct (thường là Stack)
  2. id: Định danh unique trong stack
  3. props: Các thuộc tính cấu hình specific cho resource đó

Ví dụ cơ bản:

my_vpc = ec2.CfnVPC(
    self,                       # scope
    "MyVpc",                    # id
    cidr_block="10.0.0.0/16"   # props
)

Xây Dựng VPC Infrastructure Với L1 Constructs

Kiến trúc VPC

VPC Architecture

0. Initial Setup

mkdir sample-app
cdk init app --language python

1. Tạo VPC Base

# sample_app_stack.py
from aws_cdk import aws_ec2 as ec2
 
my_vpc = ec2.CfnVPC(
    self,
    "MyVpc",
    cidr_block="10.0.0.0/16",
    enable_dns_hostnames=True,
    enable_dns_support=True
)

2. Thêm Internet Gateway

# sample_app_stack.py
my_internet_gateway = ec2.CfnInternetGateway(self, "MyInternetGateway")
 
# Attach Internet Gateway vào VPC
ec2.CfnVPCGatewayAttachment(
    self,
    "MyVPCGatewayAttachment",
    vpc_id=my_vpc.attr_vpc_id,
    internet_gateway_id=my_internet_gateway.attr_internet_gateway_id,
)

3. Tạo Subnets và Route Tables

# sample_app_stack.py
# Định nghĩa cấu trúc subnets
subnet_config = [
    {"cidrMask": 24, "name": "Ingress 1", "public": True},
    {"cidrMask": 24, "name": "Ingress 2", "public": True},
    {"cidrMask": 24, "name": "Application 2", "public": False},
    {"cidrMask": 24, "name": "Application 3", "public": False},
]
 
for index, config in enumerate(subnet_config):
    subnet_resource = ec2.CfnSubnet(
        self,
        f"MySubnet{index+1}",
        vpc_id=my_vpc.attr_vpc_id,
        cidr_block=f"10.0.{index}.0/{config['cidrMask']}",
        availability_zone=Stack.availability_zones.fget(self)[index % 2],
        map_public_ip_on_launch=config["public"],
    )
 
    # create route table
    route_table = ec2.CfnRouteTable(
        self, f"MyRouteTable{index}", vpc_id=my_vpc.attr_vpc_id
    )
 
    # Associate route table with subnet
    ec2.CfnSubnetRouteTableAssociation(
        self,
        f"MySubnetRouteTableAssociation{index}",
        route_table_id=route_table.attr_route_table_id,
        subnet_id=subnet_resource.attr_subnet_id,
    )
 
    # If subnet is public, create route to internet gateway
    if config["public"]:
        ec2.CfnRoute(
            self,
            f"MyRoute{index}",
            route_table_id=route_table.attr_route_table_id,
            destination_cidr_block="0.0.0.0/0",
            gateway_id=my_internet_gateway.attr_internet_gateway_id,
        )

4.0 Bootstrap CDK

Chỉ cần thực hiện bước này một lần để thiết lập môi trường CDK. Nếu bạn đã làm điều này, bạn có thể bỏ qua bước này.

Set up aws credentials (cần có IAM user với quyền admin)

aws configure

Install CDK CLI

npm install -g aws-cdk

Bootstrap CDK

Bước này sẽ tạo các resources cần thiết để CDK có thể deploy stack

cdk bootstrap

4.1 Deploy VPC Infrastructure

Tạo CloudFormation template

cdk synth  

Syth

Triển khai VPC infrastructure

cdk deploy

Deploy

5. Kiểm Tra VPC Trên AWS Console

Console

6. Xóa VPC Infrastructure

cdk destroy

Destroy

Các Tips Quan Trọng Khi Làm Việc Với L1 Constructs

  1. Sử Dụng CDK Construct Library Reference:

    • Truy cập documentation để tìm các constructs cần thiết
    • Tìm theo prefix “Cfn” để xác định L1 constructs
    • Check các required properties trong phần Parameters
  2. Attribute References:

    • Sử dụng attr_ prefix để access resource attributes
    • Ví dụ: my_vpc.attr_vpc_id để lấy VPC ID
  3. Best Practices:

    • Sử dụng Python loops và conditions để tránh code trùng lặp
    • Đặt tên ID theo convention PascalCase
    • Tổ chức code theo logical groups
  4. Deployment và Testing:

    • Sử dụng cdk synth để kiểm tra template trước khi deploy
    • Kiểm tra CDK Explorer để verify construct tree
    • Sử dụng cdk deploy để triển khai infrastructure
    • Xem CloudFormation console để verify resources

Khi Nào Nên Sử Dụng L1 Constructs?

L1 constructs phù hợp khi:

  • Bạn đang chuyển từ CloudFormation sang CDK
  • Resource bạn cần chưa có L2/L3 construct tương ứng
  • Bạn cần control chi tiết về resource configuration
  • Bạn đã quen thuộc với CloudFormation

Kết Luận

L1 constructs là nền tảng của AWS CDK, cho phép bạn định nghĩa AWS resources với sự linh hoạt cao. Mặc dù chúng yêu cầu nhiều configuration thủ công, việc kết hợp với các tính năng của ngôn ngữ lập trình như Python có thể giúp code của bạn clean và maintainable hơn nhiều so với CloudFormation templates truyền thống.

Trong các bài học tiếp theo, chúng ta sẽ khám phá L2 constructs - cung cấp nhiều abstraction và defaults hợp lý hơn theo AWS best practices.