-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtemplate.yaml
More file actions
668 lines (616 loc) · 20.8 KB
/
template.yaml
File metadata and controls
668 lines (616 loc) · 20.8 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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
# -----------------------------------------------------------------------------
# Planttracer stack.
# Creates:
# - VM
# - Lambda to Resize and Track
# - SQS to allow tracker to queue longer track and return
#
# Deploy (guided the first time):
# sam deploy --guided
#
# Subsequent deploys:
# sam deploy
# -----------------------------------------------------------------------------
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
Single EC2 instance + IAM access to DynamoDB + Route53 DNS A record to an Elastic IP.
(No load balancer.)
Globals:
Function:
Environment:
Variables:
POWERTOOLS_SERVICE_NAME: "planttracer"
LOG_LEVEL: !Ref LogLevel
TABLE_PREFIX: !Ref AWS::StackName
POWERTOOLS_EVENT_HANDLER_AUTO_JSON_DECIMAL: "true"
Layers:
- arn:aws:lambda:us-east-1:017000801446:layer:AWSLambdaPowertoolsPythonV2-Arm64:60
Parameters:
HostedZoneId:
Type: String
Description: Route53 Hosted Zone ID for planttracer.com (e.g., Z123ABC...)
Default: "Z02875141U8JDG1N8N5BO"
BaseDomain:
Type: String
Description: "base domain in which the hostnames are created"
Default: "planttracer.com"
WildcardCertificateArn:
Type: String
Default: "arn:aws:acm:us-east-1:343218180669:certificate/66c18f6a-49b3-4be7-a232-a371cbfef29b"
Description: "wildcard certificate; leave blank to create a certificate on the fly."
EC2KeyPairName:
Type: AWS::EC2::KeyPair::KeyName
Description: "EC2 KeyPair name for SSH access to server. Keypair must be uploaded to EC2"
ImageBucketName:
Type: String
Description: "Existing S3 bucket for videos; must outlive the stack (long-term archive). Do not include s3://"
Default: planttracer2
UbuntuAmiId:
Type: AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>
Description: "Ubuntu 24.04 LTS (arm64) via SSM"
Default: /aws/service/canonical/ubuntu/server/24.04/stable/current/arm64/hvm/ebs-gp3/ami-id
InstanceType:
Type: String
Default: t4g.small
AllowedValues:
- t4g.nano
- t4g.micro
- t4g.small
- t4g.medium
Description: "Choose an instance type compatible with your AMI architecture."
GitRepoUrl:
Type: String
Description: "Git repository URL to clone on boot (e.g., https://github.com/Plant-Tracer/webapp.git)."
Default: "https://github.com/Plant-Tracer/webapp.git"
GitBranch:
Type: String
Default: main
Description: "Git branch/tag to checkout."
AdminEmail:
Type: String
Default: plantadmin@planttracer.com
Description: "Email address for course administrator of first course"
CourseId:
Type: String
Description: "Course ID for the first course (e.g. Course1)"
AdminName:
Type: String
Description: "Display name of the course administrator"
CourseName:
Type: String
Default: "Plant motion 101"
Description: "Name of first course"
LogLevel:
Type: String
Default: INFO
AllowedValues: [CRITICAL, ERROR, WARNING, INFO, DEBUG, NOTSET]
Description: Default LOG_LEVEL environment value for the function
Resources:
# --- Minimal networking: VPC + one public subnet + IGW + route table ---
Vpc:
Type: AWS::EC2::VPC
Properties:
CidrBlock: 10.30.0.0/16
EnableDnsHostnames: true
EnableDnsSupport: true
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-vpc"
InternetGateway:
Type: AWS::EC2::InternetGateway
VpcGatewayAttachment:
Type: AWS::EC2::VPCGatewayAttachment
Properties:
VpcId: !Ref Vpc
InternetGatewayId: !Ref InternetGateway
PublicSubnet:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref Vpc
CidrBlock: 10.30.10.0/24
MapPublicIpOnLaunch: true
AvailabilityZone: !Select [0, !GetAZs ""]
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-public-subnet"
PublicRouteTable:
Type: AWS::EC2::RouteTable
Properties:
VpcId: !Ref Vpc
PublicRoute:
Type: AWS::EC2::Route
DependsOn: VpcGatewayAttachment
Properties:
RouteTableId: !Ref PublicRouteTable
DestinationCidrBlock: 0.0.0.0/0
GatewayId: !Ref InternetGateway
PublicSubnetRouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
SubnetId: !Ref PublicSubnet
RouteTableId: !Ref PublicRouteTable
# --- Security Group: open 22/80/443 to the world ---
InstanceSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: "Open inbound 22,80,443 from the world."
VpcId: !Ref Vpc
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 22
ToPort: 22
CidrIp: 0.0.0.0/0
- IpProtocol: tcp
FromPort: 80
ToPort: 80
CidrIp: 0.0.0.0/0
- IpProtocol: tcp
FromPort: 443
ToPort: 443
CidrIp: 0.0.0.0/0
# --- Logs ---
LambdaFunctionLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub "/aws/lambda/${LambdaFunction}"
RetentionInDays: 30
DeletionPolicy: Retain
UpdateReplacePolicy: Retain
# --- Stable public IP + DNS name ---
InstanceEip:
Type: AWS::EC2::EIP
Properties:
Domain: vpc
# Create DNS record for the VM's primary name
VmDnsARecord:
Type: AWS::Route53::RecordSet
Properties:
HostedZoneId: !Ref HostedZoneId
Name: !Sub "${AWS::StackName}.${BaseDomain}."
Type: A
TTL: 30
ResourceRecords:
- !Ref InstanceEip
# Create DNS record for the VM-demo name.
VmDemoDnsARecord:
Type: AWS::Route53::RecordSet
Properties:
HostedZoneId: !Ref HostedZoneId
Name: !Sub "${AWS::StackName}-demo.${BaseDomain}."
Type: A
TTL: 30
ResourceRecords:
- !Ref InstanceEip
# --- EC2 instance ---
AppInstance:
Type: AWS::EC2::Instance
Properties:
MetadataOptions: { HttpTokens: required, HttpEndpoint: enabled }
ImageId: !Ref UbuntuAmiId
InstanceType: !Ref InstanceType
KeyName: !Ref EC2KeyPairName
IamInstanceProfile: !Ref Ec2InstanceProfile
SubnetId: !Ref PublicSubnet
SecurityGroupIds: [!Ref InstanceSecurityGroup]
BlockDeviceMappings:
- DeviceName: /dev/sda1
Ebs:
VolumeSize: 20
VolumeType: gp3
DeleteOnTermination: true
CreditSpecification:
CPUCredits: unlimited
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-app"
UserData:
Fn::Base64:
Fn::Sub:
- |
#!/usr/bin/env bash
exec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1
set -euo pipefail
lsblk
df -h
# Create the environment variables
mkdir -p /etc/environment.d
touch /etc/environment.d/10-planttracer.conf
echo "LOG_LEVEL=\"${LogLevel}\"" >> /etc/environment.d/10-planttracer.conf
echo "HOSTNAME=\"${AWS::StackName}\"" >> /etc/environment.d/10-planttracer.conf
echo "DOMAIN=\"${BaseDomain}\"" >> /etc/environment.d/10-planttracer.conf
echo "ADMIN_EMAIL=\"${AdminEmail}\"" >> /etc/environment.d/10-planttracer.conf
echo "COURSE_ID=\"${CourseId}\"" >> /etc/environment.d/10-planttracer.conf
echo "ADMIN_NAME=\"${AdminName}\"" >> /etc/environment.d/10-planttracer.conf
echo "COURSE_NAME=\"${CourseName}\"" >> /etc/environment.d/10-planttracer.conf
echo "DYNAMODB_TABLE_PREFIX=\"${AWS::StackName}-\"" >> /etc/environment.d/10-planttracer.conf
echo "PLANTTRACER_S3_BUCKET=\"${ImageBucketName}\"" >> /etc/environment.d/10-planttracer.conf
echo "LAMBDA_RESIZE_ARN=\"${LambdaResizeArn}\"" >> /etc/environment.d/10-planttracer.conf
# SERVER_EMAIL is the From address for outgoing mail; configured as verified sender in SES
echo "SERVER_EMAIL=\"admin@planttracer.com\"" >> /etc/environment.d/10-planttracer.conf
# Install essentials
export DEBIAN_FRONTEND=noninteractive
apt-get update -y
apt-get install -y git ca-certificates curl make python3-poetry
snap install --classic aws-cli
snap install --classic emacs
# Clone webapp
install -d -m 0755 /opt/
git clone --branch "${GitBranch}" --depth 1 "${GitRepoUrl}" /opt/webapp
# Bucket ${ImageBucketName} must already exist (long-term archive); bootstrap configures CORS only
export PATH=$PATH:/snap/bin
echo Set permissions and run bootstrap
sudo chown -R ubuntu:ubuntu /opt/webapp
runuser -l ubuntu -c 'cd /opt/webapp && bash etc/bootstrap.sh 2>&1 | col -b'
echo "User data finished executing."
- LambdaResizeArn: !GetAtt LambdaFunction.Arn
InstanceEipAssociation:
Type: AWS::EC2::EIPAssociation
Properties:
AllocationId: !GetAtt InstanceEip.AllocationId
InstanceId: !Ref AppInstance
################################################################
### Create the DynamoDB tables
UsersTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: !Sub "${AWS::StackName}-users"
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: user_id
AttributeType: S
- AttributeName: email
AttributeType: S
KeySchema:
- AttributeName: user_id
KeyType: HASH
GlobalSecondaryIndexes:
- IndexName: email_idx
KeySchema:
- AttributeName: email
KeyType: "HASH"
Projection:
ProjectionType: "ALL"
UniqueEmailsTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: !Sub "${AWS::StackName}-unique_emails"
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: email
AttributeType: S
KeySchema:
- AttributeName: email
KeyType: HASH
ApiKeysTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: !Sub "${AWS::StackName}-api_keys"
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: api_key
AttributeType: S
- AttributeName: user_id
AttributeType: S
KeySchema:
- AttributeName: api_key
KeyType: HASH
GlobalSecondaryIndexes:
- IndexName: user_id_idx
KeySchema:
- AttributeName: user_id
KeyType: "HASH"
Projection:
ProjectionType: "ALL"
CoursesTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: !Sub "${AWS::StackName}-courses"
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: course_id
AttributeType: S
- AttributeName: course_key
AttributeType: S
KeySchema:
- AttributeName: course_id
KeyType: HASH
GlobalSecondaryIndexes:
- IndexName: course_key_idx
KeySchema:
- AttributeName: course_key
KeyType: "HASH"
Projection:
ProjectionType: "ALL"
CourseUsersTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: !Sub "${AWS::StackName}-course_users"
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: course_id
AttributeType: S
- AttributeName: user_id
AttributeType: S
KeySchema:
- AttributeName: course_id
KeyType: HASH
- AttributeName: user_id
KeyType: RANGE
MoviesTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: !Sub "${AWS::StackName}-movies"
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: movie_id
AttributeType: S
- AttributeName: course_id
AttributeType: S
- AttributeName: user_id
AttributeType: S
KeySchema:
- AttributeName: movie_id
KeyType: HASH
GlobalSecondaryIndexes:
- IndexName: course_id_idx
KeySchema:
- AttributeName: course_id
KeyType: "HASH"
Projection:
ProjectionType: "ALL"
- IndexName: user_id_idx
KeySchema:
- AttributeName: user_id
KeyType: "HASH"
Projection:
ProjectionType: "ALL"
MovieFramesTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: !Sub "${AWS::StackName}-movie_frames"
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: movie_id
AttributeType: S
- AttributeName: frame_number
AttributeType: N
KeySchema:
- AttributeName: movie_id
KeyType: HASH
- AttributeName: frame_number
KeyType: RANGE
LogsTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: !Sub "${AWS::StackName}-logs"
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: log_id
AttributeType: S
- AttributeName: ipaddr
AttributeType: S
- AttributeName: user_id
AttributeType: S
- AttributeName: course_id
AttributeType: S
- AttributeName: time_t
AttributeType: N
KeySchema:
- AttributeName: log_id
KeyType: HASH
GlobalSecondaryIndexes:
- IndexName: ipaddr_idx
KeySchema:
- AttributeName: ipaddr
KeyType: "HASH"
Projection:
ProjectionType: "KEYS_ONLY"
- IndexName: user_id_idx
KeySchema:
- AttributeName: user_id
KeyType: "HASH"
Projection:
ProjectionType: "KEYS_ONLY"
- IndexName: course_time_t_idx
KeySchema:
- AttributeName: course_id
KeyType: "HASH"
- AttributeName: time_t
KeyType: "RANGE"
Projection:
ProjectionType: "KEYS_ONLY"
HomeHttpApi:
Type: AWS::Serverless::HttpApi
Properties:
StageName: prod
Auth:
EnableIamAuthorizer: true
DefaultAuthorizer: AWS_IAM
Domain:
DomainName: !Sub "${AWS::StackName}-lambda.${BaseDomain}"
CertificateArn: !Ref WildcardCertificateArn
Route53:
HostedZoneId: !Ref HostedZoneId
# --- IAM: EC2 Role with hardcoded prefix ---
Ec2Role:
Type: AWS::IAM::Role
Properties:
RoleName: !Sub "PlantTracer-${AWS::StackName}-Ec2Role"
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: ec2.amazonaws.com
Action: "sts:AssumeRole"
ManagedPolicyArns:
- !Sub "arn:${AWS::Partition}:iam::aws:policy/AmazonSSMManagedInstanceCore"
Policies:
- PolicyName: Ec2DdbAndS3Access
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- dynamodb:GetItem
- dynamodb:PutItem
- dynamodb:UpdateItem
- dynamodb:DeleteItem
- dynamodb:Query
- dynamodb:Scan
- dynamodb:BatchGetItem
- dynamodb:BatchWriteItem
- dynamodb:DescribeTable
Resource:
- !Sub "arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${AWS::StackName}*"
- !Sub "arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${AWS::StackName}*/index/*"
- Effect: Allow
Action: ["dynamodb:ListTables"]
Resource: ["*"]
- Effect: Allow
Action:
- s3:GetBucketCORS
- s3:PutBucketCORS
- s3:GetBucketLocation
- s3:GetObject
- s3:PutObject
- s3:DeleteObject
- s3:ListBucket
- s3:GetBucketNotification
- s3:PutBucketNotification
- s3:GetBucketNotificationConfiguration
- s3:PutBucketNotificationConfiguration
Resource:
- !Sub "arn:${AWS::Partition}:s3:::${ImageBucketName}"
- !Sub "arn:${AWS::Partition}:s3:::${ImageBucketName}/*"
- Effect: Allow
Action:
- ses:VerifyEmailIdentity
- ses:ListIdentities
- ses:GetSendQuota
- ses:SendEmail
- ses:SendRawEmail
Resource: "*"
# --- Instance Profile with hardcoded prefix ---
Ec2InstanceProfile:
Type: AWS::IAM::InstanceProfile
Properties:
InstanceProfileName: !Sub "PlantTracer-${AWS::StackName}-InstanceProfile"
Roles: [!Ref Ec2Role]
# --- Lambda Role with hardcoded prefix ---
LambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
RoleName: !Sub "PlantTracer-${AWS::StackName}-LambdaRole"
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: "sts:AssumeRole"
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
- PolicyName: LambdaS3AndDdbAccess
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- s3:GetObject
- s3:PutObject
- s3:DeleteObject
- s3:ListBucket
Resource:
- !Sub "arn:${AWS::Partition}:s3:::${ImageBucketName}"
- !Sub "arn:${AWS::Partition}:s3:::${ImageBucketName}/*"
- Effect: Allow
Action:
- dynamodb:DescribeTable
- dynamodb:GetItem
- dynamodb:PutItem
- dynamodb:DeleteItem
- dynamodb:UpdateItem
- dynamodb:Query
- dynamodb:Scan
Resource:
- !Sub "arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${AWS::StackName}*"
- !Sub "arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${AWS::StackName}*/index/*"
- Effect: Allow
Action:
- sqs:SendMessage
- sqs:ReceiveMessage
- sqs:DeleteMessage
- sqs:GetQueueAttributes
- sqs:GetQueueUrl
Resource: !GetAtt TrackingQueue.Arn
TrackingQueue:
Type: AWS::SQS::Queue
Properties:
QueueName: !Sub "${AWS::StackName}-tracking-queue"
VisibilityTimeout: 900
LambdaFunction:
Type: AWS::Serverless::Function
Metadata:
BuildMethod: python3.12
BuildProperties:
# Must be inside CodeUri so --use-container mount can see it.
RequirementsFile: requirements.txt
Properties:
Role: !GetAtt LambdaExecutionRole.Arn
Runtime: python3.12
Architectures: [arm64]
PackageType: Zip
CodeUri: lambda-resize/src/
Handler: resize_app.main.lambda_handler
Timeout: 900
MemorySize: 1024
Environment:
Variables:
DYNAMODB_TABLE_PREFIX: !Sub "${AWS::StackName}-"
PLANTTRACER_S3_BUCKET: !Ref ImageBucketName
TRACKING_QUEUE_URL: !Ref TrackingQueue
Events:
AnyRoot:
Type: HttpApi
Properties:
ApiId: !Ref HomeHttpApi
Path: /
Method: ANY
PayloadFormatVersion: "2.0"
Auth:
Authorizer: NONE
AnyProxy:
Type: HttpApi
Properties:
ApiId: !Ref HomeHttpApi
Path: /{proxy+}
Method: ANY
PayloadFormatVersion: "2.0"
Auth:
Authorizer: NONE
TrackingQueueEvent:
Type: SQS
Properties:
Queue: !GetAtt TrackingQueue.Arn
BatchSize: 10
FunctionResponseTypes:
- ReportBatchItemFailures
Outputs:
ApiId:
Description: HTTP API ID
Value: !Ref HomeHttpApi
VmElasticIp:
Description: Elastic IP attached to the EC2 VM
Value: !Ref InstanceEip
VmDnsName:
Description: DNS name for the EC2 VM
Value: !Sub "${AWS::StackName}.${BaseDomain}"
LambdaDnsName:
Description: DNS name for the Lambda HTTP API custom domain
Value: !Sub "${AWS::StackName}-lambda.${BaseDomain}"
LambdaFunction:
Description: PlantTracer Lambda function name
Value: !Ref LambdaFunction