Beispiel #1
0
    def __init__(self, scope: core.Construct, id: str):
        super().__init__(scope, id)

        bucket = s3.Bucket(self, "WidgetStore")

        handler = lambda_.Function(self,
                                   "WidgetHandler",
                                   runtime=lambda_.Runtime.NODEJS_10_X,
                                   code=lambda_.Code.asset("resources"),
                                   handler="widgets.main",
                                   environment=dict(BUCKET=bucket.bucket_name))

        bucket.grant_read_write(handler)

        api = apigateway.RestApi(self,
                                 "widgets-api",
                                 rest_api_name="Widget Service",
                                 description="This service serves widgets.")

        widget = api.root.add_resource("{id}")

        # Add new widget to bucket with: POST /{id}
        post_widget_integration = apigateway.LambdaIntegration(handler)

        # Get a specific widget from bucket with: GET /{id}
        get_widget_integration = apigateway.LambdaIntegration(handler)

        # Remove a specific widget from the bucket with: DELETE /{id}
        delete_widget_integration = apigateway.LambdaIntegration(handler)

        widget.add_method("POST", post_widget_integration)  # POST /{id}
        widget.add_method("GET", get_widget_integration)  # GET /{id}
        widget.add_method("DELETE", delete_widget_integration)  # DELETE /{id}
    def __init__(self, scope: core.Construct, id: str):
        super().__init__(scope, id)

        bucket = s3.Bucket(self, "WidgetStore")
        handler = lambda_.Function(
            self,
            "WidgetHandler",
            runtime=lambda_.Runtime.PYTHON_3_7,
            code=lambda_.Code.asset("resources"),
            handler="widgets.handler",
            environment=dict(BUCKET=bucket.bucket_name),
        )

        bucket.grant_read_write(handler)

        api = apigateway.RestApi(
            self,
            "widgets-api",
            rest_api_name="Widget Service",
            description="This service serves widgets.",
        )

        get_widgets_integration = apigateway.LambdaIntegration(
            handler,
            request_templates={"application/json": '{"statusCode":"200"}'})
        api.root.add_method("GET", get_widgets_integration)

        widget = api.root.add_resource("widget")
        post_widget_integration = apigateway.LambdaIntegration(handler)
        get_widget_integration = apigateway.LambdaIntegration(handler)
        delete_widget_integration = apigateway.LambdaIntegration(handler)
        widget.add_method("POST", post_widget_integration)
        widget.add_method("GET", get_widget_integration)
        widget.add_method("DELETE", delete_widget_integration)
