forked from aws-powertools/powertools-lambda-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcanary_stack.py
More file actions
70 lines (59 loc) · 2.71 KB
/
Copy pathcanary_stack.py
File metadata and controls
70 lines (59 loc) · 2.71 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
import uuid
from aws_cdk import CfnParameter, CustomResource, Duration, Stack
from aws_cdk.aws_iam import Effect, ManagedPolicy, PolicyStatement, Role, ServicePrincipal
from aws_cdk.aws_lambda import Code, Function, LayerVersion, Runtime
from aws_cdk.aws_logs import RetentionDays
from aws_cdk.aws_ssm import StringParameter
from aws_cdk.custom_resources import Provider
from constructs import Construct
class CanaryStack(Stack):
def __init__(
self,
scope: Construct,
construct_id: str,
powertools_version: str,
ssm_paramter_layer_arn: str,
**kwargs,
) -> None:
super().__init__(scope, construct_id, **kwargs)
VERSION_TRACKING_EVENT_BUS_ARN: str = (
"arn:aws:events:eu-central-1:027876851704:event-bus/VersionTrackingEventBus"
)
layer_arn = StringParameter.from_string_parameter_attributes(
self, "LayerVersionArnParam", parameter_name=ssm_paramter_layer_arn
).string_value
layer = LayerVersion.from_layer_version_arn(self, "PowertoolsLayer", layer_version_arn=layer_arn)
deploy_stage = CfnParameter(self, "DeployStage", description="Deployment stage for canary").value_as_string
execution_role = Role(self, "LambdaExecutionRole", assumed_by=ServicePrincipal("lambda.amazonaws.com"))
execution_role.add_managed_policy(
ManagedPolicy.from_aws_managed_policy_name("service-role/AWSLambdaBasicExecutionRole")
)
canary_lambda = Function(
self,
"CanaryLambdaFunction",
code=Code.from_asset("layer/canary"),
handler="app.on_event",
layers=[layer],
memory_size=512,
timeout=Duration.seconds(10),
runtime=Runtime.PYTHON_3_9,
log_retention=RetentionDays.ONE_MONTH,
role=execution_role,
environment={
"POWERTOOLS_VERSION": powertools_version,
"POWERTOOLS_LAYER_ARN": layer_arn,
"VERSION_TRACKING_EVENT_BUS_ARN": VERSION_TRACKING_EVENT_BUS_ARN,
"LAYER_PIPELINE_STAGE": deploy_stage,
},
)
canary_lambda.add_to_role_policy(
PolicyStatement(
effect=Effect.ALLOW, actions=["events:PutEvents"], resources=[VERSION_TRACKING_EVENT_BUS_ARN]
)
)
# custom resource provider configuration
provider = Provider(
self, "CanaryCustomResource", on_event_handler=canary_lambda, log_retention=RetentionDays.ONE_MONTH
)
# force to recreate resource on each deployment with randomized name
CustomResource(self, f"CanaryTrigger-{str(uuid.uuid4())[0:7]}", service_token=provider.service_token)