def __init__(self, scope, id, name=None, state_machine_arn=None) -> None:
        super().__init__(scope, id)
        # ==================================================
        # ================= IAM ROLE =======================
        # ==================================================
        api_role = iam.Role(
            scope=self,
            id='api_role',
            assumed_by=iam.ServicePrincipal(service='apigateway.amazonaws.com'),
        )
        api_role.add_to_policy(
            iam.PolicyStatement(
                effect=iam.Effect.ALLOW,
                actions=['states:StartSyncExecution'],
                resources=['*']
            )
        )

        # ==================================================
        # ================== API GATEWAY ===================
        # ==================================================
        api = apigw.HttpApi(
            scope=self,
            id='api',
            api_name=name,
            cors_preflight={
                "allow_headers": ["Authorization"],
                "allow_methods": [apigw.HttpMethod.POST],
                "allow_origins": ["*"],
                "max_age": core.Duration.days(10)
            }
        )

        integration = apigw.CfnIntegration(
            scope=self,
            id='integration',
            api_id=api.http_api_id,
            credentials_arn=api_role.role_arn,
            integration_type='AWS_PROXY',
            integration_subtype='StepFunctions-StartSyncExecution',
            request_parameters={
                'Input': '$request.body',
                'StateMachineArn': f'{state_machine_arn}'
            },
            payload_format_version='1.0'
        )

        apigw.CfnRoute(
            scope=self,
            id='route',
            api_id=api.http_api_id,
            route_key='POST /',
            target=f'integrations/{integration.ref}'
        )
Ejemplo n.º 2
0
 def _create_sqs_send_msg_route(self):
     _integ = _apigwv2.CfnIntegration(
         self,
         'HttpApiIntegSqsSendMessage',
         api_id=self._http_api.ref,
         integration_type='AWS_PROXY',
         integration_subtype='SQS-SendMessage',
         payload_format_version='1.0',
         request_parameters={
             'QueueUrl': self._queue.queue_url,
             'MessageBody': '$request.body.MessageBody',
         },
         credentials_arn=self._integration_role.role_arn,
     )
     return _apigwv2.CfnRoute(
         self,
         'HttpApiRouteSqsSendMsg',
         api_id=self._http_api.ref,
         route_key='POST /send',
         target='/'.join(['integrations', _integ.ref]),
     )
