def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        prj_name = self.node.try_get_context("project_name")
        env_name = self.node.try_get_context("env")

        api_gateway = apigw.RestApi(self,'restapi',
            endpoint_types=[apigw.EndpointType.REGIONAL],
            minimum_compression_size=1024,
            binary_media_types=["multipart/form-data"],
            rest_api_name=prj_name+'-apigateway'
            
        )
        apigw.Method(self,'method1',
            http_method="POST",
            resource=api_gateway
        )

        #TODO
        #domain name

        
        
        
            
Beispiel #2
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 #3
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)
Beispiel #4
0
 def _create_rest_api(self, api_log_group, gw, stage):
     return _api_gw.RestApi(
         self,
         gw["gw_name"],
         rest_api_name=gw["gw_name"],
         deploy_options={
             "description":
             gw["gw_stage_description"],
             "logging_level":
             LOG_INFO,
             "tracing_enabled":
             True,
             "stage_name":
             stage,
             "access_log_destination":
             LogGroupLogDestination(api_log_group),
             "access_log_format":
             AccessLogFormat.json_with_standard_fields(caller=False,
                                                       http_method=True,
                                                       ip=True,
                                                       protocol=True,
                                                       request_time=True,
                                                       resource_path=True,
                                                       response_length=True,
                                                       status=True,
                                                       user=True),
             "metrics_enabled":
             True,
         },
         endpoint_configuration={"types": [EndpointType.REGIONAL]},
         deploy=True,
         cloud_watch_role=True,
         description=gw["gw_description"],
     )
    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),
        )
    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 __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))
    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 #9
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, 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 #11
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 #12
0
    def __init__(self, scope: core.Construct, id: str,
                 user_pool_arn: str) -> None:
        super().__init__(scope, id)

        core.CfnOutput(self, id="StackName", value=get_stack_name())

        self.service_role = iam.Role(
            self,
            "KesherServiceRole",
            assumed_by=iam.ServicePrincipal("lambda.amazonaws.com"),
            inline_policies={
                "KesherServicePolicy":
                iam.PolicyDocument(statements=[
                    iam.PolicyStatement(actions=[
                        "logs:CreateLogGroup", "logs:CreateLogStream",
                        "logs:PutLogEvents"
                    ],
                                        resources=["arn:aws:logs:*:*:*"],
                                        effect=iam.Effect.ALLOW)
                ])
            })

        EmailServices(scope=self, id="Email", lambda_role=self.service_role)

        role_output = core.CfnOutput(self,
                                     id="KesherServiceRoleArn",
                                     value=self.service_role.role_arn)
        role_output.override_logical_id("KesherServiceRoleArn")

        self.table = aws_dynamodb.Table(
            self,
            'kesher-employees',
            partition_key=aws_dynamodb.Attribute(
                name="id", type=aws_dynamodb.AttributeType.STRING),
            billing_mode=aws_dynamodb.BillingMode.PAY_PER_REQUEST,
            removal_policy=core.RemovalPolicy.RETAIN)
        self.table.grant_read_write_data(self.service_role)

        self.rest_api: apigw.LambdaRestApi = apigw.RestApi(
            self,
            "kesher-rest-api",
            rest_api_name="kesher Rest API",
            description="This service handles kesher's APIs..")
        endpoint_output = core.CfnOutput(self,
                                         id="KesherApiGw",
                                         value=self.rest_api.url)
        endpoint_output.override_logical_id("KesherApiGw")

        self.api_authorizer: apigw.CfnAuthorizer = self.__create_api_authorizer(
            user_pool_arn=user_pool_arn, api=self.rest_api)

        self.api_resource: apigw.Resource = self.rest_api.root.add_resource(
            "api")

        self._environment = {"KESHER_USER_POOL_ARN": user_pool_arn}
        self._add_children_api()
        self._add_report_categories_api()
        self._add_user_profile_api()
Beispiel #13
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}"
    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 #15
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))
Beispiel #16
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)
Beispiel #17
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

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

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

        hello_world = _lambda.Function(
            self,
            "HelloWorld",
            runtime=_lambda.Runtime.PYTHON_3_8,
            handler='helloworld.lambda_handler',
            code=_lambda.Code.from_asset("lambda_fns"),
            timeout=core.Duration.seconds(60))

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

        self.resource_arn = f"arn:aws:apigateway:{core.Stack.of(self).region}::/restapis/{self.target_api.rest_api_id}/stages/{self.target_api.deployment_stage.stage_name}"
