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

        # Read Lambda Code):
        try:
            with open("serverless_stacks/lambda_src/konstone_processor.py",
                      mode="r") as f:
                konstone_fn_code = f.read()
        except OSError:
            print("Unable to read Lambda Function Code")

        konstone_fn = _lambda.Function(
            self,
            "konstoneFunction",
            function_name="konstone_function",
            runtime=_lambda.Runtime.PYTHON_3_7,
            handler="index.lambda_handler",
            code=_lambda.InlineCode(konstone_fn_code),
            timeout=core.Duration.seconds(3),
            reserved_concurrent_executions=1,
            environment={"LOG_LEVEL": "INFO"})

        # Create Custom Loggroup
        # /aws/lambda/function-name
        konstone_lg = _logs.LogGroup(
            self,
            "konstoneLoggroup",
            log_group_name=f"/aws/lambda/{konstone_fn.function_name}",
            removal_policy=core.RemovalPolicy.DESTROY)
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id)

        with open("crd_function/crd.py") as fp:
            code_body = fp.read()

        crd_lambda = lambda_.SingletonFunction(
            self, "Singleton",
            uuid=str(uuid4()),
            code=lambda_.InlineCode(code_body),
            handler="index.lambda_handler",
            timeout=core.Duration.seconds(300),
            runtime=lambda_.Runtime.PYTHON_3_7,
        )
        crd_lambda.add_to_role_policy(
            statement=iam.PolicyStatement(
                actions=["inspector:SubscribeToEvent"],
                resources=["*"]
            )
        )

        resource = cfn.CustomResource(
            self, "Resource",
            provider=cfn.CustomResourceProvider.lambda_(handler=crd_lambda),
            properties=kwargs,
        )

        self.response = resource.get_att("Response").to_string()
Exemplo n.º 3
0
 def __init__(self, scope: core.Construct, lambda_name: str, source_topic: aws_sns.Topic = None, table_name : str = 'S3Table'):
     
     super().__init__(scope = scope, id=lambda_name, code = aws_lambda.InlineCode(open('serverless/lambdas/lambda_snstarget.py', encoding="utf-8").read()), handler= 'index.handler', timeout = core.Duration.seconds(30), runtime = aws_lambda.Runtime.PYTHON_3_7, environment = {'TABLENAME':table_name})
     self.add_to_role_policy(aws_iam.PolicyStatement(actions=['dynamodb:*'], effect = aws_iam.Effect.ALLOW, resources = ['*']))
     if source_topic is not None:
         sns_source = aws_lambda_event_sources.SnsEventSource(source_topic)
         sns_source.bind(self)
