-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathmwaa_secondary_stack.py
More file actions
763 lines (688 loc) · 27.9 KB
/
mwaa_secondary_stack.py
File metadata and controls
763 lines (688 loc) · 27.9 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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
"""
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import json
from dataclasses import dataclass
import aws_cdk as cdk
from aws_cdk import aws_ec2 as ec2
from aws_cdk import aws_iam as iam
from aws_cdk import aws_lambda as _lambda
from aws_cdk import aws_s3 as s3
from aws_cdk import aws_scheduler as scheduler
from aws_cdk import aws_stepfunctions as sfn
from aws_cdk import aws_stepfunctions_tasks as tasks
from constructs import Construct
import config
from lib.stacks.mwaa_base_stack import MwaaBaseStack, VpcInfo
@dataclass
class DagTriggerStateInput:
state_name: str
mwaa_env_name: str
dag_name: str
bucket: str
dr_type: str
function: _lambda.Function
class MwaaSecondaryStack(MwaaBaseStack):
@property
def backup_bucket(self) -> s3.Bucket:
return self._backup_bucket
@property
def source_bucket(self) -> s3.Bucket:
return self._source_bucket
@property
def state_machine(self) -> sfn.StateMachine:
return self._state_machine
def __init__(
self, scope: Construct, construct_id: str, conf: config.Config = None, **kwargs
) -> None:
super().__init__(scope, construct_id, conf, **kwargs)
conf = self.conf
vpc_id = conf.secondary_vpc_id
subnet_ids = conf.secondary_subnet_ids
security_group_ids = conf.secondary_security_group_ids
self._vpc = self.get_vpc_info(conf, vpc_id, subnet_ids, security_group_ids)
mwaa_role = iam.Role.from_role_arn(
self, conf.get_name("mwaa-role"), conf.secondary_mwaa_role_arn
)
self.setup_buckets(conf, mwaa_role)
self.update_execution_role(conf, mwaa_role)
schedule_name = conf.get_name("scheduler")
if conf.dr_type == config.DR_BACKUP_RESTORE:
self._state_machine = self.create_backup_restore_state_machine(
conf=conf, vpc_info=self._vpc, schedule_name=schedule_name
)
else:
self._state_machine = self.create_warm_standby_state_machine(
conf=conf, vpc_info=self._vpc, schedule_name=schedule_name
)
self.create_scheduler(
conf=conf, schedule_name=schedule_name, state_machine=self._state_machine
)
self.sns_topic = self.create_sns_topic_with_email_subscriptions(conf)
self.setup_notification(
conf,
self.sns_topic,
self._state_machine,
["FAILED", "TIMED_OUT", "ABORTED"],
)
if conf.secondary_create_step_functions_vpce:
self.setup_sfn_vpce(conf, self._vpc)
def setup_buckets(self, conf: config.Config, mwaa_role: iam.IRole) -> s3.Bucket:
_source_bucket = s3.Bucket.from_bucket_name(
self, conf.get_name("source-bucket"), conf.secondary_dags_bucket_name
)
self._source_bucket = _source_bucket
_backup_bucket = s3.Bucket(
self,
conf.get_name("backup-bucket"),
bucket_name=cdk.PhysicalName.GENERATE_IF_NEEDED,
encryption=s3.BucketEncryption.S3_MANAGED,
block_public_access=s3.BlockPublicAccess.BLOCK_ALL,
versioned=True,
removal_policy=cdk.RemovalPolicy.DESTROY,
auto_delete_objects=True,
)
_backup_bucket.add_to_resource_policy(
iam.PolicyStatement(
principals=[mwaa_role],
actions=[
"s3:Abort*",
"s3:DeleteObject*",
"s3:GetBucket*",
"s3:GetObject*",
"s3:List*",
"s3:PutObject",
"s3:PutObjectLegalHold",
"s3:PutObjectRetention",
"s3:PutObjectTagging",
"s3:PutObjectVersionTagging",
],
resources=[
_backup_bucket.bucket_arn,
_backup_bucket.arn_for_objects("*"),
],
)
)
self._backup_bucket = _backup_bucket
cdk.CfnOutput(self, "MWAA-Backup-Bucket-Name", value=_backup_bucket.bucket_name)
def create_warm_standby_state_machine(
self, conf: config.Config, vpc_info: VpcInfo, schedule_name: str
) -> sfn.StateMachine:
success = sfn.Succeed(self, "Workflow Complete")
scheduler_heartbeat_fn = self.get_scheduler_heartbeat_function(conf)
get_scheduler_heartbeat_state = self.create_get_scheduler_heartbeat_state(
state_name="Get Scheduler Heartbeat",
scheduler_heartbeat_fn=scheduler_heartbeat_fn,
env_name=conf.primary_mwaa_environment_name,
env_region=conf.primary_region,
simulate_dr="$$.Execution.Input.simulate_dr",
)
dag_trigger_function = self.create_dag_trigger_function(
logical_id=conf.get_name("dag-trigger-function"),
env_name=conf.secondary_mwaa_environment_name,
vpc_info=vpc_info,
)
cleanup_metadata_state = self.create_dag_trigger_state(
state_name="Cleanup Metadata",
mwaa_env_name=conf.secondary_mwaa_environment_name,
mwaa_env_version=conf.mwaa_version,
dag_name=conf.metadata_cleanup_dag_name,
bucket=self.backup_bucket.bucket_name,
dr_type=conf.dr_type,
connection_restore_strategy=conf.dr_connection_restore_strategy,
variable_restore_strategy=conf.dr_variable_restore_strategy,
function=dag_trigger_function,
)
cool_off_state = sfn.Wait(
self,
f"Cool Off {conf.secondary_cleanup_cool_off_secs}s",
time=sfn.WaitTime.duration(
cdk.Duration.seconds(conf.secondary_cleanup_cool_off_secs)
),
)
restore_metadata_state = self.create_dag_trigger_state(
state_name="Restore Metadata",
mwaa_env_name=conf.secondary_mwaa_environment_name,
mwaa_env_version=conf.mwaa_version,
dag_name=conf.metadata_import_dag_name,
bucket=self.backup_bucket.bucket_name,
dr_type=conf.dr_type,
connection_restore_strategy=conf.dr_connection_restore_strategy,
variable_restore_strategy=conf.dr_variable_restore_strategy,
function=dag_trigger_function,
)
disable_schedule_state = self.create_disable_scheduler_state(schedule_name)
unhealthy_flow = (
disable_schedule_state.next(cleanup_metadata_state)
.next(cool_off_state)
.next(restore_metadata_state)
.next(success)
)
check_heartbeat_flow = (
sfn.Choice(self, "Check Heartbeat")
.when(sfn.Condition.string_equals("$.Payload", "UNHEALTHY"), unhealthy_flow)
.otherwise(success)
)
overall_flow = get_scheduler_heartbeat_state.next(check_heartbeat_flow)
state_machine = sfn.StateMachine(
self,
conf.get_name("state-machine"),
definition_body=sfn.DefinitionBody.from_chainable(overall_flow),
timeout=cdk.Duration.minutes(conf.state_machine_timeout_mins),
)
return state_machine
def create_backup_restore_state_machine(
self, conf: config.Config, vpc_info: VpcInfo, schedule_name: str
) -> sfn.StateMachine:
scheduler_heartbeat_fn = self.get_scheduler_heartbeat_function(conf)
get_scheduler_heartbeat_state = self.create_get_scheduler_heartbeat_state(
state_name="Get Scheduler Heartbeat",
scheduler_heartbeat_fn=scheduler_heartbeat_fn,
env_name=conf.primary_mwaa_environment_name,
env_region=conf.primary_region,
simulate_dr="$$.Execution.Input.simulate_dr",
)
get_env_function = self.create_get_environment_function(conf)
get_env_state = self.create_get_environment_details_state(
state_name="Get Environment Details",
get_env_fn=get_env_function,
env_name=conf.primary_mwaa_environment_name,
env_region=conf.primary_region,
)
store_env_state = self.create_store_environment_details_state(
conf, self.backup_bucket
)
healthy_flow = get_env_state.next(store_env_state)
disable_schedule_state = self.create_disable_scheduler_state(schedule_name)
read_env_state = self.create_read_environment_details_state(
conf, self.backup_bucket
)
create_env_state = self.create_new_environment_state(conf)
wait_state = sfn.Wait(
self,
f"Wait {conf.mwaa_create_env_polling_interval_secs}s",
time=sfn.WaitTime.duration(
cdk.Duration.seconds(conf.mwaa_create_env_polling_interval_secs)
),
)
get_status_state = self.create_get_environment_details_state(
state_name="Get Environment Status",
get_env_fn=get_env_function,
env_name=conf.secondary_mwaa_environment_name,
env_region=conf.secondary_region,
result_selector={"result.$": "States.StringToJson($.Payload)"},
)
dag_trigger_function = self.create_dag_trigger_function(
logical_id=conf.get_name("dag-trigger-function"),
env_name=conf.secondary_mwaa_environment_name,
vpc_info=vpc_info,
)
restore_metadata_state = self.create_dag_trigger_state(
state_name="Restore Metadata",
mwaa_env_name=conf.secondary_mwaa_environment_name,
mwaa_env_version=conf.mwaa_version,
dag_name=conf.metadata_import_dag_name,
bucket=self.backup_bucket.bucket_name,
dr_type=conf.dr_type,
connection_restore_strategy=conf.dr_connection_restore_strategy,
variable_restore_strategy=conf.dr_variable_restore_strategy,
function=dag_trigger_function,
)
check_environment_flow = (
sfn.Choice(self, "Check Environment Status")
.when(
sfn.Condition.string_equals("$.result.Environment.Status", "AVAILABLE"),
restore_metadata_state,
)
.otherwise(wait_state)
)
unhealthy_flow = (
disable_schedule_state.next(read_env_state)
.next(create_env_state)
.next(wait_state)
.next(get_status_state)
.next(check_environment_flow)
)
check_heartbeat_flow = (
sfn.Choice(self, "Check Heartbeat")
.when(sfn.Condition.string_equals("$.Payload", "HEALTHY"), healthy_flow)
.otherwise(unhealthy_flow)
)
overall_flow = get_scheduler_heartbeat_state.next(check_heartbeat_flow)
state_machine = sfn.StateMachine(
self,
conf.get_name("state-machine"),
definition_body=sfn.DefinitionBody.from_chainable(overall_flow),
timeout=cdk.Duration.minutes(conf.state_machine_timeout_mins),
)
return state_machine
def create_get_scheduler_heartbeat_state(
self,
state_name: str,
scheduler_heartbeat_fn: _lambda.Function,
env_name: str,
env_region: str,
simulate_dr: str = None,
result_selector: dict = None,
) -> tasks.CallAwsService:
state = tasks.LambdaInvoke(
self,
state_name,
lambda_function=scheduler_heartbeat_fn,
payload=sfn.TaskInput.from_object(
{
"env_name": env_name,
"region": env_region,
"simulate_dr": (
sfn.JsonPath.string_at(simulate_dr) if simulate_dr else "NO"
),
}
),
retry_on_service_exceptions=False,
result_selector=result_selector,
)
return state
def create_get_environment_details_state(
self,
state_name: str,
get_env_fn: _lambda.Function,
env_name: str,
env_region: str,
result_selector: dict = None,
) -> tasks.CallAwsService:
state = tasks.LambdaInvoke(
self,
state_name,
lambda_function=get_env_fn,
payload=sfn.TaskInput.from_object(
{
"env_name": env_name,
"env_region": env_region,
}
),
retry_on_service_exceptions=False,
result_selector=result_selector,
)
return state
def create_get_environment_function(self, conf: config.Config) -> _lambda.Function:
account_id = conf.aws_account_id
primary_region = conf.primary_region
secondary_region = conf.secondary_region
primary_env_name = conf.primary_mwaa_environment_name
secondary_env_name = conf.secondary_mwaa_environment_name
primary_mwaa_arn = f"arn:aws:airflow:{primary_region}:{account_id}:environment/{primary_env_name}"
primary_dummy_dr_arn = (
f"arn:aws:airflow:{primary_region}:{account_id}:environment/MWAA-Dummy-DR"
)
secondary_mwaa_arn = f"arn:aws:airflow:{secondary_region}:{account_id}:environment/{secondary_env_name}"
mwaa_arns = [primary_mwaa_arn, primary_dummy_dr_arn, secondary_mwaa_arn]
get_env_fn = _lambda.Function(
self,
conf.get_name("get-environment-function"),
runtime=_lambda.Runtime.PYTHON_3_11,
code=_lambda.Code.from_asset(
path="lib/functions",
bundling=cdk.BundlingOptions(
image=_lambda.Runtime.PYTHON_3_11.bundling_image,
command=[
"bash",
"-c",
"pip install --no-cache -r requirements.txt -t /asset-output && rsync -au . /asset-output",
],
),
),
handler="get_environment_function.handler",
timeout=cdk.Duration.seconds(10),
)
get_env_fn.add_to_role_policy(
iam.PolicyStatement(
resources=mwaa_arns,
actions=["airflow:GetEnvironment"],
)
)
return get_env_fn
def create_store_environment_details_state(
self, conf: config.Config, bucket: s3.Bucket
) -> tasks.CallAwsService:
key = conf.mwaa_backup_file_name
state = tasks.CallAwsService(
self,
"Store Environment Details",
service="s3",
action="putObject",
parameters={
"Bucket": bucket.bucket_name,
"Key": key,
"Body": sfn.JsonPath.object_at("$"),
},
iam_resources=[bucket.arn_for_objects(key)],
)
return state
def create_dag_trigger_function(
self, logical_id: str, env_name: str, vpc_info: VpcInfo
) -> _lambda.Function:
mwaa_arn = (
f"arn:aws:airflow:{self.region}:{self.account}:environment/{env_name}"
)
trigger_fn = _lambda.Function(
self,
logical_id,
runtime=_lambda.Runtime.PYTHON_3_11,
code=_lambda.Code.from_asset(
path="lib/functions",
bundling=cdk.BundlingOptions(
image=_lambda.Runtime.PYTHON_3_11.bundling_image,
command=[
"bash",
"-c",
"pip install --no-cache -r requirements.txt -t /asset-output && rsync -au . /asset-output",
],
),
),
handler="airflow_dag_trigger_function.handler",
vpc=vpc_info.vpc,
vpc_subnets=vpc_info.vpc_subnets,
security_groups=vpc_info.security_groups,
timeout=cdk.Duration.minutes(10),
)
trigger_fn.add_to_role_policy(
iam.PolicyStatement(
resources=[mwaa_arn],
actions=["airflow:CreateCliToken"],
)
)
return trigger_fn
def create_dag_trigger_state(
self,
state_name: str,
mwaa_env_name: str,
mwaa_env_version: str,
dag_name: str,
bucket: str,
dr_type: str,
variable_restore_strategy: str,
connection_restore_strategy: str,
function: _lambda.Function,
) -> tasks.LambdaInvoke:
state = tasks.LambdaInvoke(
self,
state_name,
lambda_function=function,
integration_pattern=sfn.IntegrationPattern.WAIT_FOR_TASK_TOKEN,
payload=sfn.TaskInput.from_object(
{
"task_token": sfn.JsonPath.task_token,
"mwaa_env_name": mwaa_env_name,
"mwaa_env_version": mwaa_env_version,
"dag": dag_name,
"bucket": bucket,
"dr_type": dr_type,
"variable_restore_strategy": variable_restore_strategy,
"connection_restore_strategy": connection_restore_strategy,
}
),
retry_on_service_exceptions=True,
)
return state
def update_execution_role(self, conf: config.Config, role: iam.IRole) -> None:
if conf.mwaa_update_execution_role.lower() == "yes":
iam.Policy(
self,
conf.get_name("mwaa-execution-role-policy"),
roles=[role],
statements=[
iam.PolicyStatement(
actions=[
"states:SendTaskSuccess",
"states:SendTaskFailure",
"states:SendTaskHeartbeat",
],
resources=[
f"arn:aws:states:{self.region}:{self.account}:stateMachine:*"
],
)
],
)
def create_read_environment_details_state(
self, conf: config.Config, bucket: s3.Bucket
) -> tasks.CallAwsService:
key = conf.mwaa_backup_file_name
state = tasks.CallAwsService(
self,
"Read Environment Backup",
service="s3",
action="getObject",
parameters={
"Bucket": bucket.bucket_name,
"Key": key,
},
iam_resources=[bucket.arn_for_objects(key)],
result_selector={
"result.$": "States.StringToJson($.Body)",
},
)
return state
def create_new_environment_state(self, conf: config.Config) -> tasks.LambdaInvoke:
state = tasks.LambdaInvoke(
self,
"Create New Environment",
lambda_function=self.create_new_environment_function(conf),
payload=sfn.TaskInput.from_object(
{
"execution_role_arn": conf.secondary_mwaa_role_arn,
"name": conf.secondary_mwaa_environment_name,
"network": {
"subnet_ids": conf.secondary_subnet_ids,
"security_group_ids": conf.secondary_security_group_ids,
},
"source_bucket_arn": self.source_bucket.bucket_arn,
"environment": sfn.JsonPath.object_at("$.result.Payload"),
}
),
retry_on_service_exceptions=True,
)
return state
def create_new_environment_function(self, conf: config.Config) -> _lambda.Function:
create_env_fn = _lambda.Function(
self,
conf.get_name("create-environment-function"),
runtime=_lambda.Runtime.PYTHON_3_11,
code=_lambda.Code.from_asset(
path="lib/functions",
bundling=cdk.BundlingOptions(
image=_lambda.Runtime.PYTHON_3_11.bundling_image,
command=[
"bash",
"-c",
"pip install --no-cache -r requirements.txt -t /asset-output && rsync -au . /asset-output",
],
),
),
handler="create_environment_function.handler",
timeout=cdk.Duration.seconds(10),
)
create_env_fn.add_to_role_policy(
iam.PolicyStatement(
resources=[
f"arn:aws:airflow:{conf.secondary_region}:{conf.aws_account_id}:environment/{conf.secondary_mwaa_environment_name}"
],
actions=["airflow:CreateEnvironment"],
)
)
create_env_fn.add_to_role_policy(
iam.PolicyStatement(
resources=[self.source_bucket.bucket_arn],
actions=["s3:GetEncryptionConfiguration"],
)
)
create_env_fn.add_to_role_policy(
iam.PolicyStatement(
resources=["arn:aws:logs:*:*:log-group:airflow-*:*"],
actions=[
"logs:CreateLogStream",
"logs:CreateLogGroup",
"logs:DescribeLogGroups",
],
)
)
create_env_fn.add_to_role_policy(
iam.PolicyStatement(
resources=["*"],
actions=[
"ec2:AttachNetworkInterface",
"ec2:CreateNetworkInterface",
"ec2:CreateNetworkInterfacePermission",
"ec2:DescribeDhcpOptions",
"ec2:DescribeNetworkInterfaces",
"ec2:DescribeSecurityGroups",
"ec2:DescribeSubnets",
"ec2:DescribeVpcEndpoints",
"ec2:DescribeVpcs",
],
)
)
create_env_fn.add_to_role_policy(
iam.PolicyStatement(
resources=[
"arn:aws:ec2:*:*:vpc/*",
"arn:aws:ec2:*:*:vpc-endpoint/*",
"arn:aws:ec2:*:*:security-group/*",
"arn:aws:ec2:*:*:subnet/*",
],
actions=["ec2:CreateVpcEndpoint", "ec2:ModifyVpcEndpoint"],
)
)
create_env_fn.add_to_role_policy(
iam.PolicyStatement(
resources=["arn:aws:ec2:*:*:vpc-endpoint/*"], actions=["ec2:CreateTags"]
)
)
create_env_fn.add_to_role_policy(
iam.PolicyStatement(resources=["*"], actions=["cloudwatch:PutMetricData"])
)
create_env_fn.add_to_role_policy(
iam.PolicyStatement(resources=["*"], actions=["iam:PassRole"])
)
return create_env_fn
def create_scheduler(
self, schedule_name: str, conf: config.Config, state_machine: sfn.StateMachine
) -> scheduler.CfnSchedule:
role = iam.Role(
self,
conf.get_name("scheduler-role"),
assumed_by=iam.ServicePrincipal("scheduler.amazonaws.com"),
inline_policies={
"sfn-start-execution": iam.PolicyDocument(
statements=[
iam.PolicyStatement(
resources=[state_machine.state_machine_arn],
actions=["states:StartExecution"],
)
]
)
},
)
state = "ENABLED" if conf.health_check_enabled else "DISABLED"
schedule = scheduler.CfnSchedule(
self,
conf.get_name("scheduler"),
name=schedule_name,
flexible_time_window={"mode": "OFF"},
schedule_expression=f"rate({conf.health_check_interval_mins} minutes)",
target={
"arn": state_machine.state_machine_arn,
"roleArn": role.role_arn,
"input": json.dumps(
{
"simulate_dr": conf.mwaa_simulate_dr,
}
),
},
state=state,
)
return schedule
def create_disable_scheduler_state(self, schedule_name: str) -> tasks.LambdaInvoke:
state = tasks.LambdaInvoke(
self,
"Disable Schedule",
lambda_function=self.disable_scheduler_function(self.conf),
payload=sfn.TaskInput.from_object({"schedule_name": schedule_name}),
retry_on_service_exceptions=True,
)
return state
def disable_scheduler_function(self, conf: config.Config) -> _lambda.Function:
disable_scheduler_fn = _lambda.Function(
self,
conf.get_name("disable-scheduler-function"),
runtime=_lambda.Runtime.PYTHON_3_11,
code=_lambda.Code.from_asset(
path="lib/functions",
bundling=cdk.BundlingOptions(
image=_lambda.Runtime.PYTHON_3_11.bundling_image,
command=[
"bash",
"-c",
"pip install --no-cache -r requirements.txt -t /asset-output && rsync -au . /asset-output",
],
),
),
handler="disable_scheduler_function.handler",
timeout=cdk.Duration.seconds(10),
)
disable_scheduler_fn.add_to_role_policy(
iam.PolicyStatement(
resources=[
f"arn:aws:scheduler:{conf.secondary_region}:{conf.aws_account_id}:schedule/*"
],
actions=["scheduler:GetSchedule", "scheduler:UpdateSchedule"],
)
)
disable_scheduler_fn.add_to_role_policy(
iam.PolicyStatement(resources=["*"], actions=["iam:PassRole"])
)
return disable_scheduler_fn
def get_scheduler_heartbeat_function(self, conf: config.Config) -> _lambda.Function:
cloudwatch_health_check_fn = _lambda.Function(
self,
conf.get_name("cloudwatch-health-check-function"),
runtime=_lambda.Runtime.PYTHON_3_11,
code=_lambda.Code.from_asset(
path="lib/functions",
bundling=cdk.BundlingOptions(
image=_lambda.Runtime.PYTHON_3_11.bundling_image,
command=[
"bash",
"-c",
"pip install --no-cache -r requirements.txt -t /asset-output && rsync -au . /asset-output",
],
),
),
handler="cloudwatch_health_check_function.handler",
timeout=cdk.Duration.seconds(10),
)
cloudwatch_health_check_fn.add_to_role_policy(
iam.PolicyStatement(resources=["*"], actions=["cloudwatch:GetMetricData"])
)
return cloudwatch_health_check_fn
def setup_sfn_vpce(
self, conf: config.Config, vpc_info: VpcInfo
) -> ec2.InterfaceVpcEndpoint:
vpce = vpc_info.vpc.add_interface_endpoint(
conf.get_name("sfn-vpce"),
service=ec2.InterfaceVpcEndpointAwsService.STEP_FUNCTIONS,
security_groups=vpc_info.security_groups,
subnets=vpc_info.vpc_subnets,
private_dns_enabled=True,
)
return vpce