[P8] AWS CDK Pattern (L3 Constructs): Cách Đơn Giản Hóa Việc Tạo Infrastructure Trên AWS
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 (hay CDK Patterns):
Có 2 nguồn chính để tìm kiếm L3 constructs:
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,
)
Đơn giản hóa code:
Tính nhất quán:
Khả năng tùy chỉnh:
Tìm hiểu cấu hình mặc định:
Kiểm tra phiên bản:
Tận dụng properties và methods:
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.