Exemplo n.º 4
0
    def __init__(self, scope: core.Construct, id: str, ** kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # Create Serverless Event Processor using Lambda):

        # Read Lambda Code
        try:
            with open("serverless_stacks/lambda_src/konstone_processor.py", mode="r") as f:
                konstone_fn_code = f.read()
        except OSError:
            print("Unable to read Lambda Function Code")

        # never sets IAM role, CDK sets up one with minimum 
        konstone_fn = _lambda.Function(self,
                                       "konstoneFunction",
                                       function_name="konstone_function",
                                       runtime=_lambda.Runtime.PYTHON_3_7,
                                       handler="index.lambda_handler",
                                       code=_lambda.InlineCode(
                                           konstone_fn_code),
                                       timeout=core.Duration.seconds(3),
                                       reserved_concurrent_executions=1, # only 1 runs at a time
                                       environment={
                                           "LOG_LEVEL": "INFO"
                                       }
                                       )
Exemplo n.º 5
0
    def __init__(self, scope: core.Construct, id: str, Description: str,
                 Uuid: str, **kwargs) -> None:
        super().__init__(scope, id)

        with open(kwargs["HandlerPath"], encoding="utf-8") as fp:
            code_body = fp.read()

        resource = cfn.CustomResource(
            self,
            "Resource",
            provider=cfn.CustomResourceProvider.lambda_(
                lambda_.SingletonFunction(
                    self,
                    "Singleton",
                    description=Description,
                    uuid=Uuid,
                    code=lambda_.InlineCode(code_body),
                    handler="index.main",
                    timeout=core.Duration.seconds(300),
                    runtime=lambda_.Runtime.PYTHON_3_7,
                    initial_policy=kwargs["ResourcePolicies"],
                    log_retention=logs.RetentionDays.ONE_DAY,
                )),
            properties=kwargs,
        )
        # response
        self.response = resource.get_att("Response")
Exemplo n.º 6
0
    def __init__(self, app: core.App, id: str) -> None:
        super().__init__(app, id)

        with open("lambda-handler.py", encoding="utf8") as fp:
            handler_code = fp.read()

        lambdaFn = lambda_.Function(
            self,
            "callsmlambda",
            code=lambda_.InlineCode(handler_code),
            handler="index.lambda_handler",
            timeout=core.Duration.seconds(300),
            runtime=lambda_.Runtime.PYTHON_3_7,
            environment={
                "endpoint_name":
                endpoint_name,  # CHANGE TO YOUR ENDPOINT NAME!!
                "content_type": "text/csv"
            })

        lambdaFn.add_to_role_policy(
            aws_iam.PolicyStatement(
                actions=[
                    'sagemaker:InvokeEndpoint',
                ],
                resources=[
                    'arn:aws:sagemaker:{}:{}:endpoint/{}'.format(
                        my_region, my_acc_id, endpoint_name),
                ]))

        api = apig_.LambdaRestApi(self,
                                  "callsmapi",
                                  proxy=True,
                                  handler=lambdaFn)
        print(api)
Exemplo n.º 7
0
    def __init__(self, scope: core.Construct, construct_id: str,
                 **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        #import function code
        try:
            with open("serverless_stack/functions/function.py",
                      mode="r") as file:
                function_body = file.read()
        except OSError:
            print('File can not read')

        function_01 = aws_lambda.Function(
            self,
            "lambdafunction01",
            function_name="LambdaTestCDK",
            runtime=aws_lambda.Runtime.PYTHON_3_6,
            handler="index.lambda_handler",
            code=aws_lambda.InlineCode(function_body),
            timeout=core.Duration.seconds(5),
            reserved_concurrent_executions=1,
            environment={'LOG_LEVEL': 'INFO'})

        #attached cloudwatch log group
        log_group01 = aws_logs.LogGroup(
            self,
            "cloudwatchlog01",
            log_group_name=f"/aws/lambda/{function_01.function_name}",
            removal_policy=core.RemovalPolicy.DESTROY)
    def __init__(self, app: cdk.App, id: str, **kwargs) -> None:
        super().__init__(app, id)

        table_name = 'RandomWriterTable'

        with open("lambda-handler.py", encoding="utf8") as fp:
            handler_code = fp.read()

        lambda_fn = lambda_.Function(
            self,
            "RandomWriter",
            code=lambda_.InlineCode(handler_code),
            handler="index.main",
            timeout=300,
            runtime=lambda_.Runtime.PYTHON37,
            environment={'TABLE_NAME': table_name},
        )
        # Add our 'Every Minute' scheduling rule for this Lambda (via a CloudWatch scheduled Role)
        rule = events.Rule(self,
                           "Rule",
                           schedule_expression="cron(* * * * ? *)")
        rule.add_target(targets.LambdaFunction(lambda_fn))
        # Build our DynamoDb Table
        dynamodb = Table(self,
                         table_name,
                         table_name=table_name,
                         partition_key={
                             'name': 'ID',
                             'type': AttributeType.String
                         },
                         billing_mode=BillingMode.PayPerRequest)
        dynamodb.grant_full_access(lambda_fn)
Exemplo n.º 9
0
    def __init__(self, app: App, id: str) -> None:
        super().__init__(app, id)

        with open("lambda-handler.py", encoding="utf8") as fp:
            handler_code = fp.read()

        # Creates reference to already existing kinesis stream
        kinesis_stream = kinesis.Stream.from_stream_arn(
            self, 'KinesisStream',
            Arn.format(
                ArnComponents(resource='stream',
                              service='kinesis',
                              resource_name='my-stream'), self))

        lambdaFn = lambda_.Function(self,
                                    'Singleton',
                                    handler='index.main',
                                    code=lambda_.InlineCode(handler_code),
                                    runtime=lambda_.Runtime.PYTHON_3_7,
                                    timeout=Duration.seconds(300))

        # Update Lambda Permissions To Use Stream
        kinesis_stream.grant_read(lambdaFn)

        # Create New Kinesis Event Source
        kinesis_event_source = event_sources.KinesisEventSource(
            stream=kinesis_stream,
            starting_position=lambda_.StartingPosition.LATEST,
            batch_size=1)

        # Attach New Event Source To Lambda
        lambdaFn.add_event_source(kinesis_event_source)
Exemplo n.º 10
0
    def __init__(self, scope: cdk.Construct, id: str, **kwargs) -> None:
        super().__init__(
            scope,
            id,
        )

        with open("custom-resource-handler.py", encoding="utf-8") as fp:
            code_body = fp.read()

        resource = cfn.CustomResource(
            self,
            "Resource",
            provider=cfn.CustomResourceProvider.lambda_(
                lambda_.SingletonFunction(
                    self,
                    "Singleton",
                    uuid="f7d4f730-4ee1-11e8-9c2d-fa7ae01bbebc",
                    code=lambda_.InlineCode(code_body),
                    handler="index.main",
                    timeout=300,
                    runtime=lambda_.Runtime.PYTHON27,
                )),
            properties=kwargs,
        )

        self.response = resource.get_att("Response").to_string()
Exemplo n.º 11
0
    def __init__(self,
                 scope: core.Construct,
                 id: str,
                 idp_name: str,
                 idp_url: str,
                 *,
                 cfn_lambda: str = None,
                 cfn_resources_path: str = None,
                 debug=False):
        """Create an IAM SAML Identity Provider

        Args:
            scope (core.Construct): [description]
            id (str): [description]
            idp_name (str): IAM Idp name
            idp_url (str): Your SAML Identity provider URL
        """
        rdir = sys.prefix + '/share/aviv-cdk/iam-idp/'
        if not cfn_lambda:
            p = os.path.dirname(os.path.dirname(__file__))
            cfn_lambda = p + '/lambdas/iam_idp/saml.py'
        lambda_attrs = dict(code=aws_lambda.InlineCode(
            CDKLambda._code_inline(cfn_lambda)),
                            handler='index.handler',
                            timeout=core.Duration.seconds(20),
                            runtime=aws_lambda.Runtime.PYTHON_3_7)
        if not cfn_resources_path:
            cfn_resources_path = rdir + 'artifacts-cfn_resources.zip'
        layer_attrs = dict(description='cfn_resources layer for idp',
                           code=aws_lambda.AssetCode(cfn_resources_path))
        super().__init__(scope,
                         id,
                         lambda_attrs=lambda_attrs,
                         layer_attrs=layer_attrs,
                         remote_account_grant=False)

        # Add required policies for the lambda to create an IAM idp
        self._lambda.add_to_role_policy(
            iam.PolicyStatement(actions=[
                'iam:CreateSAMLProvider', 'iam:UpdateSAMLProvider',
                'iam:DeleteSAMLProvider'
            ],
                                effect=iam.Effect.ALLOW,
                                resources=['*']))

        self._idp = cfn.CustomResource(
            self,
            "identityProvider",
            resource_type='Custom::SAMLProvider',
            provider=cfn.CustomResourceProvider.lambda_(self._lambda),
            properties=dict(Name=idp_name, URL=idp_url))
        self.response = self._idp.get_att("Response").to_string()

        # Export
        ssm_name = '/' + id.replace('-', '/')
        ssm.StringParameter(self,
                            'ssm',
                            string_value=self._idp.ref,
                            parameter_name=ssm_name)
        core.CfnOutput(self, 'IAMIdpSAMLArn', value=self._idp.ref)
Exemplo n.º 12
0
    def __init__(self, app: core.App, id: str) -> None:
        super().__init__(app, id)

        with open("lambda-handler.py", encoding="utf8") as fp:
            handler_code = fp.read()

        lambdaFn = lambda_.Function(
            self,
            "Singleton",
            code=lambda_.InlineCode(handler_code),
            handler="index.main",
            timeout=core.Duration.seconds(300),
            runtime=lambda_.Runtime.PYTHON_3_7,
        )

        # Run every day at 6PM UTC
        # See https://docs.aws.amazon.com/lambda/latest/dg/tutorial-scheduled-events-schedule-expressions.html
        rule = events.Rule(
            self,
            "Rule",
            schedule=events.Schedule.cron(minute='0',
                                          hour='18',
                                          month='*',
                                          week_day='MON-FRI',
                                          year='*'),
        )
        rule.add_target(targets.LambdaFunction(lambdaFn))
Exemplo n.º 13
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        for i in ["lambda-handler", "lambda-handler1", "lambda-handler2" ]:

            with open(f"./scripts/{i}.py", encoding="utf8") as fp:
                handler_code = fp.read()
    
            lambda_function = lambda_.Function(
                self, f"MyFun-{i}",
                code=lambda_.InlineCode(handler_code),
                handler="index.main",
                timeout=core.Duration.seconds(300),
                runtime=lambda_.Runtime.PYTHON_3_7,
            )


#alternative way to achieve above functionality
            lambda_function = lambda_.Function(
                self, f"MyFun-{i}",
                code=lambda_.Code.asset("scripts"),,
                handler=f"{i}.main",
                timeout=core.Duration.seconds(300),
                runtime=lambda_.Runtime.PYTHON_3_7,
            )
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id)

        with open("custom_resource/random_string_generator_lambda_function.py", encoding="utf-8") as fp:
            code_body = fp.read()


        # Use `uuidgen` in bash to generate new ones
        random_string_generator_fn=lambda_.SingletonFunction(
            self, "Singleton",
            uuid="RANDOMF2-F7DB-4561-B7AC-4C9730D10E95",
            code=lambda_.InlineCode(code_body),
            handler="index.lambda_handler",
            timeout=core.Duration.seconds(300),
            runtime=lambda_.Runtime.PYTHON_3_7,
        )


        resource = cfn.CustomResource(
            self, "Resource",
            provider=cfn.CustomResourceProvider.lambda_(
                random_string_generator_fn
            ),
            properties=kwargs,
        )

        self.response = resource.get_att("Response").to_string()
Exemplo n.º 15
0
    def create_lambda_function(self,
                               boto3_lambda_layer,
                               source_path,
                               identifier,
                               is_inline,
                               environment={}):
        lambda_function = None
        lambda_code = None
        lambda_handler = None
        if is_inline:
            with open(f"{source_path}/app.py", encoding="utf8") as fp:
                handler_code = fp.read()
                lambda_code = aws_lambda.InlineCode(handler_code)
                lambda_handler = "index.handler"
        else:
            lambda_code = aws_lambda.AssetCode(source_path)
            lambda_handler = "app.handler"

        lambda_function = aws_lambda.Function(
            self,
            identifier,
            runtime=aws_lambda.Runtime.PYTHON_3_8,
            handler=lambda_handler,
            code=lambda_code,
            environment=environment,
        )
        if boto3_lambda_layer:
            lambda_function.add_layers(boto3_lambda_layer)
        return lambda_function
Exemplo n.º 16
0
    def __init__(self, app: App, id: str) -> None:
        super().__init__(app, id)

        # Lambda Function
        with open("lambda-handler.py", encoding="utf8") as fp:
            handler_code = fp.read()

        lambdaFn = lambda_.Function(
            self, "Singleton",
            code=lambda_.InlineCode(handler_code),
            handler="index.main",
            timeout=Duration.seconds(10),
            runtime=lambda_.Runtime.PYTHON_3_9,
        )

        # Set Lambda Logs Retention and Removal Policy
        logs.LogGroup(
            self,
            'logs',
            log_group_name = f"/aws/lambda/{lambdaFn.function_name}",
            removal_policy = RemovalPolicy.DESTROY,
            retention = logs.RetentionDays.ONE_DAY
        )

        # EventBridge Rule
        rule = events.Rule(
            self, "Rule",
        )
        rule.add_event_pattern(
            source=["cdk.myApp"],
            detail_type=["transaction"]
        )
        rule.add_target(targets.LambdaFunction(lambdaFn))
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id)

        # Read Lambda Code:)
        try:
            with open(
                    "waf_stacks/custom_resources/waf_rate_rule_creator/lambda_src/index.py",
                    encoding="utf-8",
                    mode="r") as f:
                waf_rate_rule_creator_fn_code = f.read()
        except OSError:
            print("Unable to read Lambda Function Code")
            raise

        # Create IAM Permission Statements that are required by the Lambda

        role_stmt1 = _iam.PolicyStatement(
            effect=_iam.Effect.ALLOW,
            resources=["*"],
            actions=["wafv2:GetWebACL", "wafv2:UpdateWebACL"])
        role_stmt1.sid = "AllowLambdaToCreateWafRules"

        waf_rate_rule_creator_fn = _lambda.SingletonFunction(
            self,
            "waFRateRuleCreatorSingleton",
            uuid="mystique30-4ee1-11e8-9c2d-fa7ae01bbebc",
            code=_lambda.InlineCode(waf_rate_rule_creator_fn_code),
            handler="index.lambda_handler",
            timeout=core.Duration.seconds(10),
            runtime=_lambda.Runtime.PYTHON_3_7,
            reserved_concurrent_executions=1,
            environment={
                "LOG_LEVEL": "INFO",
                "APP_ENV": "Production"
            },
            description="Creates a rate based WAF rule")

        waf_rate_rule_creator_fn.add_to_role_policy(role_stmt1)

        # Create Custom Log group
        waf_rate_rule_creator_fn_lg = _logs.LogGroup(
            self,
            "wafRateRuleCreatorLogGroup",
            log_group_name=
            f"/aws/lambda/{waf_rate_rule_creator_fn.function_name}",
            retention=_logs.RetentionDays.ONE_WEEK,
            removal_policy=core.RemovalPolicy.DESTROY)

        waf_rate_rule_creator = cfn.CustomResource(
            self,
            "wafRateRuleCreatorCustomResource",
            provider=cfn.CustomResourceProvider.lambda_(
                waf_rate_rule_creator_fn),
            properties=kwargs,
        )

        self.response = waf_rate_rule_creator.get_att(
            "rule_add_status").to_string()
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # Add your stack resources below):
        # Create an S3 Bucket for storing our web store assets
        kk_store = _s3.Bucket(self, "kkStore", versioned=True)

        # DynamoDB Table
        kk_store_assets_table = _dynamodb.Table(
            self,
            "kkStoreAssetsDDBTable",
            table_name="kk_store_assets_tables",
            partition_key=_dynamodb.Attribute(
                name="_id", type=_dynamodb.AttributeType.STRING),
            removal_policy=core.RemovalPolicy.DESTROY)

        # Read Lambda Code
        try:
            with open("advanced_use_cases/lambda_src/s3_event_processor.py",
                      mode="r") as f:
                kk_store_processor_fn_code = f.read()
        except OSError:
            print("Unable to read Lambda Function Code")

        # Deploy the lambda function
        kk_store_processor_fn = _lambda.Function(
            self,
            "kkStoreProcessorFn",
            function_name="kk_store_processor_fn",
            description="Process store events and update DDB",
            runtime=_lambda.Runtime.PYTHON_3_7,
            handler="index.lambda_handler",
            code=_lambda.InlineCode(kk_store_processor_fn_code),
            timeout=core.Duration.seconds(3),
            reserved_concurrent_executions=1,
            environment={
                "LOG_LEVEL": "INFO",
                "DDB_TABLE_NAME": f"{kk_store_assets_table.table_name}"
            })

        # Add DynamoDB Write Privileges To Lambda
        kk_store_assets_table.grant_read_write_data(kk_store_processor_fn)

        # Create Custom Loggroup
        kk_store_lg = _logs.LogGroup(
            self,
            "kkStoreLogGroup",
            log_group_name=f"/aws/lambda/{kk_store_processor_fn.function_name}",
            removal_policy=core.RemovalPolicy.DESTROY,
            retention=_logs.RetentionDays.ONE_DAY)

        # Create s3 notification for lambda function
        kk_store_backend = _s3_notifications.LambdaDestination(
            kk_store_processor_fn)

        # Assign notification for the s3 event type (ex: OBJECT_CREATED)
        kk_store.add_event_notification(_s3.EventType.OBJECT_CREATED,
                                        kk_store_backend)
