[P8] AWS CDK Pattern (L3 Constructs): Cách Đơn Giản Hóa Việc Tạo Infrastructure Trên AWS

Mon, November 18, 2024 - 3 min read View Count
AWS CDK Deployment Process

AWS CDK Pattern (L3 Constructs): Cách Đơn Giản Hóa Việc Tạo Infrastructure Trên AWS

Giới thiệu

Khi làm việc với AWS CDK, bạn thường phải tạo và quản lý nhiều resources khác nhau (Lambda, DynamoDB, API Gateway,…). Việc sử dụng L1 và L2 constructs riêng lẻ có thể khiến code trở nên phức tạp và khó maintain. AWS CDK Patterns (L3 constructs) là giải pháp giúp đơn giản hóa việc này bằng cách gom nhóm các resources thường được sử dụng cùng nhau thành một construct duy nhất.

L3 Constructs là gì?

L3 constructs (hay CDK Patterns):

  • Là cấp độ cao nhất trong hệ thống construct của AWS CDK
  • Không chỉ tập trung vào một AWS resource đơn lẻ
  • Kết hợp nhiều AWS services với các cấu hình mặc định tối ưu
  • Được xây dựng từ L1 và L2 constructs
  • Được publish dưới dạng các thư viện riêng biệt

Nguồn tìm kiếm L3 Constructs

Có 2 nguồn chính để tìm kiếm L3 constructs:

  1. AWS Solutions Constructs:

    • Được cung cấp bởi AWS Solutions Team
    • Chứa các patterns phổ biến với best practices
    • Ví dụ: aws-apigateway-lambda, aws-lambda-dynamodb,…
  2. Construct Hub:

    • Kho lưu trữ trung tâm cho tất cả CDK constructs
    • Chứa cả patterns từ AWS và third-party
    • Có tính năng tìm kiếm và lọc hiệu quả
    • Hỗ trợ nhiều ngôn ngữ lập trình khác nhau

Ví dụ Thực Tế: Chuyển đổi từ L2 sang L3 Construct

from aws_cdk import (
    Stack,
    aws_dynamodb as dynamodb,
    aws_lambda as lambda_,
    CfnOutput,
    RemovalPolicy,
    Duration,
    aws_cloudwatch as cloudwatch,
)# requirements.txt
aws-solutions-constructs.aws-lambda-dynamodb>=2.74.0
 
# app_stack.py
class ServerlessAppStackUsingL3(Stack):
 
    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)
 
    
        #Set up the product backend
        products_backend = LambdaToDynamoDB(
            self, "ProductsBackend",
            lambda_function_props=lambda_.FunctionProps(
                code=lambda_.Code.from_asset("lambda_src"),
                runtime=lambda_.Runtime.PYTHON_3_10,
                handler="product_list_function.lambda_handler",
            ),
            table_environment_variable_name="TABLE_NAME",
            table_permissions="Read"
        )
    
        #Get reference to the resources created by the construct
        products_table = products_backend.dynamo_table
        product_list_function = products_backend.lambda_function
    
        #Config destroy policy for the table
        products_table.apply_removal_policy(RemovalPolicy.DESTROY)
    
        # Get function URL
        function_url = product_list_function.add_function_url(
            auth_type=lambda_.FunctionUrlAuthType.NONE
        )
 
        # Create output with the URL string
        CfnOutput(
            self,
            "ProductListFunctionUrl",
            value=function_url.url  # Use .url to get the string value
        )
    
        # Configure metrics to monitor the lambda function
        errors_metric = product_list_function.metric_errors(
            label="ProductListFunctionErrors",
            period=Duration.minutes(5),
            statistic=cloudwatch.Stats.SUM,
        )
 
        # Create an alarm to monitor the errors metric
        errors_metric.create_alarm(
            self,
            "ProductListErrorsAlarm",
            evaluation_periods=1,
            threshold=1,
            comparison_operator=cloudwatch.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD,
            treat_missing_data=cloudwatch.TreatMissingData.IGNORE,
        )

Deploy

1732094489052

1732094541907

Ưu điểm của L3 Constructs

  1. Đơn giản hóa code:

    • Giảm số lượng code cần viết
    • Tích hợp sẵn các best practices
    • Cấu hình mặc định tối ưu
  2. Tính nhất quán:

    • Đảm bảo các resources được cấu hình theo chuẩn
    • Tự động thiết lập permissions và relationships giữa các services
  3. Khả năng tùy chỉnh:

    • Vẫn có thể truy cập và tùy chỉnh từng resource riêng lẻ
    • Hỗ trợ override các cấu hình mặc định khi cần

Best Practices khi sử dụng L3 Constructs

  1. Tìm hiểu cấu hình mặc định:

    • Đọc kỹ documentation để hiểu các cấu hình mặc định
    • Xem xét liệu các cấu hình có phù hợp với use case của bạn
  2. Kiểm tra phiên bản:

    • Sử dụng version constraint trong requirements.txt
    • Đảm bảo compatibility với AWS CDK core version
  3. Tận dụng properties và methods:

    • Sử dụng các properties có sẵn để truy cập resources
    • Áp dụng các methods bổ sung khi cần tùy chỉnh (ví dụ: apply_removal_policy)

Kết luận

L3 constructs là một công cụ mạnh mẽ giúp đơn giản hóa việc tạo và quản lý AWS infrastructure. Bằng cách sử dụng các patterns có sẵn, bạn không chỉ tiết kiệm thời gian mà còn đảm bảo tuân thủ các best practices của AWS. Đặc biệt phù hợp cho những dự án mới hoặc khi bạn muốn nhanh chóng tạo một prototype với các configurations chuẩn.