AWS Cloud Development Kit (CDK) Deep Dive
1. Construct Tree Architecture
CDK app là một cây các Construct.
- *L1 (Cfn)**: CloudFormation Resource thô. Khó dùng.
- L2: Intent-based. Có defaults thông minh. (VD:
Buckettự động bật encryption). - L3 (Patterns): Kiến trúc trọn gói.
Use L2/L3
Luôn ưu tiên dùng L2 và L3 constructs. Chúng đóng gói sẵn các best practices của AWS (Security, Logging) giúp bạn viết ít code hơn và an toàn hơn.
2. CDK Synthesis & Deploy
- Synth: Code TS/Python -> CloudFormation Template (JSON/YAML).
- Deploy: CloudFormation Engine thực thi Template.
3. Testing Infrastructure
Vì là code thật, bạn có thể viết Unit Test cho hạ tầng!
- Snapshot Test: Đảm bảo template sinh ra không bị thay đổi bất ngờ.
- Fine-grained Assertion: "Kiểm tra xem Security Group có mở port 22 ra 0.0.0.0/0 không? Nếu có -> Fail build".
template.hasResourceProperties('AWS::EC2::SecurityGroup', {
SecurityGroupIngress: Match.arrayWith([
Match.objectLike({
CidrIp: '0.0.0.0/0',
FromPort: 22
})
])
});