Beispiel #18
0
    def __init__(self, scope: core.Construct, construct_id: str, processing_bucket, processing_bucket_upload_prefix) -> None:
        super().__init__(scope, construct_id)

        # lambda to act as upload API handler
        lambda_name = 'image-pipeline-s3-url-generator'
        s3_url_generator_lambda = aws_lambda.Function(
            self,
            lambda_name,
            function_name=lambda_name,
            runtime=aws_lambda.Runtime.NODEJS_12_X,
            code=aws_lambda.Code.asset('lambda_functions/get_signed_s3_url'),
            handler='app.handler',
            environment={
                'UploadBucket': processing_bucket.bucket_name,
                'UploadPrefix': processing_bucket_upload_prefix,
            },
            timeout=core.Duration.minutes(3)
        )
        # write access allows the lambda to generate signed urls
        processing_bucket.grant_write(s3_url_generator_lambda)

        # rest api endpoint to pass requests to lambda
        base_api = aws_apigateway.RestApi(self, 'ImageUpload',
                                          rest_api_name='ImageUpload')
        # we'll send uploads to the `image` prefix, CORS must be allowed
        image_entity = base_api.root.add_resource(
            'images',
            default_cors_preflight_options=aws_apigateway.CorsOptions(
                allow_origins=aws_apigateway.Cors.ALL_ORIGINS)
        )

        # hooks the endpoint up to the lambda above
        image_entity_lambda_integration = aws_apigateway.LambdaIntegration(
            s3_url_generator_lambda,
            proxy=False,
            integration_responses=[{
                'statusCode': '200',
                'responseParameters': {
                    'method.response.header.Access-Control-Allow-Origin': "'*'",
                }
            }])

        # GET will be used to get presigned url
        image_entity.add_method(
            'GET',
            image_entity_lambda_integration,
            method_responses=[{
                'statusCode': '200',
                'responseParameters': {
                    'method.response.header.Access-Control-Allow-Origin': True,
                }
            }])

        self.api = base_api
Beispiel #19
0
    def create_and_integrate_apigw(self, queue: sqs.Queue,
                                   dashboard_name_prefix: str) -> str:
        """Creates API Gateway and integrates with SQS queue

        :param queue: the SQS queue to integrate with
        :type queue: aws_cdk.aws_sqs.Queue
        :param dashboard_name_prefix: the dashboard name to use as the API Gateway resource name
        :type dashboard_name_prefix: str
        :returns: the url that the webhooks will post to
        :rtype: str
        """
        webhook_apigw_role = iam.Role(
            self,
            'WebhookAPIRole',
            role_name='WebhookAPIRole',
            assumed_by=iam.ServicePrincipal('apigateway.amazonaws.com'))
        webhook_apigw_role.add_to_policy(
            iam.PolicyStatement(resources=['*'], actions=['sqs:SendMessage']))

        webhook_apigw = apigw.RestApi(
            self,
            'RepositoryStatusMonitorAPI',
            rest_api_name='RepositoryStatusMonitorAPI')
        webhook_apigw_resource = webhook_apigw.root.add_resource(
            dashboard_name_prefix)

        apigw_integration_response = apigw.IntegrationResponse(
            status_code='200', response_templates={'application/json': ""})
        apigw_integration_options = apigw.IntegrationOptions(
            credentials_role=webhook_apigw_role,
            integration_responses=[apigw_integration_response],
            request_templates={
                'application/json':
                'Action=SendMessage&MessageBody=$input.body'
            },
            passthrough_behavior=apigw.PassthroughBehavior.NEVER,
            request_parameters={
                'integration.request.header.Content-Type':
                "'application/x-www-form-urlencoded'"
            })
        webhook_apigw_resource_sqs_integration = apigw.AwsIntegration(
            service='sqs',
            integration_http_method='POST',
            path='{}/{}'.format(core.Aws.ACCOUNT_ID, queue.queue_name),
            options=apigw_integration_options)

        webhook_apigw_resource.add_method(
            'POST',
            webhook_apigw_resource_sqs_integration,
            method_responses=[apigw.MethodResponse(status_code='200')])

        path = '/' + dashboard_name_prefix
        return webhook_apigw.url_for_path(path)