Exemplo n.º 19
0
    def __init__(self, app: core.App, id: str) -> None:
        super().__init__(app, id)

        second_lambda_name = core.CfnParameter(self,
                                               "SecondLambdaName",
                                               type="String")

        second_lambda_Role_name = second_lambda_name.value_as_string + 'Role'
        second_lambda_Rule_name = second_lambda_name.value_as_string + 'Rule'

        iamRole = aws_iam.Role(
            self,
            "twoone",
            role_name=second_lambda_Role_name,
            assumed_by=aws_iam.ServicePrincipal("lambda.amazonaws.com"))

        iamRole.add_to_policy(
            aws_iam.PolicyStatement(effect=aws_iam.Effect.ALLOW,
                                    actions=[
                                        "logs:CreateLogGroup",
                                        "logs:CreateLogStream",
                                        "logs:PutLogEvents", "cloudwatch:*",
                                        "dynamodb:*", "s3:*"
                                    ],
                                    resources=["*"]))

        with open("files/lambdafiles/lambda-handler2.py",
                  encoding="utf8") as fp:
            handler_code = fp.read()

        lambdaFunction = lambda_.Function(
            self,
            "twotwo",
            function_name=second_lambda_name.value_as_string,
            code=lambda_.InlineCode(handler_code),
            handler="index.main",
            timeout=core.Duration.seconds(300),
            runtime=lambda_.Runtime.PYTHON_3_7,
            role=iamRole)

        rule = events.Rule(
            self,
            "twothree",
            rule_name=second_lambda_Rule_name,
            schedule=events.Schedule.cron(minute='0/5',
                                          hour='*',
                                          month='*',
                                          week_day='MON-FRI',
                                          year='*'),
        )

        rule.add_target(targets.LambdaFunction(lambdaFunction))

        core.CfnOutput(self,
                       "_SecondLambdaName",
                       value=lambdaFunction.function_name)
