|
| 1 | +from aws_cdk import ( |
| 2 | + Stack, |
| 3 | + aws_apigateway as apigateway, |
| 4 | + aws_dynamodb as dynamodb, |
| 5 | + aws_logs as logs, |
| 6 | + aws_pipes as pipes, |
| 7 | + aws_sqs as sqs, |
| 8 | + aws_iam as iam, |
| 9 | + RemovalPolicy, |
| 10 | + CfnOutput |
| 11 | +) |
| 12 | +from constructs import Construct |
| 13 | +import aws_cdk as cdk |
| 14 | + |
| 15 | +class EventbridgePipesSqsToDynamodb(Stack): |
| 16 | + |
| 17 | + def __init__(self, scope: Construct, construct_id: str, env: cdk.Environment, **kwargs) -> None: |
| 18 | + super().__init__(scope, construct_id, env=env, **kwargs) |
| 19 | + |
| 20 | + # SQS queue for decoupling and buffering events for destination_lambda_b |
| 21 | + source_queue = sqs.Queue( |
| 22 | + self, "EntryPointToEventbridgePipe", |
| 23 | + visibility_timeout=cdk.Duration.seconds(60), |
| 24 | + retention_period=cdk.Duration.days(4), |
| 25 | + enforce_ssl=True |
| 26 | + ) |
| 27 | + |
| 28 | + # DynamoDB table |
| 29 | + self.table = dynamodb.Table( |
| 30 | + self, "EventTableNew", |
| 31 | + table_name="Audit-Table", |
| 32 | + partition_key=dynamodb.Attribute( |
| 33 | + name="id", |
| 34 | + type=dynamodb.AttributeType.STRING |
| 35 | + ), |
| 36 | + billing_mode=dynamodb.BillingMode.PAY_PER_REQUEST, |
| 37 | + removal_policy=RemovalPolicy.DESTROY, |
| 38 | + point_in_time_recovery_specification=dynamodb.PointInTimeRecoverySpecification( |
| 39 | + point_in_time_recovery_enabled=True |
| 40 | + ) |
| 41 | + ) |
| 42 | + |
| 43 | + # IAM role for API Gateway to access DynamoDB |
| 44 | + api_gateway_role = iam.Role( |
| 45 | + self, "ApiGatewayDynamoDBRole", |
| 46 | + assumed_by=iam.ServicePrincipal("apigateway.amazonaws.com"), |
| 47 | + inline_policies={ |
| 48 | + "DynamoDBAccess": iam.PolicyDocument( |
| 49 | + statements=[ |
| 50 | + iam.PolicyStatement( |
| 51 | + actions=[ |
| 52 | + "dynamodb:PutItem", |
| 53 | + "dynamodb:GetItem", |
| 54 | + "dynamodb:UpdateItem", |
| 55 | + "dynamodb:DeleteItem", |
| 56 | + "dynamodb:Query", |
| 57 | + "dynamodb:Scan" |
| 58 | + ], |
| 59 | + resources=[self.table.table_arn] |
| 60 | + ) |
| 61 | + ] |
| 62 | + ) |
| 63 | + } |
| 64 | + ) |
| 65 | + |
| 66 | + # CloudWatch Log Group for API Gateway |
| 67 | + api_log_group = logs.LogGroup( |
| 68 | + self, "ApiGatewayLogGroup", |
| 69 | + removal_policy=RemovalPolicy.DESTROY |
| 70 | + ) |
| 71 | + |
| 72 | + stage_name = "test" |
| 73 | + |
| 74 | + # API Gateway with Resource policy to be invoked only by Eventbridge Pipes |
| 75 | + self.api = apigateway.RestApi( |
| 76 | + self, "RegionalApi", |
| 77 | + rest_api_name="EventBridge-DynamoDB-API", |
| 78 | + endpoint_configuration=apigateway.EndpointConfiguration( |
| 79 | + types=[apigateway.EndpointType.REGIONAL] |
| 80 | + ), |
| 81 | + policy=iam.PolicyDocument( |
| 82 | + statements=[ |
| 83 | + iam.PolicyStatement( |
| 84 | + effect=iam.Effect.ALLOW, |
| 85 | + principals=[iam.ServicePrincipal("pipes.amazonaws.com")], |
| 86 | + actions=["execute-api:Invoke"], |
| 87 | + resources=[f"execute-api:/{stage_name}/POST/events"] |
| 88 | + ) |
| 89 | + ] |
| 90 | + ), |
| 91 | + deploy_options=apigateway.StageOptions( |
| 92 | + stage_name=stage_name, |
| 93 | + access_log_destination=apigateway.LogGroupLogDestination(api_log_group), |
| 94 | + access_log_format=apigateway.AccessLogFormat.clf(), |
| 95 | + logging_level=apigateway.MethodLoggingLevel.INFO, |
| 96 | + data_trace_enabled=True |
| 97 | + ) |
| 98 | + ) |
| 99 | + |
| 100 | + # API Gateway integration with DynamoDB |
| 101 | + dynamodb_integration = apigateway.AwsIntegration( |
| 102 | + service="dynamodb", |
| 103 | + action="PutItem", |
| 104 | + options=apigateway.IntegrationOptions( |
| 105 | + credentials_role=api_gateway_role, |
| 106 | + request_templates={ |
| 107 | + "application/json": f'''#set($inputRoot = $input.path('$')) |
| 108 | +#set($body = $util.parseJson($inputRoot.body)) |
| 109 | +#set($message = $util.parseJson($body.Message)) |
| 110 | +{{ |
| 111 | + "TableName": "{self.table.table_name}", |
| 112 | + "Item": {{ |
| 113 | + "id": {{ |
| 114 | + "S": "$context.requestId" |
| 115 | + }}, |
| 116 | + "createdAt": {{ |
| 117 | + "S": "$context.requestTime" |
| 118 | + }}, |
| 119 | + "name": {{ |
| 120 | + "S": "$message.params.name" |
| 121 | + }}, |
| 122 | + "surname": {{ |
| 123 | + "S": "$message.params.surname" |
| 124 | + }}, |
| 125 | + "content": {{ |
| 126 | + "S": "$util.escapeJavaScript($message.content)" |
| 127 | + }} |
| 128 | + }} |
| 129 | +}}''' |
| 130 | + }, |
| 131 | + integration_responses=[ |
| 132 | + apigateway.IntegrationResponse( |
| 133 | + status_code="200", |
| 134 | + response_templates={ |
| 135 | + "application/json": '{"status": "success", "id": "$context.requestId"}' |
| 136 | + } |
| 137 | + ) |
| 138 | + ] |
| 139 | + ) |
| 140 | + ) |
| 141 | + |
| 142 | + # API Gateway resource and method with IAM authentication |
| 143 | + events_resource = self.api.root.add_resource("events") |
| 144 | + events_resource.add_method( |
| 145 | + "POST", |
| 146 | + dynamodb_integration, |
| 147 | + authorization_type=apigateway.AuthorizationType.IAM, |
| 148 | + method_responses=[ |
| 149 | + apigateway.MethodResponse( |
| 150 | + status_code="200", |
| 151 | + response_models={ |
| 152 | + "application/json": apigateway.Model.EMPTY_MODEL |
| 153 | + } |
| 154 | + ) |
| 155 | + ] |
| 156 | + ) |
| 157 | + |
| 158 | + # IAM role for EventBridge Pipe |
| 159 | + pipe_role = iam.Role( |
| 160 | + self, "EventBridgePipeRole", |
| 161 | + assumed_by=iam.ServicePrincipal("pipes.amazonaws.com").with_conditions({ |
| 162 | + "StringEquals": { |
| 163 | + "aws:SourceAccount": cdk.Stack.of(self).account, |
| 164 | + "aws:SourceArn": f"arn:aws:pipes:{cdk.Stack.of(self).region}:{cdk.Stack.of(self).account}:pipe/EventBridgePipe" |
| 165 | + } |
| 166 | + }), |
| 167 | + inline_policies={ |
| 168 | + "SqsPipeSourceAccess": iam.PolicyDocument( |
| 169 | + statements=[ |
| 170 | + iam.PolicyStatement( |
| 171 | + actions=[ |
| 172 | + "sqs:ReceiveMessage", |
| 173 | + "sqs:DeleteMessage", |
| 174 | + "sqs:GetQueueAttributes" |
| 175 | + ], |
| 176 | + resources=[source_queue.queue_arn] |
| 177 | + ) |
| 178 | + ] |
| 179 | + ), |
| 180 | + "ApiGatewayPipeTargetAccess": iam.PolicyDocument( |
| 181 | + statements=[ |
| 182 | + iam.PolicyStatement( |
| 183 | + actions=[ |
| 184 | + "execute-api:Invoke", |
| 185 | + "execute-api:ManageConnections" |
| 186 | + ], |
| 187 | + resources=[f"arn:aws:execute-api:{cdk.Stack.of(self).region}:{cdk.Stack.of(self).account}:{self.api.rest_api_id}/{stage_name}/*"] |
| 188 | + ) |
| 189 | + ] |
| 190 | + ) |
| 191 | + } |
| 192 | + ) |
| 193 | + |
| 194 | + # EventBridge Pipe: SQS → API Gateway |
| 195 | + self.pipe = pipes.CfnPipe( |
| 196 | + self, "SqsToApiGatewayPipe", |
| 197 | + role_arn=pipe_role.role_arn, |
| 198 | + name="EventBridgePipe", |
| 199 | + desired_state="RUNNING", |
| 200 | + source=source_queue.queue_arn, |
| 201 | + source_parameters=pipes.CfnPipe.PipeSourceParametersProperty( |
| 202 | + sqs_queue_parameters=pipes.CfnPipe.PipeSourceSqsQueueParametersProperty( |
| 203 | + batch_size=1 |
| 204 | + ) |
| 205 | + ), |
| 206 | + target=f"arn:aws:execute-api:{cdk.Stack.of(self).region}:{cdk.Stack.of(self).account}:{self.api.rest_api_id}/{stage_name}/POST/events", |
| 207 | + target_parameters=pipes.CfnPipe.PipeTargetParametersProperty( |
| 208 | + http_parameters=pipes.CfnPipe.PipeTargetHttpParametersProperty( |
| 209 | + header_parameters={ |
| 210 | + "Content-Type": "application/json" |
| 211 | + } |
| 212 | + ) |
| 213 | + ) |
| 214 | + ) |
| 215 | + |
| 216 | + # Output |
| 217 | + CfnOutput(self, "QueueName", value=source_queue.queue_name) |
| 218 | + |
0 commit comments