// Defines a new lambda resource
        public CdkWorkshopStack(Construct parent, string id, IStackProps props = null) : base(parent, id, props)
        {
            var hello = new Function(this, "HelloHandler", new FunctionProps
            {
                Runtime = Runtime.NODEJS_10_X,
                Code    = Code.FromAsset("lambda"),
                Handler = "hello.handler"
            });

            var helloWithCounter = new HitCounter(this, "HelloHitCounter", new HitCounterProps
            {
                Downstream = hello
            });

            var gateway = new LambdaRestApi(this, "Endpoint", new LambdaRestApiProps
            {
                Handler = helloWithCounter.Handler
            });

            var tv = new TableViewer(this, "ViewerHitCount", new TableViewerProps
            {
                Title = "Hello Hits",
                Table = helloWithCounter.MyTable
            });

            this.HCViewerUrl = new CfnOutput(this, "TableViewerUrl", new CfnOutputProps
            {
                Value = gateway.Url
            });

            this.HCEndpoint = new CfnOutput(this, "GatewayUrl", new CfnOutputProps
            {
                Value = gateway.Url
            });
        }
Exemplo n.º 2
0
        public DotNetLambdaWithApiGetway(Stack scope, string id, DotNetLambdaWithApiGetwayProps props) : base(scope, id)
        {
            // domain and certificate have been created manually on AWS Console for security purposes

            var snsTopic = new Topic(this, "WorkSplitRequest", new TopicProps()
            {
                TopicName   = "work-split-request",
                DisplayName = "Work Split Request"
            });

            snsTopic.AddSubscription(new EmailSubscription("*****@*****.**", new EmailSubscriptionProps()));

            var queue = new Queue(this, "QueueProcessor", new QueueProps()
            {
                RetentionPeriod = Duration.Days(2)
            });

            snsTopic.AddSubscription(new SqsSubscription(queue));

            var dotnetWebApiLambda = new Function(this, "WebLambda", new FunctionProps
            {
                Runtime = Runtime.DOTNET_CORE_3_1,
                Code    = props.Code,
                Handler = "Web::Web.LambdaEntryPoint::FunctionHandlerAsync"
            });

            dotnetWebApiLambda.AddEnvironment("Region", scope.Region);
            dotnetWebApiLambda.AddEnvironment("SnsTopic", snsTopic.TopicArn);
            snsTopic.GrantPublish(dotnetWebApiLambda);

            var fullDomain = $"{props.SiteSubDomain}.{props.DomainName}";

            var apiGetway = new LambdaRestApi(this, fullDomain, new LambdaRestApiProps()
            {
                Handler = dotnetWebApiLambda
            });

            var apiDomain = apiGetway.AddDomainName("customDomain", new DomainNameOptions()
            {
                DomainName     = fullDomain,
                Certificate    = props.Certificate,
                SecurityPolicy = SecurityPolicy.TLS_1_2,
                EndpointType   = EndpointType.EDGE
            });

            new ARecord(this, "ApiGateway-ARecord", new ARecordProps()
            {
                Zone       = props.Zone,
                RecordName = fullDomain,
                Target     = RecordTarget.FromAlias(new ApiGateway(apiGetway)),
            });


            scope.Log($"ApiGateway Url {id}", apiGetway.Url);
            scope.Log($"ApiGateway public domain {id}", apiDomain.DomainNameAliasDomainName);
        }
Exemplo n.º 3
0
        protected override RestApi Build(Construct scope)
        {
            if (_binaryMediaTypes.Any())
            {
                _props.BinaryMediaTypes = _binaryMediaTypes.ToArray();
            }

            if (_handler != null)
            {
                _props.Handler = _handler.GetInstance(scope);
            }

            var result = new LambdaRestApi(scope, _name, _props);

            return(result);
        }