Exemplo n.º 20
0
    def __init__(self, app: core.App, id: str) -> None:
        super().__init__(app, id)

        with open("lambda-handler.py", encoding="utf8") as fp:
            handler_code = fp.read()

        lambdaFn = lambda_.Function(
            self,
            "Singleton",
            code=lambda_.InlineCode(handler_code),
            handler="index.lambda_handler",
            timeout=core.Duration.seconds(300),
            runtime=lambda_.Runtime.PYTHON_3_7,
            environment={
                "endpoint_name":
                endpoint_name,  # CHANGE TO YOUR ENDPOINT NAME!!
                "content_type": "text/csv",
                "input_data": input_data,
                "bucket": bucket,
                "key": key
            })

        # Add sagemaker role
        lambdaFn.add_to_role_policy(
            aws_iam.PolicyStatement(
                actions=[
                    'sagemaker:InvokeEndpoint',
                ],
                resources=[
                    'arn:aws:sagemaker:{}:{}:endpoint/{}'.format(
                        my_region, my_acc_id, endpoint_name),
                ]))

        #Add s3 role
        lambdaFn.add_to_role_policy(
            aws_iam.PolicyStatement(actions=[
                's3:GetObject',
            ],
                                    resources=[
                                        'arn:aws:s3:::{}'.format(bucket),
                                    ]))

        # Run every day at 6PM UTC
        # See https://docs.aws.amazon.com/lambda/latest/dg/tutorial-scheduled-events-schedule-expressions.html
        rule = events.Rule(
            self,
            "Rule",
            schedule=events.Schedule.cron(minute='0',
                                          hour='18',
                                          month='*',
                                          week_day='MON-FRI',
                                          year='*'),
        )
        rule.add_target(targets.LambdaFunction(lambdaFn))