Beispiel #20
0
    def __init__(self, scope: core.Construct, id: str, common_stack: CommonStack, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        self._supported_in_region = self.is_service_supported_in_region()

        # Create API
        api = apigateway.RestApi(self, "testApi")

        # Generate a random API key, add it to the underlying CloudFormation
        # resource of the Construct so that we can use it in our tests.
        api_key_value = self.random_hex(20)
        api_key = api.add_api_key("testKey")
        cfn_api_key = api_key.node.default_child
        cfn_api_key.add_property_override("Value", api_key_value)

        # Create Usage Plan and add it to the API
        plan = api.add_usage_plan("usagePlan", api_key=api_key)
        plan.add_api_stage(stage=api.deployment_stage)

        # Create resources in API
        echo = api.root.add_resource("echo")
        echo_post = echo.add_resource("post")
        auth = api.root.add_resource("auth")
        apikey = api.root.add_resource("apikey")

        # Wire up methods
        get_url = self.HTTPBIN_URL_TEMPLATE.format(method="get")
        post_url = self.HTTPBIN_URL_TEMPLATE.format(method="post")

        get_integration = apigateway.HttpIntegration(get_url)
        post_integration = apigateway.HttpIntegration(post_url, http_method="POST")
        options_integration = apigateway.HttpIntegration(get_url, http_method="OPTIONS")
        head_integration = apigateway.HttpIntegration(get_url, http_method="HEAD")

        echo.add_method("GET", get_integration)
        echo.add_method("OPTIONS", options_integration)
        echo.add_method("HEAD", head_integration)
        echo_post.add_method("POST", post_integration)
        auth.add_method("GET", get_integration, authorization_type=apigateway.AuthorizationType.IAM)
        apikey.add_method("GET", get_integration, api_key_required=True)

        # Generate all methods for /echo
        for method in ("put", "post", "delete", "patch"):
            url = self.HTTPBIN_URL_TEMPLATE.format(method=method)
            integration = apigateway.HttpIntegration(url, http_method=method)
            echo.add_method(method.upper(), integration)

        # Create SSM parameters for the endpoint of the API and the API key

        self._parameters_to_save = {"endpoint": api.url, "api_key": api_key_value}
        self.save_parameters_in_parameter_store(platform=Platform.ANDROID)

        common_stack.add_to_common_role_policies(self)
Beispiel #21
0
    def __init__(self, scope: core.Construct, construct_id: str,
                 apigw_role: _iam.Role, eventBus: _events.EventBus, **kwargs):
        super().__init__(scope, construct_id, **kwargs)

        integrationOptions = \
            _apigw.IntegrationOptions(
                credentials_role=apigw_role,
                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 + '"}]}'
                },
                integration_responses=[_apigw.IntegrationResponse(
                    status_code="200",
                    response_templates={"application/json": ""},
                )]
            )

        # Integration API Gateway with EventBridge
        integrationEventBridge = _apigw.Integration(
            type=_apigw.IntegrationType("AWS"),
            integration_http_method="POST",
            options=integrationOptions,
            uri=
            f"arn:aws:apigateway:{os.environ['CDK_DEFAULT_REGION']}:events:path//"
        )

        myApi = _apigw.RestApi(self, construct_id)
        # myApi.root.add_method("POST",
        #     integrationEventBridge,
        #     method_responses=[
        #         _apigw.MethodResponse(
        #             status_code="200"
        #         )
        #     ]
        # )

        languageResource = myApi.root.add_resource("{language}")
        languageResource.add_method(
            "POST",
            integrationEventBridge,
            method_responses=[_apigw.MethodResponse(status_code="200")],
            request_models={"application/json": self.getModel(myApi)},
            request_validator=_apigw.RequestValidator(
                self,
                "myValidator",
                rest_api=myApi,
                validate_request_body=True))
Beispiel #22
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        api = aws_apigateway.RestApi(self, "example")

        create_noddy_endpoint(api.root, "GET", {"message": "hi from root!"})

        apples = aws_apigateway.Resource(self,
                                         id="apples",
                                         parent=api.root,
                                         path_part="apples")

        create_noddy_endpoint(apples, "GET", {"message": "You have 3 apples"})
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        table = dynamo.Table(
            self,
            'Table',
            table_name='subscriptions',
            partition_key=dynamo.Attribute(name='pk',
                                           type=dynamo.AttributeType.STRING),
            sort_key=dynamo.Attribute(name='sk',
                                      type=dynamo.AttributeType.STRING),
            time_to_live_attribute='ttl')

        template_name = 'EmailVerification'
        template = ses.CfnTemplate(
            self,
            'Template',
            template={
                'htmlPart': '<div><a href="{code}">Verify Email</a></div>',
                'subjectPart': 'Verify Email Address',
                'templateName': template_name
            })

        create_subscription = lambda_.Function(
            self,
            'CreateSubscriptionFunction',
            function_name='create_subscription',
            handler='src.main.handler',
            code=lambda_.Code.from_asset('../functions/create_subscription'),
            runtime=lambda_.Runtime.PYTHON_3_7,
            environment={
                'TEMPLATE_NAME': template_name,
                'TABLE_NAME': table.table_name
            })

        # Update Lambda Permissions
        create_subscription.add_to_role_policy(
            iam.PolicyStatement(actions=['ses:SendEmail', 'ses:SendRawEmail'],
                                resources=['*']))

        table.grant_read_write_data(create_subscription)

        # API
        api = ag.RestApi(self, 'Api', rest_api_name='email-subscriptions')

        subscriptions_resource = api.root.add_resource('subscriptions')

        subscriptions_resource.add_method('POST',
                                          integration=ag.LambdaIntegration(
                                              handler=create_subscription,
                                              proxy=True))