Beispiel #3
0
    def _add_generic_api_integration(self,
                                     api_resource: aws_apigateway.Resource,
                                     api_function,
                                     get_access_auth: bool = False,
                                     edit_access_auth: bool = False,
                                     is_proxy: bool = False):

        api_lambda_integration = aws_apigateway.LambdaIntegration(
            api_function,
            proxy=False,
            integration_responses=[self.get_integration_response()],
            request_templates={
                "application/json": self.get_request_template()
            })

        if is_proxy:
            api_lambda_integration_without_response = aws_apigateway.LambdaIntegration(
                api_function,
                proxy=False,
                request_templates={
                    "application/json": self.get_request_template()
                })
            api_resource = api_resource.add_proxy(
                default_integration=api_lambda_integration_without_response,
                any_method=False)

        self.add_cors_options(api_resource)
        get_authorizer = self._api_authorizer if get_access_auth else None
        edit_authorizer = self._api_authorizer if edit_access_auth else None

        self._add_generic_api_method(api_resource, api_lambda_integration,
                                     ["GET"], get_authorizer)
        self._add_generic_api_method(api_resource, api_lambda_integration,
                                     ["POST"], edit_authorizer)
    def __init__(self, scope: core.Construct, construct_id: str,
                 **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        # The code that defines your stack goes here

        # DynamoDB定義
        dynamo_table = dynamo.Table(
            self,
            "schedule",
            partition_key={
                "name": "id",
                "type": dynamo.AttributeType.STRING,
            },
            table_name="schedule",
            removal_policy=core.RemovalPolicy.
            DESTROY,  # NOT recommended for production code
        )

        # GET Request
        get_schedule_lambda = lam.Function(
            self,
            "get-schedule-function",
            code=lam.Code.from_asset("lambda"),
            handler="get_schedule.lambda_handler",
            runtime=lam.Runtime.PYTHON_3_8,
            environment={
                "TABLE_NAME": dynamo_table.table_name,
                "PRIMARY_KEY": "id",
            },
        )
        dynamo_table.grant_read_data(get_schedule_lambda)

        # POST Request
        set_schedule_lambda = lam.Function(
            self,
            "set-schedule-function",
            code=lam.Code.from_asset("lambda"),
            handler="set_schedule.lambda_handler",
            runtime=lam.Runtime.PYTHON_3_8,
            environment={
                "TABLE_NAME": dynamo_table.table_name,
                "PRIMARY_KEY": "id",
            },
        )
        dynamo_table.grant_read_write_data(set_schedule_lambda)

        api = apigateway.RestApi(self,
                                 "scheduler-api-template",
                                 rest_api_name="scheduler-api-template")

        schedule = api.root.add_resource("schedule")
        schedule.add_resource("{id}").add_method(
            "GET", apigateway.LambdaIntegration(get_schedule_lambda))
        # schedule.add_method("GET", apigateway.LambdaIntegration(get_schedule_lambda))
        schedule.add_method("POST",
                            apigateway.LambdaIntegration(set_schedule_lambda))
        add_cors_options(schedule)
Beispiel #5
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)
        self.table_name = 'globaldatatest.global.table'
        executelambda = aws_lambda.Function(
            self,
            id='execute',
            runtime=aws_lambda.Runtime.PYTHON_3_8,
            handler='execute.lambda_handler',
            code=aws_lambda.Code.asset('lambda'))

        statsLambda = aws_lambda.Function(
            self,
            id='stats',
            runtime=aws_lambda.Runtime.PYTHON_3_8,
            handler='stats.lambda_handler',
            code=aws_lambda.Code.asset('lambda'))

        resetLambda = aws_lambda.Function(
            self,
            id='reset',
            runtime=aws_lambda.Runtime.PYTHON_3_8,
            handler='reset.lambda_handler',
            code=aws_lambda.Code.asset('lambda'))

        my_bucket = s3.Bucket(self, id='s3buckset3', bucket_name='s3mybucket')
        table = aws_dynamodb.Table(self,
                                   'table3',
                                   partition_key={
                                       'name': 'key',
                                       'type':
                                       aws_dynamodb.AttributeType.STRING
                                   },
                                   table_name='commands')
        api = apigateway.RestApi(
            self,
            "web-shell-apii",
            rest_api_name="Web Shell",
            description="This service serves shell commands.")
        executeIntegration = apigateway.LambdaIntegration(executelambda)
        statsIntegration = apigateway.LambdaIntegration(statsLambda)
        resetIntegration = apigateway.LambdaIntegration(resetLambda)

        executeResource = api.root.add_resource('execute')
        executeResource.add_method("POST",
                                   executeIntegration,
                                   api_key_required=True)

        statsResource = api.root.add_resource('stats')
        statsResource.add_method("GET",
                                 statsIntegration,
                                 api_key_required=True)

        resetResource = api.root.add_resource('reset')
        resetResource.add_method("PUT",
                                 resetIntegration,
                                 api_key_required=True)
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # lambda
        lambda_ = aws_lambda.Function(
            self,
            "ApiLambdaIntegrationLambda",
            code=aws_lambda.Code.asset("lambdas/api_lambda_integration"),
            runtime=aws_lambda.Runtime.PYTHON_3_8,
            handler="lambda_function.lambda_handler",
        )

        # API Gateway
        api = aws_apigateway.RestApi(
            self,
            "ApiLambdaIntegrationApiGateway",
            deploy_options=aws_apigateway.StageOptions(stage_name="hogehoge"))
        hoge_resources = api.root.add_resource("hoge")
        hoge_resources.add_method(
            "GET",
            aws_apigateway.LambdaIntegration(lambda_),
            request_parameters={
                # クエリ文字列(URLパラメータ)の明示的に宣言
                "method.request.querystring.hoge": True,  # 必須
                "method.request.querystring.hogeOption": False,  # 必須ではない
            },
            # 下記設定を入れないと必須フラグは動作しない
            request_validator=api.add_request_validator(
                "ApiLambdaIntegrationValidator",
                validate_request_parameters=True),
        )
Beispiel #7
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # create s3 bucket
        bucket = s3.Bucket(self,
                           "cdkdemobucket",
                           public_read_access=True,
                           bucket_name="cdkdemobucket")

        # upload local file to s3 bucket
        deploy = s3deploy.BucketDeployment(
            self,
            'DeployLocal',
            sources=[s3deploy.Source.asset('resources/s3')],
            destination_bucket=bucket)

        # create lambda function
        handler = lambda_.Function(
            self,
            "toppage",
            runtime=lambda_.Runtime.PYTHON_3_7,
            code=lambda_.Code.asset("resources/webapp/artifact"),
            handler="webapp.main",
            environment=dict(BUCKET=bucket.bucket_name))

        bucket.grant_read_write(handler)

        #api gateway
        api = apigateway.RestApi(self, "demo page", rest_api_name="demo page")
        get_top_page = apigateway.LambdaIntegration(
            handler,
            request_templates={"application/json": '{ "statusCode": "200" }'})

        api.root.add_method("GET", get_top_page)
    def __configure_gateway(self) -> None:
        self.gateway = a.RestApi(self, 'PortfolioMgmt')

        # Create kinesis integration
        integration_role = iam.Role(
            self,
            'KinesisIntegrationRole',
            assumed_by=iam.ServicePrincipal('apigateway.amazonaws.com'))

        self.updates_stream.grant_write(integration_role)

        updates = self.gateway.root.add_resource('updates')
        updates.add_method(http_method='POST',
                           authorization_type=a.AuthorizationType.IAM,
                           integration=a.AwsIntegration(
                               service='kinesis',
                               action='PutRecord',
                               subdomain=self.updates_stream.stream_name,
                               options=a.IntegrationOptions(
                                   credentials_role=integration_role)))

        pmapi = self.gateway.root.add_resource('pmapi')
        pmapi.add_proxy(
            any_method=True,
            default_integration=a.LambdaIntegration(handler=PythonLambda(
                self,
                'PortfolioMgmtAPI',
                build_prefix='artifacts/FinSurf-PortfolioMgmt-API',
                handler='handler.app',
                subnet_group_name='PortfolioMgmt',
                context=self.context,
                securityGroups=[self.security_group]).function))