Exemplo n.º 21
0
    def __init__(self, app: cdk.App, id: str, **kwargs) -> None:
        super().__init__(app, id)

        with open('lambda_handler.py', encoding="utf8") as fp:
            handler_code = fp.read()

            lambdaFn = lambda_.Function(self,
                                        "InlineLambda",
                                        code=lambda_.InlineCode(handler_code),
                                        handler="index.main",
                                        timeout=300,
                                        runtime=lambda_.Runtime.PYTHON37)
 def __init__(self, scope: core.Construct, id, handler, function_name,
              memory_size):
     super().__init__(
         scope=scope,
         id=id,
         code=aws_lambda.InlineCode(
             open('serverlessbackend\libs\dummy_lambda\lambda_handler.py',
                  encoding="utf-8").read()),
         handler=handler,
         runtime=aws_lambda.Runtime.PYTHON_3_7,
         function_name=function_name,
         memory_size=memory_size)
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        my_main_func = lambda_.Function(
            self,
            "myMainFunction",
            code=lambda_.InlineCode("def main(event, context)\n  print('hello, world')"),
            handler='index.main',
            runtime=lambda_.Runtime.PYTHON_3_7
        )
        
        # We assign the function's arn to a local variable for the Object.
        self._function_arn = my_main_func.function_arn
