-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtemplate.yaml
More file actions
276 lines (259 loc) · 9.67 KB
/
Copy pathtemplate.yaml
File metadata and controls
276 lines (259 loc) · 9.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: vac API - FastAPI on Lambda + API Gateway + Aurora Serverless v2 (PostgreSQL)
Parameters:
ImageUri:
Type: String
Description: >-
ECR에 푸시한 컨테이너 이미지 URI. API 함수와 마이그레이션 함수가 같은 이미지를
공유하고 ImageConfig.Command 로 핸들러만 구분한다.
예: 123456789012.dkr.ecr.ap-northeast-2.amazonaws.com/vac-api:latest
AllowedPattern: "^[0-9]{12}\\.dkr\\.ecr\\.[a-z0-9-]+\\.amazonaws\\.com/.+$"
ConstraintDescription: "계정ID.dkr.ecr.리전.amazonaws.com/리포지토리:태그 형식이어야 한다"
VpcId:
Type: AWS::EC2::VPC::Id
Description: Lambda와 Aurora를 배치할 VPC
PrivateSubnetIds:
Type: List<AWS::EC2::Subnet::Id>
Description: >-
Lambda/Aurora를 배치할 프라이빗 서브넷 (서로 다른 AZ 2개 이상).
VPC 엔드포인트 제약으로 한 AZ당 서브넷은 1개만 선택한다.
DBName:
Type: String
Default: vac
DBMinCapacity:
Type: Number
Default: 0
Description: >-
Aurora Serverless v2 최소 ACU. 0 이면 유휴 시 자동 일시정지되어 고정비가 거의
사라지는 대신 재개되는 첫 요청에 수 초가 추가된다. 상시 응답성이 필요하면 0.5.
DBMaxCapacity:
Type: Number
Default: 4
LogRetentionDays:
Type: Number
Default: 30
Globals:
Function:
Timeout: 30
MemorySize: 1024
Architectures:
- arm64
Environment:
Variables:
AUTO_CREATE_TABLES: "false"
DEBUG: "false"
Resources:
# ---------------------------------------------------------------- 네트워크
LambdaSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: vac Lambda functions
VpcId: !Ref VpcId
DBSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: vac Aurora cluster
VpcId: !Ref VpcId
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 5432
ToPort: 5432
SourceSecurityGroupId: !Ref LambdaSecurityGroup
Description: Lambda to Aurora
# 프라이빗 서브넷에는 인터넷 경로가 없으므로, Lambda가 Secrets Manager를 호출하려면
# NAT Gateway 또는 아래 인터페이스 엔드포인트가 필요하다 (엔드포인트 쪽이 저렴하다).
SecretsManagerEndpointSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: vac Secrets Manager VPC endpoint
VpcId: !Ref VpcId
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 443
ToPort: 443
SourceSecurityGroupId: !Ref LambdaSecurityGroup
Description: Lambda to Secrets Manager endpoint
SecretsManagerEndpoint:
Type: AWS::EC2::VPCEndpoint
Properties:
VpcId: !Ref VpcId
ServiceName: !Sub "com.amazonaws.${AWS::Region}.secretsmanager"
VpcEndpointType: Interface
# VPC의 DNS 이름을 엔드포인트로 해석시켜 boto3 코드를 수정하지 않아도 되게 한다.
PrivateDnsEnabled: true
# 인터페이스 엔드포인트는 배치한 서브넷마다 ENI가 생기고 ENI 단위로 시간당
# 과금된다. 시크릿 조회는 콜드 스타트당 1회뿐이라 AZ 하나로 충분하므로 첫 번째
# 서브넷에만 둔다(고정비 절반). 다른 AZ의 Lambda도 VPC 내부에서 그대로 접근한다.
# 대신 이 AZ에 장애가 나면 시크릿 조회가 막히므로, 가용성이 중요해지면
# !Ref PrivateSubnetIds 로 되돌린다.
SubnetIds:
- !Select [0, !Ref PrivateSubnetIds]
SecurityGroupIds:
- !Ref SecretsManagerEndpointSecurityGroup
# ---------------------------------------------------------------- 시크릿
DBSecret:
Type: AWS::SecretsManager::Secret
Properties:
Description: vac Aurora master credentials
GenerateSecretString:
SecretStringTemplate: '{"username": "vacadmin"}'
GenerateStringKey: password
PasswordLength: 32
# asyncpg URL 파싱과 충돌하지 않도록 일부 특수문자를 제외한다.
ExcludeCharacters: '"@/\''`'
JwtSecret:
Type: AWS::SecretsManager::Secret
Properties:
Description: vac JWT signing key
GenerateSecretString:
SecretStringTemplate: "{}"
GenerateStringKey: secret_key
PasswordLength: 64
ExcludePunctuation: true
# ---------------------------------------------------------- Aurora Serverless v2
DBSubnetGroup:
Type: AWS::RDS::DBSubnetGroup
Properties:
DBSubnetGroupDescription: vac Aurora subnet group
SubnetIds: !Ref PrivateSubnetIds
DBCluster:
Type: AWS::RDS::DBCluster
DeletionPolicy: Snapshot
UpdateReplacePolicy: Snapshot
Properties:
Engine: aurora-postgresql
EngineVersion: "17.5"
DatabaseName: !Ref DBName
# RDS Data API. 클러스터가 프라이빗 서브넷에 있어도 콘솔 쿼리 편집기와
# aws rds-data CLI 로 SQL 을 실행할 수 있다. 접근은 IAM + 시크릿으로 통제된다.
EnableHttpEndpoint: true
MasterUsername: !Sub "{{resolve:secretsmanager:${DBSecret}:SecretString:username}}"
MasterUserPassword: !Sub "{{resolve:secretsmanager:${DBSecret}:SecretString:password}}"
DBSubnetGroupName: !Ref DBSubnetGroup
VpcSecurityGroupIds:
- !Ref DBSecurityGroup
ServerlessV2ScalingConfiguration:
MinCapacity: !Ref DBMinCapacity
MaxCapacity: !Ref DBMaxCapacity
StorageEncrypted: true
BackupRetentionPeriod: 7
DBInstance:
Type: AWS::RDS::DBInstance
Properties:
DBClusterIdentifier: !Ref DBCluster
Engine: aurora-postgresql
DBInstanceClass: db.serverless
PubliclyAccessible: false
DBSecretAttachment:
Type: AWS::SecretsManager::SecretTargetAttachment
Properties:
SecretId: !Ref DBSecret
TargetId: !Ref DBCluster
TargetType: AWS::RDS::DBCluster
# ---------------------------------------------------------------- API
HttpApi:
Type: AWS::Serverless::HttpApi
Properties:
StageName: !Ref AWS::StackName
# 필요 시 CORS 허용 오리진을 실제 클라이언트 도메인으로 좁힌다.
CorsConfiguration:
AllowOrigins:
- "*"
AllowHeaders:
- Authorization
- Content-Type
AllowMethods:
- GET
- POST
- DELETE
- OPTIONS
ApiFunction:
Type: AWS::Serverless::Function
DependsOn: SecretsManagerEndpoint
Properties:
PackageType: Image
ImageUri: !Ref ImageUri
ImageConfig:
Command:
- app.lambda_handler.handler
# RDS Proxy 없이 Aurora에 직접 접속하므로 동시 실행 수가 곧 DB 커넥션 수가 되지만,
# 현재 계정의 Lambda 동시성 한도(30 미만)가 이미 상한 역할을 한다.
# ReservedConcurrentExecutions 는 미예약 동시성을 10 미만으로 떨어뜨릴 수 없어
# 이 한도에서는 설정 자체가 거부된다. 한도를 증설하면 그때 다시 넣는다.
VpcConfig:
SecurityGroupIds:
- !Ref LambdaSecurityGroup
SubnetIds: !Ref PrivateSubnetIds
Environment:
Variables:
DB_SECRET_ARN: !Ref DBSecret
DB_HOST: !GetAtt DBCluster.Endpoint.Address
DB_NAME: !Ref DBName
JWT_SECRET_ARN: !Ref JwtSecret
# API Gateway 스테이지 경로를 URL에서 제거한다.
API_GATEWAY_BASE_PATH: !Sub "/${AWS::StackName}"
Policies:
- VPCAccessPolicy: {}
- AWSSecretsManagerGetSecretValuePolicy:
SecretArn: !Ref DBSecret
- AWSSecretsManagerGetSecretValuePolicy:
SecretArn: !Ref JwtSecret
Events:
Root:
Type: HttpApi
Properties:
ApiId: !Ref HttpApi
Path: /
Method: ANY
Proxy:
Type: HttpApi
Properties:
ApiId: !Ref HttpApi
Path: /{proxy+}
Method: ANY
ApiFunctionLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub "/aws/lambda/${ApiFunction}"
RetentionInDays: !Ref LogRetentionDays
# 배포 후 수동/파이프라인에서 1회 호출하여 스키마를 마이그레이션한다.
MigrationFunction:
Type: AWS::Serverless::Function
DependsOn: SecretsManagerEndpoint
Properties:
PackageType: Image
ImageUri: !Ref ImageUri
ImageConfig:
Command:
- app.lambda_handler.migrate_handler
Timeout: 300
VpcConfig:
SecurityGroupIds:
- !Ref LambdaSecurityGroup
SubnetIds: !Ref PrivateSubnetIds
Environment:
Variables:
DB_SECRET_ARN: !Ref DBSecret
DB_HOST: !GetAtt DBCluster.Endpoint.Address
DB_NAME: !Ref DBName
Policies:
- VPCAccessPolicy: {}
- AWSSecretsManagerGetSecretValuePolicy:
SecretArn: !Ref DBSecret
Outputs:
ApiUrl:
Description: API Base URL
Value: !Sub "https://${HttpApi}.execute-api.${AWS::Region}.amazonaws.com/${AWS::StackName}/api/v1"
DBEndpoint:
Description: Aurora cluster writer endpoint
Value: !GetAtt DBCluster.Endpoint.Address
MigrationFunctionName:
Description: alembic upgrade head 를 실행하는 Lambda 함수명
Value: !Ref MigrationFunction
DBSecretArn:
Description: Aurora 접속 정보 시크릿 (쿼리 편집기 인증에 사용)
Value: !Ref DBSecret
DBClusterArn:
Description: Aurora 클러스터 ARN (aws rds-data execute-statement 에 사용)
Value: !Sub "arn:${AWS::Partition}:rds:${AWS::Region}:${AWS::AccountId}:cluster:${DBCluster}"