def __init__( self, scope: core.Construct, id: str, # pylint: disable=redefined-builtin lambda_notifications: aws_lambda.IFunction, social_log_group: aws_logs.ILogGroup, pagespeed_table: aws_dynamodb.ITable, **kwargs) -> None: super().__init__(scope, id, **kwargs) api_lambda = get_lambda( self, id, code='lib/stacks/{id}/{id}'.format(id=id), handler='main.handler', environment={ 'CORS_ALLOW_ORIGIN': env['CORS_ALLOW_ORIGIN'], 'PUSHOVER_TOKEN': env['PUSHOVER_TOKEN'], 'PUSHOVER_USERKEY': env['PUSHOVER_USERKEY'], 'LAMBDA_FUNCTIONS_LOG_LEVEL': 'INFO', 'LAMBDA_NOTIFICATIONS': lambda_notifications.function_name, 'PAGESPEED_TABLE': pagespeed_table.table_name, 'REPORT_LOG_GROUP_NAME': social_log_group.log_group_name, }, ) lambda_notifications.grant_invoke(api_lambda) social_log_group.grant(api_lambda, "logs:GetLogEvents", "logs:DescribeLogStreams") pagespeed_table.grant_read_data(api_lambda) cert = aws_certificatemanager.Certificate( self, '{}-certificate'.format(id), domain_name=env['API_DOMAIN'], ) domain = aws_apigateway.DomainNameOptions( certificate=cert, domain_name=env['API_DOMAIN'], ) cors = aws_apigateway.CorsOptions( allow_methods=['POST'], allow_origins=[env['CORS_ALLOW_ORIGIN']] if "CORS_ALLOW_ORIGIN" in env else aws_apigateway.Cors.ALL_ORIGINS) aws_apigateway.LambdaRestApi( self, '%s-gateway' % id, handler=api_lambda, domain_name=domain, default_cors_preflight_options=cors, )
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 # Sorry, it's late toots_function = _lambda.Function(self, "Toots Function", runtime=_lambda.Runtime.NODEJS_12_X, code=_lambda.Code.asset('lambda'), handler="index.handler") apigw.LambdaRestApi(self, 'Endpoint', handler=toots_function)
def __init__(self, scope: core.Construct, id: str, handler: lambda_.Function, context: InfraContext, **kwargs) -> None: super().__init__(scope, id, **kwargs) self.rest_api = a.LambdaRestApi(self, id, options=a.RestApiProps(), handler=handler, proxy=True, description='Frontend proxy for ' + handler.function_name)
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) lambda_lith = _lambda.Function( self, "lambdalithHandler", runtime=_lambda.Runtime.PYTHON_3_8, handler="lambdalith.handler", code=_lambda.Code.from_asset("lambda_fns/the_lambda_lith/flask")) # defines an API Gateway REST API resource backed by our "lambda_lith" function. api_gw.LambdaRestApi(self, 'LambdalithAPI', handler=lambda_lith)
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) testLambda: _lambda.Function = FfmpegLambdaStack.cdkResourcesCreate( self) projectPolicy = FfmpegLambdaStack.createPolicy(self, testLambda) apigw.LambdaRestApi(self, 'Endpoint', handler=testLambda, binary_media_types=['multipart/form-data'])
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) my_lambda = _lambda.Function( self, 'CatFactsHandler', runtime=_lambda.Runtime.PYTHON_3_7, code=_lambda.Code.asset('lambda/deployment.zip'), handler='cat_facts.handler', ) apigw.LambdaRestApi(self, 'Endpoint', handler=my_lambda)
def __init__(self, scope: core.Construct, id: str, stage: Optional[str] = 'prod', **kwargs) -> None: super().__init__(scope, id + '-' + stage, **kwargs) acct_table_name = id + '-accounts-table-' + stage acct_table = ddb.Table(self, id=acct_table_name, table_name=acct_table_name, partition_key=ddb.Attribute( name='id', type=ddb.AttributeType.STRING), billing_mode=ddb.BillingMode.PAY_PER_REQUEST) events_table_name = id + '-events-table-' + stage events_table = ddb.Table(self, id=events_table_name, table_name=events_table_name, partition_key=ddb.Attribute( name='id', type=ddb.AttributeType.STRING), billing_mode=ddb.BillingMode.PAY_PER_REQUEST, stream=ddb.StreamViewType.NEW_IMAGE) self._table_stream_arn = events_table.table_stream_arn # create our Lambda function for the bank account service func_name = id + '-' + stage + '-' + 'bank-accounts' handler = lambda_.Function( self, func_name, code=lambda_.Code.from_asset('bank_account_service'), runtime=lambda_.Runtime.NODEJS_10_X, handler='handler.handler', environment={ 'ACCOUNTS_TABLE_NAME': acct_table.table_name, 'EVENTS_TABLE_NAME': events_table.table_name, 'REGION': core.Aws.REGION }) self._bank_account_service = handler gw.LambdaRestApi(self, id=stage + '-' + id, handler=handler) # give EventBridge permission to invoke this Lambda handler.add_permission( id='EBPermission', principal=iam.ServicePrincipal('events.amazonaws.com'), action='lambda:InvokeFunction') acct_table.grant_read_write_data(handler.role) events_table.grant_read_write_data(handler.role)
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) lambda_function = lb.Function(self, 'helloworldfunction', runtime=lb.Runtime.PYTHON_3_8, code=lb.Code.asset('lambda'), handler='hello.handler') api_gateway = apigw.LambdaRestApi(self, 'helloworld', handler=lambda_function, rest_api_name='mylambdaapi')
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 lambda_function = _lambda.Function( self, 'Valhalla-Bot', runtime=_lambda.Runtime.PYTHON_3_8, code=_lambda.AssetCode('lambda'), handler='app.handler', ) apigw.LambdaRestApi(self, 'Endpoint', handler=lambda_function)
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) handler = aws_lambda.Function( self, "cdk-lambda-apigateway", runtime=aws_lambda.Runtime.PYTHON_3_7, handler="api.main", code=aws_lambda.AssetCode(path="./lambda")) api = aws_apigateway.LambdaRestApi(self, "LambdawithAPIGateway", handler=handler)
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) user_info_collecter = UserCollecter( self, 'UserInfoCollecter', ) apigw.LambdaRestApi( self, 'Endpoint', handler=user_info_collecter.handler, )
def create_rest_apis(self) -> None: '''Rest API Gateway integrations with Lambda ''' self.rest_api_blog = aws_apigateway.LambdaRestApi( self, 'sls-blog-rest-api-gateway', handler=self.lambda_blog, deploy_options=aws_apigateway.StageOptions( stage_name='api', throttling_rate_limit=self.lambda_param_max_concurrency, logging_level=aws_apigateway.MethodLoggingLevel('INFO'), ), )
def __init__(self, app: core.App, id: str, props, **kwargs) -> None: super().__init__(app, id, **kwargs) handler = lambda_.Function( self, "UrlShortenerFunction", code=aws_lambda.Code.asset("./lambda"), handler="lambda_function.lambda_handler", timeout=Duration.minutes(5), runtime=aws_lambda.Runtime.PYTHON_3_7) # define the API endpoint and associate the handler api = apig.LambdaRestApi( self, "IoTPgControlPlaneApi", handler=handler)
def __init__(self, scope: core.Construct, id: str, demo_table: dynamodb.Table, **kwargs) -> None: super().__init__(scope, id, **kwargs) bundling_options = core.BundlingOptions( image=_lambda.Runtime.NODEJS_12_X.bundling_docker_image, user="******", command=[ 'bash', '-c', 'cp /asset-input/* /asset-output/ && cd /asset-output && npm test' ] ) source_code = _lambda.Code.from_asset( './lambda', bundling=bundling_options ) # create lambda function web_lambda = _lambda.Function( self, "dynamo-lambda-function", runtime=_lambda.Runtime.NODEJS_12_X, handler="dynamoFunction.handler", code=source_code, environment=dict( TABLE_NAME=demo_table.table_name ) ) # grant permission to lambda to write to demo table demo_table.grant_full_access( web_lambda ) codedeploy.LambdaDeploymentGroup( self, "web-lambda-deployment", alias=web_lambda.current_version.add_alias("live"), deployment_config=codedeploy.LambdaDeploymentConfig.ALL_AT_ONCE ) gw = _apigw.LambdaRestApi( self, "Gateway", handler=web_lambda, description="Endpoint for a simple Lambda-powered web service" ) # add an output with a well-known name to read it from the integ tests self.gw_url = gw.url
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) # DynamoDB Table # This is standing in for what is RDS on the diagram due to simpler/cheaper setup table = dynamo_db.Table(self, "Messages", partition_key=dynamo_db.Attribute( name="id", type=dynamo_db.AttributeType.STRING)) # Queue Setup sqs_queue = sqs.Queue(self, 'RDSPublishQueue', visibility_timeout=core.Duration.seconds(300)) # defines an AWS Lambda resource to publish to our sqs_queue sqs_publish_lambda = _lambda.Function( self, "SQSPublishLambdaHandler", runtime=_lambda.Runtime.NODEJS_12_X, # execution environment handler="lambda.handler", # file is "lambda", function is "handler" code=_lambda.Code.from_asset( "lambda_fns/publish" ), # Code loaded from the lambda_fns/publish dir environment={'queueURL': sqs_queue.queue_url}) sqs_queue.grant_send_messages(sqs_publish_lambda) # defines an AWS Lambda resource to pull from our sqs_queue sqs_subscribe_lambda = _lambda.Function( self, "SQSSubscribeLambdaHandler", runtime=_lambda.Runtime.NODEJS_12_X, # execution environment handler="lambda.handler", # file is "lambda", function is "handler" code=_lambda.Code.from_asset( "lambda_fns/subscribe" ), # Code loaded from the lambda_fns/subscribe dir environment={ 'queueURL': sqs_queue.queue_url, 'tableName': table.table_name }, reserved_concurrent_executions=2) sqs_queue.grant_consume_messages(sqs_subscribe_lambda) sqs_subscribe_lambda.add_event_source( lambda_event.SqsEventSource(sqs_queue)) table.grant_read_write_data(sqs_subscribe_lambda) # defines an API Gateway REST API resource backed by our "sqs_publish_lambda" function. api_gw.LambdaRestApi(self, 'Endpoint', handler=sqs_publish_lambda)
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: super().__init__(scope, construct_id, **kwargs) my_lambda = _lambda.Function(self, 'HelloHandler', runtime=_lambda.Runtime.PYTHON_3_7, code=_lambda.Code.from_asset('lambda'), handler='hello.handler') hello_with_counter = HitCounter(self, 'HelloHitCounter', downstream=my_lambda) apigw.LambdaRestApi(self, 'Endpoint', handler=hello_with_counter._handler)
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) # Defines an AWS Lambda resource my_lambda = _lambda.Function(self, 'HelloHandler', runtime=_lambda.Runtime.PYTHON_3_7, code=_lambda.Code.asset('lambda'), handler='hello.handler') apigw.LambdaRestApi( self, 'Endpoint', handler=my_lambda, )
def __init__(self, scope: cdk.Construct, construct_id: str, **kwargs) -> None: super().__init__(scope, construct_id, **kwargs) lambda_func = lambda_.DockerImageFunction( scope=self, id="tso-lambda-function", code=lambda_.DockerImageCode.from_image_asset( directory="../docker"), memory_size=3000, timeout=core.Duration.seconds(60)) api = apigateway.LambdaRestApi(self, "tso-apigateway", handler=lambda_func)
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) role_arn = 'arn:aws:iam::315207712355:role/lbrole' role = iam.Role.from_role_arn(self, id='role_id', role_arn=role_arn) # The code that defines your stack goes here this_dir = path.dirname(__file__) handler = lmb.Function(self, 'Handler', runtime=lmb.Runtime.PYTHON_3_7, role=role, handler='handler.handler', code=lmb.Code.from_asset( path.join(this_dir, 'lambda'))) alias = lmb.Alias(self, 'HandlerAlias', alias_name='Current', version=handler.current_version) gw = apigw.LambdaRestApi( self, 'Gateway', description='Endpoint for a simple Lambda-powered web service', handler=alias) failure_alarm = cloudwatch.Alarm(self, 'FailureAlarm', metric=cloudwatch.Metric( metric_name='5XXError', namespace='AWS/ApiGateway', dimensions={ 'ApiName': 'Gateway', }, statistic='Sum', period=core.Duration.minutes(1)), threshold=1, evaluation_periods=1) codedeploy.LambdaDeploymentGroup( self, 'DeploymentGroup', alias=alias, deployment_config=codedeploy.LambdaDeploymentConfig. CANARY_10_PERCENT_10_MINUTES, alarms=[failure_alarm]) self.url_output = core.CfnOutput(self, 'Url', value=gw.url)
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) # The code that defines your stack goes here ''' v0.1 The below line, with only one line of code, will create a DynamoDB table that is name "url-shortener-table" as well as having one defined attribute of type String call "id" ''' table = aws_dynamodb.Table(self, "url-shortner-table", partition_key=aws_dynamodb.Attribute(name="id", type=aws_dynamodb.AttributeType.STRING)) ''' v0.2 As we did previously with creating DynamoDB, we now create a Lambda function. Please take note of the following: * the "runtime" is defined from the static class aws_lambda.Runtime.<Runtime> * the handler is referencing the function "main" in the handler.py file * Code refers to the bundling of code assets from the entire directory ./lambda ''' function = aws_lambda.Function(self, 'backend', runtime=aws_lambda.Runtime.PYTHON_3_7, handler='handler.main', code=aws_lambda.Code.asset('./lambda')) ''' v0.3 The following creates the tie in between the lambda function and the dynamodb table by granting read and write permissions to the function on the table itself this also involves injecting environment variables - please refer to the file handler.py to see where the environment variable is used ''' # create the tie in between the lambda function and the DynamoDB table table.grant_read_write_data(function) # add the environment variable for the function to consume function.add_environment("TABLE_NAME", table.table_name) # create the API Gateway ''' v0.4 The following is the entirety of the construct of creating the API Gateway and having it front the previously created lambda function ''' api = aws_apigateway.LambdaRestApi(self, 'api', handler=function)
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) this_dir = path.dirname(__file__) handler = lmb.Function(self, 'Handler', runtime=lmb.Runtime.PYTHON_3_8, handler='handler.handler', code=lmb.Code.from_asset(path.join(this_dir, 'lambda'))) gw = apigw.LambdaRestApi(self, 'Gateway', description='Endpoint for a simple Lambda-powered web service', handler=handler.current_version) self.url_output = core.CfnOutput(self, 'Url', value=gw.url)
def __init__(self, scope: core.Construct, id: str, lambda_echo: aws_lambda.Function, common_stack: CommonStack, **kwargs) -> None: super().__init__(scope, id, **kwargs) self._supported_in_region = self.is_service_supported_in_region() endpoint = aws_apigateway.LambdaRestApi(self, "endpoint", handler=lambda_echo) self._parameters_to_save = {"endpointURL": endpoint.url} self.save_parameters_in_parameter_store(platform=Platform.IOS) common_stack.add_to_common_role_policies(self)
def create_apigateway(self): apig = aws_apigateway.LambdaRestApi(self, API_NAME, handler=self.apig_handler, proxy=False, deploy=True) users = apig.root.add_resource("users") users.add_method("GET") user = apig.root.add_resource("{userId}") user.add_method("GET") user.add_method("POST") user.add_method("DELETE") self.apig = apig
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) my_lambda = _lambda.Function( self, 'vlan-game', runtime=_lambda.Runtime.PYTHON_3_7, code=_lambda.Code.asset('src'), handler='game', ) apigw.LambdaRestApi( self, 'Endpoint', handler=my_lambda, )
def __init__(self, scope: Construct, id: str, **kwarg) -> None: super().__init__(scope, id, **kwarg) # define the table that maps short codes to URLs. table = aws_dynamodb.Table(self, "Table", partition_key=aws_dynamodb.Attribute( name="id", type=aws_dynamodb.AttributeType.STRING), read_capacity=10, write_capacity=5) # define the API gateway request handler. all API requests will go to the same function. handler = aws_lambda.Function(self, "UrlShortenerFunction", code=aws_lambda.Code.asset("./lambda"), handler="handler.main", timeout=Duration.minutes(5), runtime=aws_lambda.Runtime.PYTHON_3_7) # generate the topic to publish to topic = aws_sns.Topic(self, "Topic", display_name="Url created topic") topic.add_subscription(aws_sns_subscriptions.EmailSubscription("*****@*****.**")) # pass the table name to the handler through an environment variable and grant # the handler read/write permissions on the table. handler.add_environment('TABLE_NAME', table.table_name) handler.add_environment('TOPIC_ARN', topic.topic_arn) table.grant_read_write_data(handler) topic.grant_publish(handler) # define the API endpoint and associate the handler api = aws_apigateway.LambdaRestApi(self, "UrlShortenerApi", handler=handler) # define the static website hosting frontendBucket = aws_s3.Bucket(self, "UrlShortenerWebsiteBucket", public_read_access=True, removal_policy=core.RemovalPolicy.DESTROY, website_index_document="index.html") deployment = aws_s3_deployment.BucketDeployment(self, "deployStaticWebsite", sources=[aws_s3_deployment.Source.asset("./frontend")], destination_bucket=frontendBucket) # define a Watchful monitoring system and watch the entire scope # this will automatically find all watchable resources and add # them to our dashboard wf = Watchful(self, 'watchful', alarm_email='*****@*****.**') wf.watch_scope(self)
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) lambda_function = lb.Function(self, 'streamlinkerfunction', runtime=lb.Runtime.PYTHON_3_8, code=lb.Code.asset('lambda'), handler='streamlinker.handler', timeout=core.Duration.seconds(30)) api_gateway = apigw.LambdaRestApi( self, 'streamlinker', handler=lambda_function, rest_api_name='streamlinkerapi', default_cors_preflight_options=apigw.CorsOptions( allow_origins=apigw.Cors.ALL_ORIGINS))
def __init__(self, scope: core.Construct, id: str, *, alarm_email: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) functions_path = os.path.join(os.path.dirname(__file__), '../lambda') backend = _lambda.Function(self, 'BackendFunction', handler='backend.handler', runtime=_lambda.Runtime.PYTHON_3_7, code=_lambda.Code.from_asset(functions_path)) hit_count_handler = HitCounter(self, 'HitCountHandler', downstream_function=backend).handler desc = 'A simple example REST API backed by lambda using CDK' api = _apigw.LambdaRestApi(self, 'RestApi', handler=hit_count_handler, description=desc) watch = Watchful(self, 'my-monitoring', alarm_email=alarm_email) watch.watch_scope(self)
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: cdk.Construct, construct_id: str, **kwargs) -> None: super().__init__(scope, construct_id, **kwargs) my_lambda = _lambda.Function( self, 'HelloHandler', runtime=_lambda.Runtime.PYTHON_3_7, code=_lambda.Code.asset('lambda'), handler='hello.handler', ) apigw.LambdaRestApi( self, 'Endpoint', handler=my_lambda, )
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) hello_lambda = _lambda.Function( self, 'HelloHandler', runtime=_lambda.Runtime.PYTHON_3_7, code=_lambda.Code.asset('lambda'), handler='hello.handler', ) apigw.LambdaRestApi( self, 'PycdkStackEndpoint', handler=hello_lambda, endpoint_types=[apigw.EndpointType.REGIONAL], )