Ejemplo n.º 3
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        brand = 'a'
        stage = 'dev'
        tablename = 'webchat'

        connectionstable = dynamodb.Table(
            self,
            'connectionsTable',
            billing_mode=dynamodb.BillingMode.PAY_PER_REQUEST,
            removal_policy=core.RemovalPolicy.DESTROY,
            table_name=tablename,
            partition_key=dynamodb.Attribute(
                name="connectionId", type=dynamodb.AttributeType.STRING),
        )

        websocketgw = apiv2.CfnApi(
            self,
            'websocket',
            name='SimpleChatWebSocket',
            protocol_type='WEBSOCKET',
            route_selection_expression='$request.body.action')

        # connect function
        connect_function = py_lambda.PythonFunction(
            self,
            "connect_function",
            entry='websocket/api_lambda/connect',  #folder
            index='connect.py',  #file
            handler='lambda_handler',  #function
            description='connect',
            environment={
                'brand': brand,
                'stage': stage,
                'CONNECTION_TABLE_NAME': tablename
            },
            timeout=core.Duration.seconds(60))
        connectionstable.grant_read_write_data(connect_function)

        connect_function_policy = iam.Policy(
            self,
            'connect_policy',
            statements=[
                iam.PolicyStatement(actions=['dynamodb:*'],
                                    resources=[connectionstable.table_arn])
            ],
            roles=[connect_function.role])

        connect_function_permission = aws_lambda.CfnPermission(
            self,
            'connectFunctionPermission',
            action='lambda:InvokeFunction',
            function_name=connect_function.function_name,
            principal='apigateway.amazonaws.com')
        connect_function_permission.add_depends_on(websocketgw)

        # # disconnect function
        disconnect_function = py_lambda.PythonFunction(
            self,
            "disconnect_function",
            entry='websocket/api_lambda/disconnect',  #folder
            index='disconnect.py',  #file
            handler='lambda_handler',  #function
            description='disconnect',
            environment={
                'brand': brand,
                'stage': stage,
                'CONNECTION_TABLE_NAME': tablename
            },
            timeout=core.Duration.seconds(60))

        disconnect_function_policy = iam.Policy(
            self,
            'disconnect_policy',
            statements=[
                iam.PolicyStatement(actions=['dynamodb:*'],
                                    resources=[connectionstable.table_arn])
            ],
            roles=[disconnect_function.role])

        disconnect_function_permission = aws_lambda.CfnPermission(
            self,
            'disconnectFunctionPermission',
            action='lambda:InvokeFunction',
            function_name=disconnect_function.function_name,
            principal='apigateway.amazonaws.com')
        connectionstable.grant_read_write_data(disconnect_function)
        disconnect_function_permission.add_depends_on(websocketgw)

        #send message function.
        sendmessage_function = py_lambda.PythonFunction(
            self,
            "sendmessage_function",
            entry='websocket/api_lambda/sendmessage',  #folder
            index='sendmessage.py',  #file
            handler='lambda_handler',  #function
            description='sendmessage',
            environment={
                'brand': brand,
                'stage': stage,
                'CONNECTION_TABLE_NAME': tablename
            },
            timeout=core.Duration.seconds(60))
        connectionstable.grant_read_write_data(connect_function)

        sendmessage_function_policy = iam.Policy(
            self,
            'sendmessage_policy',
            statements=[
                iam.PolicyStatement(actions=['dynamodb:*'],
                                    resources=[connectionstable.table_arn]),
                iam.PolicyStatement(
                    actions=['execute-api:ManageConnections'],
                    resources=[
                        f'arn:aws:execute-api:aws:{self.region}:{self.account}:{websocketgw.ref}/*',
                        f'arn:aws:execute-api:{self.region}:{self.account}:{websocketgw.ref}/prod/POST/@connections/*'
                    ],
                ),
            ],
            roles=[sendmessage_function.role])
        sendmessage_function_permission = aws_lambda.CfnPermission(
            self,
            'sendmessageFunctionPermission',
            action='lambda:InvokeFunction',
            function_name=sendmessage_function.function_name,
            principal='apigateway.amazonaws.com')
        sendmessage_function_permission.add_depends_on(websocketgw)

        #set username function
        setusername_function = py_lambda.PythonFunction(
            self,
            "setusername_function",
            entry='websocket/api_lambda/setusername',  #folder
            index='setusername.py',  #file
            handler='lambda_handler',  #function
            description='setusername',
            environment={
                'brand': brand,
                'stage': stage,
                'CONNECTION_TABLE_NAME': tablename
            },
            timeout=core.Duration.seconds(60))
        connectionstable.grant_read_write_data(connect_function)

        setusername_function_policy = iam.Policy(
            self,
            'setusername_policy',
            statements=[
                iam.PolicyStatement(actions=['dynamodb:*'],
                                    resources=[connectionstable.table_arn]),
                iam.PolicyStatement(
                    actions=['execute-api:ManageConnections'],
                    resources=[
                        f'arn:aws:execute-api:aws:{self.region}:{self.account}:{websocketgw.ref}/*',
                        f'arn:aws:execute-api:{self.region}:{self.account}:{websocketgw.ref}/prod/POST/@connections/*'
                    ],
                ),
            ],
            roles=[setusername_function.role])
        setusername_function_permission = aws_lambda.CfnPermission(
            self,
            'setusernameFunctionPermission',
            action='lambda:InvokeFunction',
            function_name=setusername_function.function_name,
            principal='apigateway.amazonaws.com')
        setusername_function_permission.add_depends_on(websocketgw)

        # Connect route
        connect_integration = apiv2.CfnIntegration(
            self,
            'ConnectIntegration',
            api_id=websocketgw.ref,
            description='Connect Integration',
            integration_type='AWS_PROXY',
            integration_uri=
            f'arn:aws:apigateway:{self.region}:lambda:path/2015-03-31/functions/{connect_function.function_arn}/invocations'
        )

        connect_route = apiv2.CfnRoute(self,
                                       'connectRoute',
                                       api_id=websocketgw.ref,
                                       route_key='$connect',
                                       authorization_type='NONE',
                                       operation_name='ConnectRoute',
                                       target='integrations/' +
                                       connect_integration.ref)

        # #Disconnect route
        disconnect_integration = apiv2.CfnIntegration(
            self,
            'disConnectIntegration',
            api_id=websocketgw.ref,
            description='disConnect Integration',
            integration_type='AWS_PROXY',
            integration_uri=
            f'arn:aws:apigateway:{self.region}:lambda:path/2015-03-31/functions/{disconnect_function.function_arn}/invocations'
        )
        disconnect_route = apiv2.CfnRoute(self,
                                          'disconnectRoute',
                                          api_id=websocketgw.ref,
                                          route_key='$disconnect',
                                          authorization_type='NONE',
                                          operation_name='DisconnectRoute',
                                          target='integrations/' +
                                          disconnect_integration.ref)

        #Send Route
        sendmessage_integration = apiv2.CfnIntegration(
            self,
            'sendMessageIntegration',
            api_id=websocketgw.ref,
            description='sendmessage Integration',
            integration_type='AWS_PROXY',
            integration_uri=
            f'arn:aws:apigateway:{self.region}:lambda:path/2015-03-31/functions/{sendmessage_function.function_arn}/invocations'
        )
        sendmessage_route = apiv2.CfnRoute(self,
                                           'sendRoute',
                                           api_id=websocketgw.ref,
                                           route_key='sendmessage',
                                           authorization_type='NONE',
                                           operation_name='SendRoute',
                                           target='integrations/' +
                                           sendmessage_integration.ref)

        #Set username Route
        setusername_integration = apiv2.CfnIntegration(
            self,
            'setUsernameIntegration',
            api_id=websocketgw.ref,
            description='setusername Integration',
            integration_type='AWS_PROXY',
            integration_uri=
            f'arn:aws:apigateway:{self.region}:lambda:path/2015-03-31/functions/{setusername_function.function_arn}/invocations'
        )
        setusername_route = apiv2.CfnRoute(self,
                                           'setUsernameRoute',
                                           api_id=websocketgw.ref,
                                           route_key='setusername',
                                           authorization_type='NONE',
                                           operation_name='SetUsernameRoute',
                                           target='integrations/' +
                                           setusername_integration.ref)

        deployment = apiv2.CfnDeployment(
            self,
            'Deployment',
            api_id=websocketgw.ref,
        )
        deployment.add_depends_on(sendmessage_route)
        deployment.add_depends_on(setusername_route)
        deployment.add_depends_on(connect_route)
        deployment.add_depends_on(disconnect_route)

        stage = apiv2.CfnStage(
            self,
            'stage',
            stage_name='prod',
            description='prod stage',
            # deployment_id= deployment.ref,
            api_id=websocketgw.ref,
        )

        core.CfnOutput(
            self,
            'WebSocketURI',
            value=
            f'wss://{websocketgw.ref}.execute-api.{self.region}.amazonaws.com/prod',
            description='URI of websocket')

        print('WebSocket')