Beispiel #9
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # The code that defines your stack goes here
        handler = _lambda.Function(
            self,
            "demo_func",
            runtime=_lambda.Runtime.PYTHON_3_7,
            handler="demo_func.handler",
            timeout=Duration.minutes(1),  # pylint: disable=E1120
            code=_lambda.Code.asset("lambda_code/demo_func"),  # pylint: disable=E1120
        )

        api_gw = _apigw.RestApi(self,
                                "ApiGatewayForSlack",
                                rest_api_name="gw_for_slack")

        exam_entity = api_gw.root.add_resource("test")
        exam_entity_lambda_integration = _apigw.LambdaIntegration(
            handler,
            proxy=False,
            integration_responses=[{
                "statusCode": "200"
            }],
        )
        exam_entity.add_method(
            "GET",
            exam_entity_lambda_integration,
            method_responses=[{
                "statusCode": "200"
            }],
        )
Beispiel #10
0
    def __init__(self, scope: core.Construct, id, lambda_function):
        super().__init__(scope = scope, id=id, rest_api_name=id) 

        # Common API Gateway options
        integration_responses = [
            {
                'statusCode': '200',
                'responseParameters': {
                    'method.response.header.Access-Control-Allow-Headers': "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent'",
                    'method.response.header.Access-Control-Allow-Origin': "'*'",
                    'method.response.header.Access-Control-Allow-Credentials': "'false'",
                    'method.response.header.Access-Control-Allow-Methods': "'OPTIONS,GET,PUT,POST,DELETE'",
                }
            }
        ]
        method_responses=[{
            'statusCode': '200',
            'responseParameters': {
                'method.response.header.Access-Control-Allow-Headers': True,
                'method.response.header.Access-Control-Allow-Methods': True,
                'method.response.header.Access-Control-Allow-Credentials': True,
                'method.response.header.Access-Control-Allow-Origin': True,
            },  
        }]
        request_templates={
            "application/json": "{\"statusCode\": 200}"
        }

        # API Gateway Resource
        api_gw = self.root.add_resource('test')
        integration_lambda = aws_apigateway.LambdaIntegration(lambda_function, proxy=False, integration_responses=integration_responses, passthrough_behavior=aws_apigateway.PassthroughBehavior.NEVER, request_templates=request_templates)
        api_gw.add_method('GET', integration_lambda, method_responses=method_responses)
        self.add_cors_options(api_gw)
Beispiel #11
0
    def create_resource_handler(
        self,
        name,
        handler,
        api,
        path,
        methods,
        code,
        table,
        memory_size=512,
        readonly=True,
    ):

        function = self.create_function(
            name=name,
            handler=handler,
            memory_size=memory_size,
            code=code,
            table=table,
            readonly=readonly,
        )

        api_resource = api.root.resource_for_path(path)

        for method in methods:
            api_resource.add_method(method,
                                    _apigateway.LambdaIntegration(function))
Beispiel #12
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # API GW lambdas first:
        dummy_lambda = aws_lambda.Function(
            self,
            id,
            function_name='dummy_lambda',
            handler='lambda_handler.handler',
            runtime=aws_lambda.Runtime.PYTHON_3_7,
            code=aws_lambda.Code.asset('src/api_lambda/dummy_lambda'),
        )

        # API Gateway
        base_api = apigw.RestApi(self, 'ApiGatewayWithCors')

        # Lambda Integration
        dummy_entity = base_api.root.add_resource('dummy')
        dummy_lambda_integration = apigw.LambdaIntegration(
            dummy_lambda,
            proxy=False,
            integration_responses=api_gw_integration.integration_response())

        dummy_entity.add_method(
            'GET',
            dummy_lambda_integration,
            method_responses=api_gw_integration.GET_response())
Beispiel #13
0
    def create_API_GW_integration(self, disambiguator: str,
                                  lambda_function: aws_lambda.Function,
                                  function_name: str) -> apigateway.RestApi:
        lambda_integration = apigateway.LambdaIntegration(lambda_function)

        # The fields in this construct can't be tokens, for example, references to the lambda function name:
        # jsii.errors.JSIIError: Cannot use tokens in construct ID: DocumentGuardian-beta-ApiGw-${Token[TOKEN.87]}
        # Which is why this function has the `function_name` arg.
        api_gw_rest_api = apigateway.RestApi(
            self,
            '-'.join([
                self.STACK_NAME_PREFIX, disambiguator, 'ApiGw', function_name
            ]),
            rest_api_name='-'.join(
                [self.STACK_NAME_PREFIX, disambiguator, function_name]),
            description="This API handles all requests to " +
            self.STACK_NAME_PREFIX + function_name + ".",
        )
        api_gw_rest_api.root.add_method('ANY', lambda_integration)

        api_gw_proxy = apigateway.Resource(self,
                                           '-'.join([
                                               self.STACK_NAME_PREFIX,
                                               disambiguator, function_name,
                                               'root'
                                           ]),
                                           parent=api_gw_rest_api.root,
                                           path_part='{proxy+}')
        api_gw_proxy.add_method('ANY', lambda_integration)
        return api_gw_rest_api