Exemplo n.º 4
0
        internal Example3Stack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            var functionHandler = new Function(this, "LambdaHandler", new FunctionProps
            {
                Runtime = Runtime.DOTNET_CORE_3_1,
                Code    = Code.FromAsset("./LambdaFunction/bin/Release/netcoreapp3.1/publish"),
                Handler = "LambdaFunction::LambdaFunction.Function::Handler",
                Tracing = Tracing.ACTIVE
            });

            var restApi = new LambdaRestApi(this, "TestApi", new LambdaRestApiProps
            {
                Handler     = functionHandler,
                RestApiName = "TestApi"
            });
        }
        public CdkMissingLibInfraStack(Construct parent, string id, IStackProps props) : base(parent, id, props)
        {
            var lambdaFunction = new Function(this, "webapi-function",
                                              new FunctionProps
            {
                Code       = Code.FromAsset(@"C:\Users\joanv\Source\Repos\CdkMissingLib\CdkMissingLib\bin\Debug\netcoreapp2.1"),
                Handler    = "CdkMissingLib::CdkMissingLib.LambdaEntryPoint::FunctionHandlerAsync",
                Runtime    = Runtime.DOTNET_CORE_2_1,
                Timeout    = Duration.Seconds(30),
                MemorySize = 128
            }
                                              );

            var api = new LambdaRestApi(this, "webapi-function-api", new LambdaRestApiProps
            {
                Handler = lambdaFunction
            });
        }
        public XRayStack(Construct parent, string id) : base(parent, id)
        {
            var table = new Table(this, "Table", new TableProps()
            {
                TableName    = "MysfitsQuestionsTable",
                PartitionKey = new Attribute
                {
                    Name = "QuestionId",
                    Type = AttributeType.STRING
                },
                Stream = StreamViewType.NEW_IMAGE
            });

            var postQuestionLambdaFunctionPolicyStmDDB = new PolicyStatement();

            postQuestionLambdaFunctionPolicyStmDDB.AddActions("dynamodb:PutItem");
            postQuestionLambdaFunctionPolicyStmDDB.AddResources(table.TableArn);

            var LambdaFunctionPolicyStmXRay = new PolicyStatement();

            LambdaFunctionPolicyStmXRay.AddActions(
                //  Allows the Lambda function to interact with X-Ray
                "xray:PutTraceSegments",
                "xray:PutTelemetryRecords",
                "xray:GetSamplingRules",
                "xray:GetSamplingTargets",
                "xray:GetSamplingStatisticSummaries"
                );
            LambdaFunctionPolicyStmXRay.AddAllResources();

            var mysfitsPostQuestion = new Function(this, "PostQuestionFunction", new FunctionProps
            {
                Handler     = "mysfitsPostQuestion.postQuestion",
                Runtime     = Runtime.PYTHON_3_6,
                Description =
                    "A microservice Lambda function that receives a new question submitted to the MythicalMysfits website from a user and inserts it into a DynamoDB database table.",
                MemorySize    = 128,
                Code          = Code.FromAsset("../../lambda-questions/PostQuestionsService"),
                Timeout       = Duration.Seconds(30),
                InitialPolicy = new[]
                {
                    postQuestionLambdaFunctionPolicyStmDDB,
                    LambdaFunctionPolicyStmXRay
                },
                Tracing = Tracing.ACTIVE
            });

            var topic = new Topic(this, "Topic", new TopicProps
            {
                DisplayName = "MythicalMysfitsQuestionsTopic",
                TopicName   = "MythicalMysfitsQuestionsTopic"
            });

            topic.AddSubscription(new EmailSubscription("REPLACE@EMAIL_ADDRESS"));

            var postQuestionLambdaFunctionPolicyStmSNS = new PolicyStatement();

            postQuestionLambdaFunctionPolicyStmSNS.AddActions("sns:Publish");
            postQuestionLambdaFunctionPolicyStmSNS.AddResources(topic.TopicArn);

            var mysfitsProcessQuestionStream = new Function(this, "ProcessQuestionStreamFunction", new FunctionProps
            {
                Handler     = "mysfitsProcessStream.processStream",
                Runtime     = Runtime.PYTHON_3_6,
                Description =
                    "An AWS Lambda function that will process all new questions posted to mythical mysfits" +
                    " and notify the site administrator of the question that was asked.",
                MemorySize    = 128,
                Code          = Code.FromAsset("../../lambda-questions/ProcessQuestionsStream"),
                Timeout       = Duration.Seconds(30),
                InitialPolicy = new[]
                {
                    postQuestionLambdaFunctionPolicyStmSNS,
                    LambdaFunctionPolicyStmXRay
                },
                Tracing     = Tracing.ACTIVE,
                Environment = new Dictionary <string, string>()
                {
                    { "SNS_TOPIC_ARN", topic.TopicArn }
                },
                Events = new IEventSource[]
                {
                    new DynamoEventSource(table, new DynamoEventSourceProps
                    {
                        StartingPosition = StartingPosition.TRIM_HORIZON,
                        BatchSize        = 1
                    })
                }
            });

            var questionsApiRole = new Role(this, "QuestionsApiRole", new RoleProps
            {
                AssumedBy = new ServicePrincipal("apigateway.amazonaws.com")
            });

            var apiPolicy = new PolicyStatement();

            apiPolicy.AddActions("lambda:InvokeFunction");
            apiPolicy.AddResources(mysfitsPostQuestion.FunctionArn);
            new Policy(this, "QuestionsApiPolicy", new PolicyProps
            {
                PolicyName = "questions_api_policy",
                Statements = new[]
                {
                    apiPolicy
                },
                Roles = new IRole[]
                {
                    questionsApiRole
                }
            });

            var questionsIntegration = new LambdaIntegration(mysfitsPostQuestion, new LambdaIntegrationOptions
            {
                CredentialsRole      = questionsApiRole,
                IntegrationResponses = new IntegrationResponse[]
                {
                    new IntegrationResponse()
                    {
                        StatusCode        = "200",
                        ResponseTemplates = new Dictionary <string, string>
                        {
                            { "application/json", "{\"status\":\"OK\"}" }
                        }
                    }
                }
            });

            var api = new LambdaRestApi(this, "APIEndpoint", new LambdaRestApiProps
            {
                Handler       = mysfitsPostQuestion,
                RestApiName   = "Questions API Service",
                DeployOptions = new StageOptions
                {
                    TracingEnabled = true
                },
                Proxy = false
            });

            var questionsMethod = api.Root.AddResource("questions");

            questionsMethod.AddMethod("POST", questionsIntegration, new MethodOptions
            {
                MethodResponses = new MethodResponse[]
                {
                    new MethodResponse
                    {
                        StatusCode         = "200",
                        ResponseParameters = new Dictionary <string, bool>()
                        {
                            { "method.response.header.Access-Control-Allow-Headers", true },
                            { "method.response.header.Access-Control-Allow-Methods", true },
                            { "method.response.header.Access-Control-Allow-Origin", true },
                        }
                    }
                },
                AuthorizationType = AuthorizationType.NONE
            });

            questionsMethod.AddMethod("OPTIONS", new MockIntegration(new IntegrationOptions
            {
                IntegrationResponses = new IntegrationResponse[]
                {
                    new IntegrationResponse
                    {
                        StatusCode         = "200",
                        ResponseParameters = new Dictionary <string, string>
                        {
                            {
                                "method.response.header.Access-Control-Allow-Headers",
                                "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent'"
                            },
                            { "method.response.header.Access-Control-Allow-Origin", "'*'" },
                            { "method.response.header.Access-Control-Allow-Credentials", "'false'" },
                            { "method.response.header.Access-Control-Allow-Methods", "'OPTIONS,GET,PUT,POST,DELETE'" }
                        }
                    }
                },
                PassthroughBehavior = PassthroughBehavior.NEVER,
                RequestTemplates    = new Dictionary <string, string>
                {
                    { "application/json", "{\"statusCode\": 200}" }
                }
            }),
                                      new MethodOptions
            {
                MethodResponses = new MethodResponse[]
                {
                    new MethodResponse
                    {
                        StatusCode         = "200",
                        ResponseParameters = new Dictionary <string, bool>
                        {
                            { "method.response.header.Access-Control-Allow-Headers", true },
                            { "method.response.header.Access-Control-Allow-Methods", true },
                            { "method.response.header.Access-Control-Allow-Credentials", true },
                            { "method.response.header.Access-Control-Allow-Origin", true }
                        }
                    }
                }
            }
                                      );
        }