Exemplo n.º 24
0
    def __init__(self, app: core.App, id: str, **kwargs) -> None:
        super().__init__(app, id)

        with open('aws_cdk_python/Zach_Lambda_Stack/lambda_handler.py',
                  encoding="utf8") as fp:
            handler_code = fp.read()

            lambdaFn = lambda_.Function(self,
                                        "InlineLambda",
                                        code=lambda_.InlineCode(handler_code),
                                        handler="index.main",
                                        timeout=core.Duration.seconds(2),
                                        runtime=lambda_.Runtime.PYTHON_3_7)
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id)

        with open("custom_resource/iam_user_tagger_lambda_function.py",
                  encoding="utf-8") as fp:
            code_body = fp.read()

        statement = iam.PolicyStatement()
        # https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html
        statement.add_actions("iam:TagUser")
        statement.add_actions("iam:UntagUser")
        statement.add_all_resources()
        statement.effect = iam.Effect.ALLOW

        iam_tagger_fn = lambda_.SingletonFunction(
            self,
            "Singleton",
            uuid="tagger30-4ee1-11e8-9c2d-fa7ae01bbebc",
            code=lambda_.InlineCode(code_body),
            handler="index.lambda_handler",
            timeout=core.Duration.seconds(300),
            runtime=lambda_.Runtime.PYTHON_3_7,
        )

        iam_tagger_fn.add_to_role_policy(statement)
        """ 
        resource = cfn.CustomResource(
            self, "Resource",
            provider=cfn.CustomResourceProvider.lambda_(
                lambda_.SingletonFunction(
                    self, "Singleton",
                    uuid="f7d4f730-4ee1-11e8-9c2d-fa7ae01bbebc",
                    code=lambda_.InlineCode(code_body),
                    handler="index.main",
                    timeout=core.Duration.seconds(300),
                    runtime=lambda_.Runtime.PYTHON_3_7,
                )
            ),
            properties=kwargs,
        )
        """

        resource = cfn.CustomResource(
            self,
            "Resource",
            provider=cfn.CustomResourceProvider.lambda_(iam_tagger_fn),
            properties=kwargs,
        )

        self.response = resource.get_att("Response").to_string()