Ejemplo n.º 4
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # Step Function Starts Here

        # The first thing we need to do is see if they are asking for pineapple on a pizza
        pineapple_check_lambda = _lambda.Function(
            self,
            "pineappleCheckLambdaHandler",
            runtime=_lambda.Runtime.NODEJS_12_X,
            handler="orderPizza.handler",
            code=_lambda.Code.from_asset("lambda_fns"),
        )

        # Step functions are built up of steps, we need to define our first step
        order_pizza = step_fn_tasks.LambdaInvoke(
            self,
            'Order Pizza Job',
            lambda_function=pineapple_check_lambda,
            input_path='$.flavour',
            result_path='$.pineappleAnalysis',
            payload_response_only=True)

        # Pizza Order failure step defined
        pineapple_detected = step_fn.Fail(self,
                                          'Sorry, We Dont add Pineapple',
                                          cause='They asked for Pineapple',
                                          error='Failed To Make Pizza')

        # If they didnt ask for pineapple let's cook the pizza
        cook_pizza = step_fn.Succeed(self,
                                     'Lets make your pizza',
                                     output_path='$.pineappleAnalysis')

        # If they ask for a pizza with pineapple, fail. Otherwise cook the pizza
        definition = step_fn.Chain \
            .start(order_pizza) \
            .next(step_fn.Choice(self, 'With Pineapple?')
                  .when(step_fn.Condition.boolean_equals('$.pineappleAnalysis.containsPineapple', True),
                        pineapple_detected)
                  .otherwise(cook_pizza))

        state_machine = step_fn.StateMachine(
            self,
            'StateMachine',
            definition=definition,
            timeout=core.Duration.minutes(5),
            tracing_enabled=True,
            state_machine_type=step_fn.StateMachineType.EXPRESS)

        # HTTP API Definition

        # Give our gateway permissions to interact with SNS
        http_api_role = iam.Role(
            self,
            'HttpApiRole',
            assumed_by=iam.ServicePrincipal('apigateway.amazonaws.com'),
            inline_policies={
                "AllowSFNExec":
                iam.PolicyDocument(statements=[
                    iam.PolicyStatement(
                        actions=["states:StartSyncExecution"],
                        effect=iam.Effect.ALLOW,
                        resources=[state_machine.state_machine_arn])
                ])
            })

        api = api_gw.HttpApi(self,
                             'the_state_machine_api',
                             create_default_stage=True)

        # create an AWS_PROXY integration between the HTTP API and our Step Function
        integ = api_gw.CfnIntegration(
            self,
            'Integ',
            api_id=api.http_api_id,
            integration_type='AWS_PROXY',
            connection_type='INTERNET',
            integration_subtype='StepFunctions-StartSyncExecution',
            credentials_arn=http_api_role.role_arn,
            request_parameters={
                "Input": "$request.body",
                "StateMachineArn": state_machine.state_machine_arn
            },
            payload_format_version="1.0",
            timeout_in_millis=10000)

        api_gw.CfnRoute(self,
                        'DefaultRoute',
                        api_id=api.http_api_id,
                        route_key=api_gw.HttpRouteKey.DEFAULT.key,
                        target="integrations/" + integ.ref)

        core.CfnOutput(self, 'HTTP API URL', value=api.url)
    def __init__(self, scope: core.Construct, construct_id: str,
                 **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        # ==================================================
        # =============== CFN PARAMETERS ===================
        # ==================================================
        project_name = core.CfnParameter(scope=self,
                                         id='SageMakerProjectName',
                                         type='String')
        model_execution_role_arn = core.CfnParameter(
            scope=self, id='ModelExecutionRoleArn', type='String')
        model_binary_location = core.CfnParameter(scope=self,
                                                  id='ModelBinaryLocation',
                                                  type='String')
        stage_name = core.CfnParameter(scope=self,
                                       id='StageName',
                                       type='String')

        name = f'{project_name.value_as_string}-{stage_name.value_as_string}'
        # ==================================================
        # ================== IAM ROLE ======================
        # ==================================================
        role = iam.Role.from_role_arn(
            scope=self,
            id='role',
            role_arn=model_execution_role_arn.value_as_string)

        # ==================================================
        # ================== ECR IMAGE =====================
        # ==================================================
        ecr_repository = ecr.Repository.from_repository_name(
            scope=self,
            id='repo',
            repository_name='<ADD YOUR CONTAINER REPO HERE>')

        ecr_image = aws_lambda.DockerImageCode.from_ecr(
            repository=ecr_repository, tag='<ADD YOUR IMAGE TAG HERE>')
        # ==================================================
        # ================ LAMBDA FUNCTION =================
        # ==================================================
        lambda_function = aws_lambda.DockerImageFunction(
            scope=self,
            id='lambda',
            function_name=name,
            code=ecr_image,
            memory_size=1024,
            role=role,
            environment={
                'MODEL_S3_URI': model_binary_location.value_as_string,
            },
            timeout=core.Duration.seconds(60))

        # ==================================================
        # ================== API GATEWAY ===================
        # ==================================================
        api = apigw.HttpApi(scope=self,
                            id='api_gateway',
                            api_name=name,
                            cors_preflight={
                                "allow_headers": ["Authorization"],
                                "allow_methods": [apigw.HttpMethod.POST],
                                "allow_origins": ["*"],
                                "max_age": core.Duration.days(10)
                            })

        integration = apigw.CfnIntegration(
            scope=self,
            id='integration',
            api_id=api.http_api_id,
            credentials_arn=role.role_arn,
            integration_type='AWS_PROXY',
            integration_uri=lambda_function.function_arn,
            integration_method='POST',
            payload_format_version='2.0')

        apigw.CfnRoute(scope=self,
                       id='route',
                       api_id=api.http_api_id,
                       route_key='POST /',
                       target=f'integrations/{integration.ref}')
    def __init__(self, scope: core.Construct, construct_id: str,
                 apigw_role: _iam.Role, eventBus: _events.EventBus, **kwargs):
        super().__init__(scope, construct_id, **kwargs)

        myApi = _apigwv2.CfnApi(
            self,
            construct_id,
            protocol_type="WEBSOCKET",
            route_selection_expression="${request.body.language}",
            name=construct_id)

        integration = _apigwv2.CfnIntegration(self, "EventBusIntegration",
            api_id=myApi.ref,
            integration_type="AWS",
            integration_method="POST",
            integration_uri=f"arn:aws:apigateway:{os.environ['CDK_DEFAULT_REGION']}:events:path//",
            credentials_arn=apigw_role.role_arn,
            template_selection_expression="application/json",
            request_parameters={
                    "integration.request.header.X-Amz-Target": "'AWSEvents.PutEvents'",
                    "integration.request.header.Content-Type": "'application/x-amz-json-1.1'",
            },
            request_templates={
                "application/json":'#set($language=$input.params(\'language\'))\n{"Entries": [{"Source": "com.amazon.alexa.$language",' + \
                                       ' "Detail": "$util.escapeJavaScript($input.body)",' + \
                                       ' "Resources": ["resource1", "resource2"], ' + \
                                       ' "DetailType": "myDetailType", "EventBusName": "' + eventBus.event_bus_name + '"}]}'
            }
        )

        germanRoute = _apigwv2.CfnRoute(
            self,
            "MyGermanRoute",
            api_id=myApi.ref,
            route_key="german",
            target=f"integrations/{integration.ref}",
            route_response_selection_expression='$default')

        genericIntegrationResponse = _apigwv2.CfnIntegrationResponse(
            self,
            "genericIntegrationResponse",
            api_id=myApi.ref,
            integration_id=integration.ref,
            integration_response_key="/200/")

        genericRouteResponse = _apigwv2.CfnRouteResponse(
            self,
            "genericRouteResponse",
            api_id=myApi.ref,
            route_id=germanRoute.ref,
            route_response_key="$default")

        defaultRoute = _apigwv2.CfnRoute(
            self,
            "MyDefaultRoute",
            api_id=myApi.ref,
            route_key="$default",
            target=f"integrations/{integration.ref}",
        )

        myStage = _apigwv2.CfnStage(self,
                                    "MyStage",
                                    api_id=myApi.ref,
                                    stage_name="prod",
                                    auto_deploy=True)
        myStage.add_depends_on(defaultRoute)
        myStage.add_depends_on(germanRoute)
        myStage.add_depends_on(genericIntegrationResponse)

        core.CfnOutput(
            self,
            "APIEndpoint",
            description="APIEndpoint",
            value=
            f"wss://{myApi.ref}.execute-api.{os.environ['CDK_DEFAULT_REGION']}.amazonaws.com/prod"
        )