Beispiel #14
0
 def __init__(
     self,
     scope: core.Construct,
     id: str,
     function_name: str,
     handler: str,
     config_bucket: aws_s3.Bucket,
     state_table: aws_dynamodb.Table,
     dependency_layer: aws_lambda.LayerVersion,
     api: aws_apigateway.RestApi,
     endpoint: str,
 ) -> None:
     super().__init__(scope, id)
     environment = {
         'bridge_env': 'PROD',
         'bridge_config': f's3://{config_bucket.bucket_name}/bridge.json',
         'state_dynamodb_table': state_table.table_name,
     }
     self.function = aws_lambda.Function(
         self,
         function_name,
         function_name=function_name,
         runtime=aws_lambda.Runtime.PYTHON_3_8,
         layers=[dependency_layer],
         code=code_asset,
         handler=handler,
         timeout=core.Duration.seconds(30),
         retry_attempts=0,
         environment=environment,
     )
     function_resource = api.root.add_resource(endpoint)
     function_resource.add_method(
         'POST', aws_apigateway.LambdaIntegration(handler=self.function, ))
     config_bucket.grant_read(self.function)
     state_table.grant_write_data(self.function)
    def __init__(self, scope: core.Construct, construct_id: str,
                 **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        state_machine_role = _iam.Role(
            self,
            "state_machine_role",
            assumed_by=_iam.ServicePrincipal("lambda.amazonaws.com"),
        )

        state_machine_role.add_to_policy(
            _iam.PolicyStatement(
                resources=["*"],
                actions=[
                    "lambda:InvokeFunction",
                    "logs:CreateLogGroup",
                    "logs:CreateLogStream",
                    "logs:PutLogEvents",
                ],
            ))

        state_machine_handler = _lambda.Function(
            self,
            'state_machine_handler',
            code=_lambda.Code.asset('lambdas'),
            environment={
                "REGION": "us-east-1",
            },
            function_name="state_machine_handler",
            handler='state_machine_handler.lambda_handler',
            role=state_machine_role,
            runtime=_lambda.Runtime.PYTHON_3_7,
            timeout=core.Duration.seconds(2),
        )

        api_gateway_definition = _apigw.RestApi(
            self,
            'api_gateway_definition',
            default_cors_preflight_options={
                "allow_origins": _apigw.Cors.ALL_ORIGINS,
                "allow_methods": _apigw.Cors.ALL_METHODS,
            },
            description="Api to engage or handler states machines.",
            rest_api_name="state_machine_api_gateway",
        )

        state_machine = _apigw.LambdaIntegration(state_machine_handler)

        state_machine_resource = api_gateway_definition.root.add_resource("sm")

        state_machine_resource.add_method("GET", state_machine)

        _dynamodb.Table(
            self,
            "solicitud_test",
            table_name="solicitud_test",
            partition_key=_dynamodb.Attribute(
                name="id", type=_dynamodb.AttributeType.STRING),
            stream=_dynamodb.StreamViewType.NEW_AND_OLD_IMAGES,
        )
    def __init__(self, scope: core.Construct, id: str):
        super().__init__(scope, id)
        '''wallet_table = dynamodb.table('WalletDetail')
        transaction_table = dynamodb.table('TransactionDetail')'''

        create_trx_handler = lambda_.Function(
            "Transaction",
            "TrxCreateHandler",
            function_name="TransactionCreate",
            runtime=lambda_.Runtime.PYTHON_3_7,
            code=lambda_.Code.asset("resources"),
            handler="create.handler",
            environment=dict(WALLET_TABLE="WalletDetail",
                             TRANSACTION_TABLE="TransactionDetail"))
        '''transaction_table.grant_read_write_data(create_trx_handler)
        wallet_table.grant_read_write_data(create_trx_handler)'''

        api = apigateway.RestApi(self,
                                 "Transaction-api",
                                 rest_api_name="Wallet Service",
                                 description="This service serves Wallets.")

        post_integration = apigateway.LambdaIntegration(
            create_trx_handler,
            request_templates={"application/json": '{ "statusCode": "200" }'})

        api.root.add_method("POST", post_integration)
    def __init__(self, scope: core.Construct, id: str, base_lambda,
                 **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        base_api = _apigw.RestApi(self,
                                  'ApiGatewayWithCors',
                                  rest_api_name='report-api')
        resource = base_api.root.add_resource('report')

        resource_lambda_integration = _apigw.LambdaIntegration(
            base_lambda,
            proxy=False,
            integration_responses=[{
                'statusCode': '200',
                'responseParameters': {
                    'method.response.header.Access-Control-Allow-Origin': "'*'"
                }
            }])

        resource.add_method(
            'POST',
            resource_lambda_integration,
            method_responses=[{
                'statusCode': '200',
                'responseParameters': {
                    'method.response.header.Access-Control-Allow-Origin': True,
                }
            }])

        self.add_cors_options(resource)
Beispiel #18
0
    def _add_create_lambda_integration(
            self, id_: str, table: aws_dynamodb.Table) -> aws_lambda.Function:
        lambda_role = self._create_lambda_role(role_name='TenantCreateRole',
                                               table=table,
                                               write_permission=True)
        func = aws_lambda.Function(
            self,
            f'{id_}CreateTenant',
            function_name=f'{id_}CreateTenant',
            runtime=aws_lambda.Runtime.PYTHON_3_7,
            code=aws_lambda.Code.from_asset('.build/service'),
            handler='crud_api.functions.handler.create_tenant',
            role=lambda_role,
            environment={
                'TENANT_MNGT_USER_POOL_ARN': self.user_pool_arn,
                'PROFILE': self._profile,
                'USER_NAME': self._username,
                'TENANTS_TABLE_NAME': table.table_name,
            },
            timeout=core.Duration.seconds(10),
            memory_size=192,
        )
        # Bind POST /tenants/ to the lambda
        method = self.tenants_resource.add_method(
            http_method="POST",
            integration=aws_apigateway.LambdaIntegration(
                handler=func),  # POST /tenants/
            authorization_type=aws_apigateway.AuthorizationType.COGNITO,
        )

        method_resource: aws_apigateway.Resource = method.node.find_child(
            "Resource")
        method_resource.add_property_override(
            "AuthorizerId", {"Ref": self.api_authorizer.logical_id})
        return func
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # lambda function
        issue_boards_maintainer = aws_lambda.Function(
            self,
            "issue_boards_maintainer",
            function_name="issue_boards_maintainer",
            code=aws_lambda.Code.asset("../functions/issue_boards_maintainer"),
            handler="lambda_function.issue_boards_maintainer",
            timeout=core.Duration.seconds(300),
            runtime=aws_lambda.Runtime.PYTHON_3_7,
            memory_size=1024,
            environment={
                "SECRET_TOKEN": os.environ.get("SECRET_TOKEN"),
                "ACCESS_TOKEN": os.environ.get("ACCESS_TOKEN"),
                "PROJECT_A_PROJECT_ID": os.environ.get("PROJECT_A_PROJECT_ID"),
                "PROJECT_B_PROJECT_ID": os.environ.get("PROJECT_B_PROJECT_ID")
            })

        # api gateway
        rest_api = aws_apigateway.RestApi(self,
                                          'issue_boards_webhook',
                                          rest_api_name='issue_boards_webhook')

        resource_entity = rest_api.root.add_resource('webhook')
        lambda_integration_entity = aws_apigateway.LambdaIntegration(
            issue_boards_maintainer, proxy=True)
        resource_entity.add_method('POST', lambda_integration_entity)
    def __init__(self, scope: cdk.Construct, construct_id: str,
                 **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        announcements_table = aws_dynamodb.Table(
            scope=self,
            id='announcements_table',
            partition_key=aws_dynamodb.Attribute(
                name='id',
                type=aws_dynamodb.AttributeType.STRING,
            ),
        )
        api = aws_apigateway.RestApi(
            scope=self,
            id='announcements_rest_api_gateway',
        )
        announcements_endpoint = api.root.add_resource('announcements')

        get_announcements_handler = aws_lambda_python.PythonFunction(
            scope=self,
            id='GetAnnouncementHandler',
            entry='lambda',
            index='get.py',
            handler='handler',
            runtime=aws_lambda.Runtime.PYTHON_3_8,
        )
        create_announcement_handler = aws_lambda_python.PythonFunction(
            scope=self,
            id='CreateAnnouncementHandler',
            entry='lambda',
            index='create.py',
            handler='handler',
            runtime=aws_lambda.Runtime.PYTHON_3_6,
        )
        announcements_table.grant_read_data(get_announcements_handler)
        announcements_table.grant_read_write_data(create_announcement_handler)
        get_announcements_handler.add_environment(
            'TABLE_NAME', announcements_table.table_name)
        create_announcement_handler.add_environment(
            'TABLE_NAME', announcements_table.table_name)
        get_announcements_integration = aws_apigateway.LambdaIntegration(
            get_announcements_handler)
        create_announcements_integration = aws_apigateway.LambdaIntegration(
            create_announcement_handler)
        announcements_endpoint.add_method('GET', get_announcements_integration)
        announcements_endpoint.add_method('POST',
                                          create_announcements_integration)
Beispiel #21
0
 def create_api(self, discord_app_handler: Function):
     api = aws_apigateway.RestApi(self,
                                  "eternal-guesses-api",
                                  rest_api_name="Eternal Guesses API")
     discord_app_integration = aws_apigateway.LambdaIntegration(
         discord_app_handler)
     discord_resource = api.root.add_resource("discord")
     discord_resource.add_method("POST", discord_app_integration)
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        ###
        # We have 3 separate lambda functions, all coming from separate files
        ###

        add_lambda = _lambda.Function(
            self,
            "addLambdaHandler",
            runtime=_lambda.Runtime.PYTHON_3_8,
            handler="add.handler",
            code=_lambda.Code.from_asset(
                "lambda_fns/the_single_purpose_function"))

        subtract_lambda = _lambda.Function(
            self,
            "subtractLambdaHandler",
            runtime=_lambda.Runtime.PYTHON_3_8,
            handler="subtract.handler",
            code=_lambda.Code.from_asset(
                "lambda_fns/the_single_purpose_function"))

        multiply_lambda = _lambda.Function(
            self,
            "multiplyLambdaHandler",
            runtime=_lambda.Runtime.PYTHON_3_8,
            handler="multiply.handler",
            code=_lambda.Code.from_asset(
                "lambda_fns/the_single_purpose_function"))

        ###
        # All functions have their own endpoint defined on our gateway
        ##

        api = api_gw.LambdaRestApi(self,
                                   'singlePurposeFunctionAPI',
                                   handler=add_lambda,
                                   proxy=False)

        api.root.resource_for_path('add').add_method(
            'GET', api_gw.LambdaIntegration(add_lambda))
        api.root.resource_for_path('subtract').add_method(
            'GET', api_gw.LambdaIntegration(subtract_lambda))
        api.root.resource_for_path('multiply').add_method(
            'GET', api_gw.LambdaIntegration(multiply_lambda))
    def __init__(self, scope: core.Construct, id: str):
        super().__init__(scope, id)

        bucket = s3.Bucket(self, "ResumeStore")

        handler = lambda_.Function(self,
                                   "ResumeHandler",
                                   runtime=lambda_.Runtime.NODEJS_10_X,
                                   code=lambda_.Code.asset("resources"),
                                   handler="resume.main",
                                   environment=dict(BUCKET=bucket.bucket_name))

        bucket.grant_read_write(handler)

        api = apigateway.RestApi(
            self,
            "resume-api",
            rest_api_name="Resume Service",
            description="This service serves Resume Module.")

        get_widgets_integration = apigateway.LambdaIntegration(
            handler,
            request_templates={"application/json": '{ "statusCode": "200" }'})

        api.root.add_method("GET", get_widgets_integration)  # GET /
        print(id)
        widget = api.root.add_resource("{id}")

        # resumeData = api.root.add_resource('data')
        # resumeData.add_method('POST')
        # resumeData.add_method('GET')

        # Add new widget to bucket with: POST /{id}
        post_widget_integration = apigateway.LambdaIntegration(handler)

        # Get a specific widget from bucket with: GET /{id}
        get_widget_integration = apigateway.LambdaIntegration(handler)

        # Remove a specific widget from the bucket with: DELETE /{id}
        delete_widget_integration = apigateway.LambdaIntegration(handler)

        widget.add_method("POST", post_widget_integration)
        # POST /{id}
        widget.add_method("GET", get_widget_integration)
        # GET /{id}
        widget.add_method("DELETE", delete_widget_integration)
Beispiel #24
0
 def rest_api(self, event_streams, event_replayer):
     rest_api = _api_gtw.RestApi(self, "{}RestApi".format(self.stack_id))
     rest_api.add_usage_plan("RestApiUsagePlan",
                             api_key=_api_gtw.ApiKey(self, "TestApiKey"),
                             api_stages=[
                                 _api_gtw.UsagePlanPerApiStage(
                                     api=rest_api,
                                     stage=rest_api.deployment_stage)
                             ])
     api_role = _iam.Role(
         self,
         "RestApiRole",
         assumed_by=_iam.ServicePrincipal('apigateway.amazonaws.com'))
     api_role.add_to_policy(
         _iam.PolicyStatement(
             actions=['firehose:PutRecord'],
             resources=[stream.attr_arn for stream in event_streams]))
     for stream in event_streams:
         stream_resource = rest_api.root.add_resource(
             path_part=stream.delivery_stream_name.lower(), )
         stream_resource.add_method(
             'POST',
             api_key_required=True,
             integration=_api_gtw.Integration(
                 type=_api_gtw.IntegrationType.AWS,
                 uri=
                 "arn:aws:apigateway:eu-west-1:firehose:action/PutRecord",
                 integration_http_method='POST',
                 options=_api_gtw.IntegrationOptions(
                     credentials_role=api_role,
                     passthrough_behavior=_api_gtw.PassthroughBehavior.
                     NEVER,
                     request_parameters={
                         'integration.request.header.Content-Type':
                         "'application/x-amz-json-1.1'"
                     },
                     request_templates={
                         'application/json':
                         json.dumps({
                             "DeliveryStreamName":
                             stream.delivery_stream_name,
                             "Record": {
                                 "Data": "$util.base64Encode($input.body)"
                             }
                         })
                     },
                     integration_responses=[
                         _api_gtw.IntegrationResponse(status_code="200")
                     ])),
             method_responses=[_api_gtw.MethodResponse(status_code="200")])
         replay = stream_resource.add_resource(path_part='replay')
         replay.add_method(
             http_method='POST',
             integration=_api_gtw.LambdaIntegration(event_replayer),
             method_responses=[
                 _api_gtw.MethodResponse(status_code="202"),
                 _api_gtw.MethodResponse(status_code="400")
             ])
Beispiel #25
0
    def __init__(self, scope: Construct, id: str, settings, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)
        self.id = id

        # cdk deploy --parameters StageName=v1
        stage = CfnParameter(
            self, "StageName",
            default="v1",
            description="The name of the API Gateway Stage.",
            type="String",
        ).value_as_string

        table_name = f"{id}Table"

        # Create a dynamodb table
        table = self.create_dynamodb_table(table_name)

        # Create function and role for OAuth
        func_oauth_role = self.create_func_oauth_execution_role(f"{id}-OAuth", table_arn=table.table_arn)
        func_oauth = self.create_lambda("OAuth", custom_role=func_oauth_role)
        func_oauth.add_environment("SlackAppClientIdParameterKey", CLIENT_ID_PARAMETER_NAME)
        func_oauth.add_environment("SlackAppClientSecretParameterKey", CLIENT_SECRET_PARAMETER_NAME)
        func_oauth.add_environment("SlackAppOAuthDynamoDBTable", table_name)
        func_oauth.add_environment("SlackChannelIds", ",".join(get_channel_ids(settings)))
        func_oauth.add_environment("SlackTeamIds", ",".join(get_team_ids(settings)))

        api = apigw_.LambdaRestApi(
            self, f"{id}-API",
            description=f"{id} API",
            endpoint_configuration=apigw_.EndpointConfiguration(types=[apigw_.EndpointType.REGIONAL]),
            handler=func_oauth,
            deploy=False,
            proxy=False,
        )

        item = api.root.add_resource("oauth2")
        item.add_method("ANY", apigw_.LambdaIntegration(func_oauth))

        # Create APIGW Loggroup for setting retention
        LogGroup(
            self, f"{id}-API-LogGroup",
            log_group_name=f"API-Gateway-Execution-Logs_{api.rest_api_id}/{stage}",
            retention=RetentionDays.ONE_DAY,
        )

        # Do a new deployment on specific stage
        new_deployment = apigw_.Deployment(self, f"{id}-API-Deployment", api=api)
        apigw_.Stage(
            self, f"{id}-API-Stage",
            data_trace_enabled=True,
            description=f"{stage} environment",
            deployment=new_deployment,
            logging_level=apigw_.MethodLoggingLevel.INFO,
            metrics_enabled=True,
            stage_name=stage,
            tracing_enabled=False,
        )
Beispiel #26
0
    def __init__(self, scope: core.Construct, id: str, stack_prefix: str,
                 **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # IAM Roles
        lambda_role = _iam.Role(
            self,
            id='{}-lambda-role'.format(stack_prefix),
            assumed_by=_iam.ServicePrincipal('lambda.amazonaws.com'))

        cw_policy_statement = _iam.PolicyStatement(effect=_iam.Effect.ALLOW)
        cw_policy_statement.add_actions("logs:CreateLogGroup")
        cw_policy_statement.add_actions("logs:CreateLogStream")
        cw_policy_statement.add_actions("logs:PutLogEvents")
        cw_policy_statement.add_actions("logs:DescribeLogStreams")
        cw_policy_statement.add_resources("*")
        lambda_role.add_to_policy(cw_policy_statement)

        # AWS Lambda Functions
        fnLambda_secureAPI = _lambda.Function(
            self,
            "{}-function-secureApi".format(stack_prefix),
            code=_lambda.AssetCode("../lambda-functions/secure-api"),
            handler="app.handler",
            timeout=core.Duration.seconds(60),
            role=lambda_role,
            runtime=_lambda.Runtime.PYTHON_3_8)

        fnLambda_authorizer = _lambda.Function(
            self,
            "{}-function-tokenAuthorizer".format(stack_prefix),
            code=_lambda.AssetCode("../lambda-functions/token-authorizer"),
            handler="app.handler",
            timeout=core.Duration.seconds(60),
            role=lambda_role,
            runtime=_lambda.Runtime.PYTHON_3_8)

        api = _ag.RestApi(
            self,
            id="{}-api-gateway".format(stack_prefix),
        )

        api_authorizer = _ag.TokenAuthorizer(
            self,
            id="{}-authorizer".format(stack_prefix),
            handler=fnLambda_authorizer)

        int_secure_api = _ag.LambdaIntegration(fnLambda_secureAPI)

        res_data = api.root.add_resource('api')
        res_data.add_method('GET', int_secure_api, authorizer=api_authorizer)

        core.CfnOutput(self,
                       "{}-output-apiEndpointURL".format(stack_prefix),
                       value=api.url,
                       export_name="{}-apiEndpointURL".format(stack_prefix))
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # S3 Bucket to store files
        myBucket = aws_s3.Bucket(self,
                                 "S3Bucket",
                                 bucket_name="new-app-bucket-example"
                                 )

        # Lambda triggered periodically
        myScheduledLambda = _lambda.Function(
            self,
            "scheduled_lambda",
            description="Lambda that will be called according to a schedule",
            function_name="scheduledLambda",
            runtime=_lambda.Runtime.PYTHON_3_7,
            handler="scheduled_lambda.handler",
            code=_lambda.Code.from_asset("../functions"),
            memory_size=128,  # Memory in mb
            retry_attempts=2,
            environment={"S3_BUCKET": myBucket.bucket_name}
        )
        # Give Lambda access to S3 bucket
        myBucket.grant_read(myScheduledLambda)
        myBucket.grant_put(myScheduledLambda)

        # Create cron Rule for Lambda
        myScheduledLambdaEvent = aws_events.Rule(
            self,
            "scheduled_lambda_event",
            schedule=aws_events.Schedule.rate(core.Duration.minutes(2)),
            enabled=True,
            targets=[aws_events_targets.LambdaFunction(handler=myScheduledLambda)]
        )

        # API Gateway Proxy Lambda definition
        myEndpointLambda = _lambda.Function(
            self,
            "endpoint_lambda",
            description="Lambda Proxy with Api Gateway",
            function_name="endpointLambda",
            runtime=_lambda.Runtime.PYTHON_3_7,
            handler="endpoint_lambda.handler",
            code=_lambda.Code.from_asset("../functions"),
            memory_size=128,  # Memory in mb
            retry_attempts=2,
            environment={"S3_BUCKET": myBucket.bucket_name}
        )
        # Give lambda access to S3 Bucket
        myBucket.grant_read(myEndpointLambda)
        myBucket.grant_put(myEndpointLambda)

        # Define API Gateway endpoints
        api = aws_apigateway.RestApi(self, "ApiEndpoint")
        api.root.resource_for_path("/test").add_method("GET",
                                                       aws_apigateway.LambdaIntegration(handler=myEndpointLambda))
Beispiel #28
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        api_log_group = cwlogs.LogGroup(self, "HelloWorldAPILogs")

        # Create the api gateway for this lambda set
        self.target_api = apigw.RestApi(
            self,
            'HelloWorldAPI',
            rest_api_name='HelloWorld',
            endpoint_types=[apigw.EndpointType.REGIONAL],
            deploy_options={
                "access_log_destination":
                apigw.LogGroupLogDestination(api_log_group),
                "access_log_format":
                apigw.AccessLogFormat.clf(),
                "method_options": {
                    "/*/*":
                    {  # This special path applies to all resource paths and all HTTP methods
                        "throttling_rate_limit": 100,
                        "throttling_burst_limit": 200
                    }
                }
            })

        hello_world = py_lambda.PythonFunction(
            self,
            "HelloWorld",
            entry='thewafapigateway/lambda_fns',
            index='helloworld.py',
            handler='lambda_handler',
            description='Helloworld',
            timeout=core.Duration.seconds(60))

        entity = self.target_api.root.add_resource('helloworld')
        this_lambda_integration = apigw.LambdaIntegration(
            hello_world,
            proxy=False,
            integration_responses=[{
                'statusCode': '200',
                'responseParameters': {
                    'method.response.header.Access-Control-Allow-Origin':
                    "'*'",
                }
            }])
        method = entity.add_method(
            'GET',
            this_lambda_integration,
            method_responses=[{
                'statusCode': '200',
                'responseParameters': {
                    'method.response.header.Access-Control-Allow-Origin': True,
                }
            }])

        self.resource_arn = f"arn:aws:apigateway:ap-southeast-2::/restapis/{self.target_api.rest_api_id}/stages/{self.target_api.deployment_stage.stage_name}"
Beispiel #29
0
    def __map_post_to_lambda_alias(self, pipeline_lambda: PipelineLambda):
        """Maps POSTs from /{lambda_name} to the prod alias for the specified Lambda.

        Note, {lambda_name} is the snake case version of the Lambda's name.
        """
        resource_name = _convert_camel_case_to_snake_case(pipeline_lambda.name)
        resource = self.__api.root.add_resource(resource_name)
        resource.add_method('POST',
                            integration=apigw.LambdaIntegration(
                                pipeline_lambda.alias))
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        ###
        # Even though all logic lives in the same file, we have 3 separate lambda functions
        ###

        add_lambda = _lambda.Function(
            self,
            "addLambdaHandler",
            runtime=_lambda.Runtime.PYTHON_3_8,
            handler="fatlambda.add",
            code=_lambda.Code.from_asset("lambda_fns/the_fat_lambda"))

        subtract_lambda = _lambda.Function(
            self,
            "subtractLambdaHandler",
            runtime=_lambda.Runtime.PYTHON_3_8,
            handler="fatlambda.subtract",
            code=_lambda.Code.from_asset("lambda_fns/the_fat_lambda"))

        multiply_lambda = _lambda.Function(
            self,
            "multiplyLambdaHandler",
            runtime=_lambda.Runtime.PYTHON_3_8,
            handler="fatlambda.multiply",
            code=_lambda.Code.from_asset("lambda_fns/the_fat_lambda"))

        ###
        # All functions have their own endpoint defined on our gateway
        ##

        api = api_gw.LambdaRestApi(self,
                                   'fatLambdaAPI',
                                   handler=add_lambda,
                                   proxy=False)

        api.root.resource_for_path('add').add_method(
            'GET', api_gw.LambdaIntegration(add_lambda))
        api.root.resource_for_path('subtract').add_method(
            'GET', api_gw.LambdaIntegration(subtract_lambda))
        api.root.resource_for_path('multiply').add_method(
            'GET', api_gw.LambdaIntegration(multiply_lambda))