Exemplo n.º 26
0
    def __init__(self, scope: core.Construct, construct_id: str,
                 **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        #import function code
        try:
            with open("serverless_stack/functions/function.py",
                      mode="r") as file:
                function_body = file.read()
        except OSError:
            print('File can not read')

        function_01 = aws_lambda.Function(
            self,
            "lambdafunction01",
            function_name="LambdaTestCDK",
            runtime=aws_lambda.Runtime.PYTHON_3_6,
            handler="index.lambda_handler",
            code=aws_lambda.InlineCode(function_body),
            timeout=core.Duration.seconds(5),
            reserved_concurrent_executions=1,
            environment={'LOG_LEVEL': 'INFO'})

        #attached cloudwatch log group
        log_group01 = aws_logs.LogGroup(
            self,
            "cloudwatchlog01",
            log_group_name=f"/aws/lambda/{function_01.function_name}",
            removal_policy=core.RemovalPolicy.DESTROY)

        #cloudwatch event trigger on 6am
        cron_01 = aws_events.Rule(self,
                                  "cron01",
                                  schedule=aws_events.Schedule.cron(
                                      minute="0",
                                      hour="6",
                                      month="*",
                                      week_day="MON-FRI",
                                      year="*"))

        #cloudwatch event trigger every 5min
        cron_02 = aws_events.Rule(self,
                                  "cron02",
                                  schedule=aws_events.Schedule.rate(
                                      core.Duration.minutes(5)))

        #add triggers to lambda
        cron_01.add_target(aws_events_targets.LambdaFunction(function_01))
        cron_02.add_target(aws_events_targets.LambdaFunction(function_01))
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # Create Serverless Event Processor using Lambda):

        # Read Lambda Code
        try:
            with open("serverless_stacks/lambda_src/konstone_processor.py",
                      mode="r") as f:
                konstone_fn_code = f.read()
        except OSError:
            print("Unable to read Lambda Function Code")

        # Simple Lambda Function to return event
        konstone_fn = _lambda.Function(
            self,
            "konstoneFunction",
            function_name="konstone_function",
            runtime=_lambda.Runtime.PYTHON_3_7,
            handler="index.lambda_handler",
            code=_lambda.InlineCode(konstone_fn_code),
            timeout=core.Duration.seconds(3),
            reserved_concurrent_executions=1,
            environment={
                "LOG_LEVEL": "INFO",
                "AUTOMATION": "SKON"
            })

        # Run Every day at 18:00 UTC
        # schedule deletion or moving of maps from one storage system to another like glacier after 2 months
        six_pm_cron = _events.Rule(self,
                                   "sixPmRule",
                                   schedule=_events.Schedule.cron(
                                       minute="0",
                                       hour="18",
                                       month="*",
                                       week_day="MON-FRI",
                                       year="*"))

        # Setup Cron Based on Rate
        # Run Every 3 Minutes
        run_every_3_minutes = _events.Rule(self,
                                           "runEvery3Minutes",
                                           schedule=_events.Schedule.rate(
                                               core.Duration.minutes(3)))

        # Add Lambda to Cloudwatch Event Trigger Rule with permissions
        six_pm_cron.add_target(_targets.LambdaFunction(konstone_fn))
        run_every_3_minutes.add_target(_targets.LambdaFunction(konstone_fn))
Exemplo n.º 28
0
    def __init__(self, app: cdk.App, id: str) -> None:
        """Create SampleStack."""
        super().__init__(app, id)

        with open('lambda-index.py', encoding='utf8') as stream:
            handler_code = stream.read()

        lambdaFn = aws_lambda.Function(
            self,
            'MyFunction',
            code=aws_lambda.InlineCode(handler_code),
            handler='index.main',
            timeout=300,
            runtime=aws_lambda.Runtime.PYTHON37,
        )
Exemplo n.º 29
0
    def __init__(self, app: core.App, id: str) -> None:
        super().__init__(app, id)

        with open("lambda-handler.py", encoding="utf8") as fp:
            handler_code = fp.read()

        Kstream = kinesis_.Stream(self,
                                  "KinesisSagemakerInference",
                                  encryption=None,
                                  encryption_key=None,
                                  retention_period_hours=24,
                                  shard_count=1)

        lambdaFn = lambda_.Function(
            self,
            "KinesisSMLambda",
            code=lambda_.InlineCode(handler_code),
            handler="index.lambda_handler",
            timeout=core.Duration.seconds(300),
            runtime=lambda_.Runtime.PYTHON_3_7,
            environment={
                "endpoint_name":
                endpoint_name,  # CHANGE TO YOUR ENDPOINT NAME!!
                "content_type": "text/csv",
                "input_data": input_data,
                "bucket": bucket,
                "key": key
            })

        lambdaFn.add_to_role_policy(
            aws_iam.PolicyStatement(
                actions=[
                    'sagemaker:InvokeEndpoint',
                ],
                resources=[
                    'arn:aws:sagemaker:{}:{}:endpoint/{}'.format(
                        my_region, my_acc_id, endpoint_name),
                ]))

        # Add the Kinesis stream as Lambda source
        lambdaFn.add_event_source(
            aws_lambda_event_sources.KinesisEventSource(
                Kstream, starting_position=lambda_.StartingPosition.LATEST))

        # Add stream read permissions
        Kstream.grant_read(lambdaFn.role)
Exemplo n.º 30
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # Create Serverless Event Processor using Lambda):
        # Read Lambda Code
        try:
            with open("serverless_stacks/lambda_src/konstone_hello_world.py",
                      mode="r") as f:
                konstone_fn_code = f.read()
        except OSError:
            print("Unable to read Lambda Function Code")

        konstone_fn = _lambda.Function(
            self,
            "konstoneFunction",
            function_name="konstone_function",
            runtime=_lambda.Runtime.PYTHON_3_7,
            handler="index.lambda_handler",
            code=_lambda.InlineCode(konstone_fn_code),
            timeout=core.Duration.seconds(3),
            reserved_concurrent_executions=1,
            environment={
                "LOG_LEVEL": "INFO",
                "Environment": "Production"
            })

        # Create Custom Loggroup
        # /aws/lambda/function-name
        konstone_lg = _logs.LogGroup(
            self,
            "konstoneLoggroup",
            log_group_name=f"/aws/lambda/{konstone_fn.function_name}",
            retention=_logs.RetentionDays.ONE_WEEK,
            removal_policy=core.RemovalPolicy.DESTROY)

        # Add API GW front end for the Lambda
        konstone_fn_integration = _apigw.LambdaRestApi(self,
                                                       "konstoneApiEndpoint",
                                                       handler=konstone_fn)

        output_1 = core.CfnOutput(
            self,
            "ApiUrl",
            value=f"{konstone_fn_integration.url}",
            description="Use a browser to access this url")