Beispiel #24
0
    def __init__(self, scope: core.Construct, id: str, func: _lambda.IFunction, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        api = apigw.RestApi(
            self,
            "APIGateway",
        )

        entity = api.root.add_resource("github")
        entity_lambda_integration = apigw.LambdaIntegration(
            func,
            proxy=True
        )
        entity.add_method("POST", entity_lambda_integration)
Beispiel #25
0
    def __init__(self, scope: core.App, id: str, domain: apigw.DomainName,
                 **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        api = apigw.RestApi(self, 'api2')
        domain.add_base_path_mapping(api, base_path="api2")

        hello_handler = _lambda.Function(
            self,
            'LambdaHandler',
            runtime=_lambda.Runtime.PYTHON_3_7,
            handler="index.handler",
            code=_lambda.Code.from_inline(handler_func),
        )
        api.root.add_method("GET", apigw.LambdaIntegration(hello_handler))
Beispiel #26
0
 def create_app(self, settings) -> aws_apigateway.RestApi:
     return aws_apigateway.RestApi(
         self,
         settings.AWS_API_GATEWAY_APP_NAME,
         # For now we do not want to keep old deployments
         retain_deployments=False,
         minimum_compression_size=10240,
         default_cors_preflight_options={
             "allow_origins": settings.CORS_ALLOWED_ORIGINS.split(","),
             "allow_methods": ["GET", "POST", "OPTIONS"],
         },
         # Because deployment is made by another stack,
         # we have to prevent deploying this API
         deploy=False,
     )
Beispiel #27
0
    def __init__(self, scope: cdk.Construct, construct_id: str,
                 **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        # Lambda function

        hello_function = lambda_.Function(
            self,
            "hello-function",
            code=lambda_.Code.from_asset("src/hello/"),
            handler="main.handler",
            runtime=lambda_.Runtime.PYTHON_3_8,
            tracing=lambda_.Tracing.ACTIVE)

        logs.LogGroup(
            self,
            "hello-logs",
            log_group_name=f"/aws/lambda/{hello_function.function_name}",
            retention=logs.RetentionDays.ONE_WEEK)

        # API Gateway

        api_logs = logs.LogGroup(self,
                                 "hello-api-logs",
                                 retention=logs.RetentionDays.ONE_WEEK)

        api = apigw.RestApi(
            self,
            "hello-api",
            deploy_options=apigw.StageOptions(
                access_log_destination=apigw.LogGroupLogDestination(api_logs),
                access_log_format=apigw.AccessLogFormat.
                json_with_standard_fields(caller=True,
                                          http_method=True,
                                          ip=True,
                                          protocol=True,
                                          request_time=True,
                                          resource_path=True,
                                          response_length=True,
                                          status=True,
                                          user=True),
                throttling_burst_limit=1000,
                throttling_rate_limit=10,
                tracing_enabled=True))

        hello_integration = apigw.LambdaIntegration(hello_function, proxy=True)
        api.root.add_method("GET", hello_integration)
    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)
    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)
    def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        # Ensure the Cognito ARN is set
        cognito_arn = os.environ.get('COGNITO_ARN')
        if cognito_arn is None:
            raise ValueError(
                'An environment variable for COGNITO_ARN is required')

        # Deploy Lambda
        my_lambda = _lambda.Function(
            self, 'HelloHandler',
            runtime=_lambda.Runtime.PYTHON_3_7,
            code=_lambda.Code.asset('lambda'),
            handler='hello.handler',
        )

        # create the API gateway
        api = apigw.RestApi(
            self,
            'HelloHandler2',
            rest_api_name="LCAOA_Demo",
            description="Demo of lambda, cognito, Azure AD and OpenId auth"
        )

        # configure the Authorizer
        auth = apigw.CfnAuthorizer(
            scope=self,
            id='cognito_authorizer',
            rest_api_id=api.rest_api_id,
            name='MyAuth',
            type='COGNITO_USER_POOLS',
            identity_source='method.request.header.Authorization',
            provider_arns=[
                cognito_arn
            ]
        )
        resource = api.root.add_resource("endpoint")
        lambda_integration = apigw.LambdaIntegration(
            my_lambda, proxy=True)
        method = resource.add_method("GET", lambda_integration)
        method_resource = method.node.find_child('Resource')
        method_resource.add_property_override(
            'AuthorizationType', 'COGNITO_USER_POOLS')
        method_resource.add_property_override(
            'AuthorizerId', {"Ref": auth.logical_id})