@@ -67,6 +67,12 @@ def create_template(
67
67
targets = [service ],
68
68
)
69
69
70
+ if ecs_manifest .metadata .auto_destruction is not None :
71
+ assert isinstance (
72
+ ecs_manifest .metadata .auto_destruction , int
73
+ ), "auto_destruction must be an Integer (minutes)"
74
+ create_autodestroy (stack , ecs_manifest .metadata .auto_destruction )
75
+
70
76
app .synth ()
71
77
72
78
@@ -350,3 +356,39 @@ def create_ecs_service(
350
356
enable_execute_command = True ,
351
357
min_healthy_percent = 0 ,
352
358
)
359
+
360
+
361
+ def create_autodestroy (stack , deployment_timeout : int ):
362
+ from pathlib import Path
363
+ from aws_cdk .aws_events import Rule , Schedule
364
+ from aws_cdk .aws_events_targets import LambdaFunction
365
+ from aws_cdk .aws_iam import PolicyStatement
366
+ from aws_cdk import aws_lambda , Duration
367
+ from aws_cdk .aws_logs import RetentionDays
368
+
369
+ lambdaDeleteStackPolicy = PolicyStatement (
370
+ actions = ["cloudformation:DeleteStack" , "lambda:RemovePermission" ],
371
+ resources = ["*" ],
372
+ )
373
+
374
+ lambda_function_file = str (
375
+ Path (__file__ ).parent .parent / "auto_destruction/harakiri.py"
376
+ )
377
+ harakiri = aws_lambda .Function (
378
+ stack ,
379
+ "AutoDestroy" ,
380
+ code = aws_lambda .Code .from_inline (open (lambda_function_file ).read ()),
381
+ handler = "index.handler" ,
382
+ timeout = Duration .seconds (300 ),
383
+ log_retention = RetentionDays .ONE_MONTH ,
384
+ environment = {"StackName" : stack .artifact_id },
385
+ runtime = aws_lambda .Runtime .PYTHON_3_11 ,
386
+ )
387
+ harakiri .add_to_role_policy (lambdaDeleteStackPolicy )
388
+
389
+ lambda_rule = Rule (
390
+ stack ,
391
+ "TimeToDestroy" ,
392
+ schedule = Schedule .rate (Duration .minutes (deployment_timeout )),
393
+ )
394
+ lambda_rule .add_target (LambdaFunction (handler = harakiri ))
0 commit comments