Exemplo n.º 7
0
        internal AwsServerlessStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            // Create IAM Admin Role
            var iamRole = new Role(this, "Role", new RoleProps {
                RoleName        = "LambdaAdminRole",
                AssumedBy       = new ServicePrincipal("lambda.amazonaws.com"),
                ManagedPolicies = new [] { ManagedPolicy.FromManagedPolicyArn(this, "RolePolicy", "arn:aws:iam::aws:policy/AdministratorAccess") }
            });

            // Create A S3 Bucket
            var s3Bucket = new Bucket(this, "demoS3", new BucketProps {
                BucketName       = "des-inv-app-s3-bckt",
                RemovalPolicy    = RemovalPolicy.DESTROY,
                PublicReadAccess = true,
            });

            // Create A DynamoDB
            var dynamoDBTable = new Table(this, "demoDynamoDB", new TableProps {
                TableName    = "serverless-inventory-app-dynamodb-table",
                PartitionKey = new Attribute {
                    Name = "Store", Type = AttributeType.STRING
                },
                SortKey = new Attribute {
                    Name = "Item", Type = AttributeType.STRING
                },
                BillingMode   = BillingMode.PAY_PER_REQUEST,
                Stream        = StreamViewType.NEW_AND_OLD_IMAGES,
                RemovalPolicy = RemovalPolicy.DESTROY
            });

            // Create Lambda Function for DynamoDB
            var func_DynamoDB = new Function(this, "demoFuncDynamoDB", new FunctionProps {
                Runtime      = Runtime.DOTNET_CORE_3_1,
                FunctionName = "serverless-inventory-app-func-dynamodb",
                Code         = Code.FromAsset("publish_lambda/func_DynamoDB"),
                Handler      = "func_DynamoDB::func_DynamoDB.Function::FunctionHandler",
                Timeout      = Amazon.CDK.Duration.Minutes(3),
                Role         = iamRole,
                //Role = Role.FromRoleArn (this, "fullAccessLambda_DynamoDB", "arn:aws:iam::138340313734:role/Lambda_AdminRole", new FromRoleArnOptions { })
            });

            // Create Lambda Function for SNS
            var func_SNS = new Function(this, "demoFuncSNS", new FunctionProps {
                Runtime      = Runtime.DOTNET_CORE_3_1,
                FunctionName = "serverless-inventory-app-func-sns",
                Code         = Code.FromAsset("publish_lambda/func_SNS"),
                Handler      = "func_SNS::func_SNS.Function::FunctionHandler",
                Timeout      = Amazon.CDK.Duration.Minutes(3),
                Role         = iamRole,
                //Role = Role.FromRoleArn (this, "fullAccessLambda_SNS", "arn:aws:iam::138340313734:role/Lambda_AdminRole", new FromRoleArnOptions { })
            });

            // Create Lambda Function for RestAPI
            var func_GetItems = new Function(this, "demoFuncGetItems", new FunctionProps {
                Runtime      = Runtime.DOTNET_CORE_3_1,
                FunctionName = "serverless-inventory-app-func-getitems",
                Code         = Code.FromAsset("publish_lambda/func_GetItems"),
                Handler      = "func_GetItems::func_GetItems.Function::FunctionHandler",
                Timeout      = Amazon.CDK.Duration.Minutes(3),
                Role         = iamRole,
                //Role = Role.FromRoleArn (this, "fullAccessLambda_GetItems", "arn:aws:iam::138340313734:role/Lambda_AdminRole", new FromRoleArnOptions { })
            });

            // Create API Gateway for Applications
            var apiGateway = new LambdaRestApi(this, "demoAPIGateway", new LambdaRestApiProps {
                Handler     = func_GetItems,
                RestApiName = "serverless-inventory-app-api-inventory",
                Proxy       = false,
            });
            var items = apiGateway.Root.AddResource("api");

            items.AddMethod("GET");

            // Create Lambda Event for Upload Image S3
            func_DynamoDB.AddEventSource(new S3EventSource(s3Bucket, new S3EventSourceProps {
                Events = new [] { EventType.OBJECT_CREATED }
            }));

            // Create Lambda Event for Insert DynamoDB
            func_SNS.AddEventSource(new DynamoEventSource(dynamoDBTable, new DynamoEventSourceProps {
                StartingPosition = StartingPosition.LATEST,
            }));

            // Create A SNS
            var snsTopic = new Topic(this, "demoSNS", new TopicProps {
                TopicName   = "NoStock",
                DisplayName = "Out of Stock Topic",
            });

            snsTopic.AddSubscription(new EmailSubscription("*****@*****.**", new EmailSubscriptionProps {
            }));
        }