当前位置: 首页 > 知识库问答 >
问题:

无服务器框架-用于预定义云前沿分发的lambda@edge部署

孟乐逸
2023-03-14
Resources:

ResourcesBucket:
    Type: AWS::S3::Bucket
    Properties:
        BucketName: ${self:custom.resourcesBucketName}
        AccessControl: Private
        CorsConfiguration:
            CorsRules:
            -   AllowedHeaders: ['*']
                AllowedMethods: ['PUT']
                AllowedOrigins: ['*']

ResourcesBucketPolicy:
    Type: AWS::S3::BucketPolicy
    Properties:
        Bucket:
            Ref: ResourcesBucket
        PolicyDocument:
            Statement:
            # Read permission for CloudFront
            -   Action: s3:GetObject
                Effect: "Allow"
                Resource: 
                    Fn::Join: 
                        - ""
                        - 
                            - "arn:aws:s3:::"
                            - 
                                Ref: "ResourcesBucket"
                            - "/*"
                Principal:
                    CanonicalUser: !GetAtt CloudFrontOriginAccessIdentity.S3CanonicalUserId

CloudFrontOriginAccessIdentity:
    Type: AWS::CloudFront::CloudFrontOriginAccessIdentity
    Properties:
        CloudFrontOriginAccessIdentityConfig:
            Comment:
                Fn::Join: 
                    - ""
                    -
                            - "Identity for accessing CloudFront from S3 within stack "
                            - 
                                Ref: "AWS::StackName"
                            - ""
                # I can use this instead of Fn::Join !Sub 'Identity for accessing CloudFront from S3 within stack #{AWS::StackName}' Getting benefit of
                # serverless-pseudo-parameters plugin

# Cloudfront distro backed by ResourcesBucket
ResourcesCdnDistribution:
    Type: AWS::CloudFront::Distribution
    Properties:
        DistributionConfig:
            Origins:
                # S3 origin for private resources
                -   DomainName: !Sub '${self:custom.resourcesBucketName}.s3-${self:provider.region}.amazonaws.com'
                    Id: S3OriginPrivate
                    S3OriginConfig:
                        OriginAccessIdentity: !Sub 'origin-access-identity/cloudfront/#{CloudFrontOriginAccessIdentity}'
                # S3 origin for public resources           
                -   DomainName: !Sub '${self:custom.resourcesBucketName}.s3-${self:provider.region}.amazonaws.com'
                    Id: S3OriginPublic
                    S3OriginConfig:
                        OriginAccessIdentity: !Sub 'origin-access-identity/cloudfront/#{CloudFrontOriginAccessIdentity}'
            Enabled: true
            Comment: CDN for public and provate static content.
            DefaultRootObject: index.html
            HttpVersion: http2
            DefaultCacheBehavior:
                AllowedMethods:
                    - DELETE
                    - GET
                    - HEAD
                    - OPTIONS
                    - PATCH
                    - POST
                    - PUT
                Compress: true
                TargetOriginId: S3OriginPublic
                ForwardedValues:
                    QueryString: false
                    Headers:
                    - Origin
                    Cookies:
                        Forward: none
                ViewerProtocolPolicy: redirect-to-https
            CacheBehaviors:
                - 
                    PathPattern: 'private/*'
                    TargetOriginId: S3OriginPrivate
                    AllowedMethods:
                    - DELETE
                    - GET
                    - HEAD
                    - OPTIONS
                    - PATCH
                    - POST
                    - PUT
                    Compress: true
                    ForwardedValues:
                        QueryString: false
                        Headers:
                            - Origin
                        Cookies:
                            Forward: none
                    ViewerProtocolPolicy: redirect-to-https
                - 
                    PathPattern: 'public/*'
                    TargetOriginId: S3OriginPublic
                    AllowedMethods:
                    - DELETE
                    - GET
                    - HEAD
                    - OPTIONS
                    - PATCH
                    - POST
                    - PUT
                    Compress: true
                    ForwardedValues:
                        QueryString: false
                        Headers:
                            - Origin
                        Cookies:
                            Forward: none
                    ViewerProtocolPolicy: redirect-to-https

            PriceClass: PriceClass_200
        service: mda-app-uploads
    
    plugins:
      - serverless-offline
      - serverless-pseudo-parameters
      - serverless-iam-roles-per-function
    
    custom:
      stage: ${opt:stage, self:provider.stage}
      resourcesBucketName: ${self:custom.stage}-mda-resources-bucket
    
    
        provider:
          name: aws
          runtime: nodejs12.x
          stage: ${opt:stage, 'dev'}
          region: us-east-1
          versionFunctions: true
        
        
        
        resources:
          - ${file(resources/s3-cloudfront.yml)}
          
        # functions:
        functions: 
          mdaAuthEdge:
            handler: mda-edge-auth.handler
            events:
              - cloudFront:
                  eventType: viewer-request
                  origin:
                    Id: S3OriginPrivate
TypeError: Cannot read property 'replace' of undefined
service: mda-app-uploads

plugins:
  - serverless-offline
  - serverless-pseudo-parameters
  - serverless-iam-roles-per-function

custom:
  stage: ${opt:stage, self:provider.stage}
  resourcesBucketName: ${self:custom.stage}-mda-resources-bucket


provider:
  name: aws
  runtime: nodejs12.x
  stage: ${opt:stage, 'dev'}
  region: us-east-1
  versionFunctions: true



resources:
  # Buckets
  - ${file(resources/s3-cloudfront.yml)}
  
# functions:
functions: 
  mdaAuthEdge:
    handler: mda-edge-auth.handler
    role: LambdaEdgeFunctionRole
Resources:

    LambdaEdgeFunctionRole:
        Type: "AWS::IAM::Role"
        Properties:
            Path: "/"
            ManagedPolicyArns:
                - "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
            AssumeRolePolicyDocument:
                Version: "2012-10-17"
                Statement:
                -
                    Sid: "AllowLambdaServiceToAssumeRole"
                    Effect: "Allow"
                    Action: 
                        - "sts:AssumeRole"
                    Principal:
                        Service: 
                            - "lambda.amazonaws.com"
                            - "edgelambda.amazonaws.com"
    LambdaEdgeFunctionPolicy:
        Type: "AWS::IAM::Policy"
        Properties:
            PolicyName: MainEdgePolicy
            PolicyDocument:
                Version: "2012-10-17"
                Statement:
                    Effect: "Allow"
                    Action: 
                        - "lambda:GetFunction"
                        - "lambda:GetFunctionConfiguration"
                    Resource: !Ref MdaAuthAtEdgeLambdaFunction.Version #!Join [':', [!GetAtt MdaAuthAtEdgeLambdaFunction.Arn, '2']]
            Roles:
                - !Ref LambdaEdgeFunctionRole




    ResourcesBucket:
        Type: AWS::S3::Bucket
        Properties:
            BucketName: ${self:custom.resourcesBucketName}
            AccessControl: Private
            CorsConfiguration:
                CorsRules:
                -   AllowedHeaders: ['*']
                    AllowedMethods: ['PUT']
                    AllowedOrigins: ['*']

    ResourcesBucketPolicy:
        Type: AWS::S3::BucketPolicy
        Properties:
            Bucket:
                Ref: ResourcesBucket
            PolicyDocument:
                Statement:
                # Read permission for CloudFront
                -   Action: s3:GetObject
                    Effect: "Allow"
                    Resource: 
                        Fn::Join: 
                            - ""
                            - 
                                - "arn:aws:s3:::"
                                - 
                                    Ref: "ResourcesBucket"
                                - "/*"
                    Principal:
                        CanonicalUser: !GetAtt CloudFrontOriginAccessIdentity.S3CanonicalUserId
    
    CloudFrontOriginAccessIdentity:
        Type: AWS::CloudFront::CloudFrontOriginAccessIdentity
        Properties:
            CloudFrontOriginAccessIdentityConfig:
                Comment:
                    Fn::Join: 
                        - ""
                        -
                                - "Identity for accessing CloudFront from S3 within stack "
                                - 
                                    Ref: "AWS::StackName"
                                - ""
                    # I can use this instead of Fn::Join !Sub 'Identity for accessing CloudFront from S3 within stack #{AWS::StackName}' Getting benefit of
                    # serverless-pseudo-parameters plugin

    # Cloudfront distro backed by ResourcesBucket
    ResourcesCdnDistribution:
        Type: AWS::CloudFront::Distribution
        Properties:
            DistributionConfig:
                Origins:
                    # S3 origin for private resources
                    -   DomainName: !Sub '${self:custom.resourcesBucketName}.s3-${self:provider.region}.amazonaws.com'
                        Id: S3OriginPrivate
                        S3OriginConfig:
                            OriginAccessIdentity: !Sub 'origin-access-identity/cloudfront/#{CloudFrontOriginAccessIdentity}'
                    # S3 origin for public resources           
                    -   DomainName: !Sub '${self:custom.resourcesBucketName}.s3-${self:provider.region}.amazonaws.com'
                        Id: S3OriginPublic
                        S3OriginConfig:
                            OriginAccessIdentity: !Sub 'origin-access-identity/cloudfront/#{CloudFrontOriginAccessIdentity}'
                Enabled: true
                Comment: CDN for public and provate static content.
                DefaultRootObject: index.html
                HttpVersion: http2
                DefaultCacheBehavior:
                    AllowedMethods:
                        - DELETE
                        - GET
                        - HEAD
                        - OPTIONS
                        - PATCH
                        - POST
                        - PUT
                    Compress: true
                    TargetOriginId: S3OriginPublic
                    ForwardedValues:
                        QueryString: false
                        Headers:
                        - Origin
                        Cookies:
                            Forward: none
                    ViewerProtocolPolicy: redirect-to-https
                CacheBehaviors:
                    - 
                        PathPattern: 'private/*'
                        TargetOriginId: S3OriginPrivate
                        AllowedMethods:
                        - DELETE
                        - GET
                        - HEAD
                        - OPTIONS
                        - PATCH
                        - POST
                        - PUT
                        Compress: true
                        LambdaFunctionAssociations:
                            - 
                                EventType: origin-request
                                LambdaFunctionARN: !Ref MdaAuthEdgeLambdaFunction.Version
                                    #!Join [':', [!GetAtt MdaAuthAtEdgeLambdaFunction.Arn, '2']]
            #    arn:aws:lambda:eu-west-1:219511374676:function:mda-aws-functions-dev-authLambdaAtEdge:1
                        ForwardedValues:
                            QueryString: false
                            Headers:
                                - Origin
                            Cookies:
                                Forward: none
                        ViewerProtocolPolicy: redirect-to-https
                    - 
                        PathPattern: 'public/*'
                        TargetOriginId: S3OriginPublic
                        AllowedMethods:
                        - DELETE
                        - GET
                        - HEAD
                        - OPTIONS
                        - PATCH
                        - POST
                        - PUT
                        Compress: true
                        ForwardedValues:
                            QueryString: false
                            Headers:
                                - Origin
                            Cookies:
                                Forward: none
                        ViewerProtocolPolicy: redirect-to-https

                PriceClass: PriceClass_200

共有1个答案

杜楚
2023-03-14
    service: mda-app-uploads
    
    plugins:
      - serverless-offline
      - serverless-pseudo-parameters
      - serverless-iam-roles-per-function
      - serverless-bundle
    
    
    custom:
      stage: ${opt:stage, self:provider.stage}
      resourcesBucketName: ${self:custom.stage}-mda-resources-bucket
      resourcesStages:
        prod: prod
        dev: dev
      resourcesStage: ${self:custom.resourcesStages.${self:custom.stage}, self:custom.resourcesStages.dev}
    
    
    provider:
      name: aws
      runtime: nodejs12.x
      stage: ${opt:stage, 'dev'}
      region: us-east-1
      versionFunctions: true
    
    functions: 
      oauthEdge:
        handler: src/mda-edge-auth.handler
        role: LambdaEdgeFunctionRole
        memorySize: 128
        timeout: 5
    
    
    resources:
      - ${file(resources/s3-cloudfront.yml)}
Resources:

    AuthEdgeLambdaVersion:
        Type: Custom::LatestLambdaVersion
        Properties:
            ServiceToken: !GetAtt PublishLambdaVersion.Arn
            FunctionName: !Ref OauthEdgeLambdaFunction
            Nonce: "Test"

    PublishLambdaVersion:
        Type: AWS::Lambda::Function
        Properties:
            Handler: index.handler
            Runtime: nodejs12.x
            Role: !GetAtt PublishLambdaVersionRole.Arn
            Code:
                ZipFile: |
                    const {Lambda} = require('aws-sdk')
                    const {send, SUCCESS, FAILED} = require('cfn-response')
                    const lambda = new Lambda()
                    exports.handler = (event, context) => {
                        const {RequestType, ResourceProperties: {FunctionName}} = event
                        if (RequestType == 'Delete') return send(event, context, SUCCESS)
                        lambda.publishVersion({FunctionName}, (err, {FunctionArn}) => {
                        err
                            ? send(event, context, FAILED, err)
                            : send(event, context, SUCCESS, {FunctionArn})
                        })
                    }

    PublishLambdaVersionRole:
        Type: AWS::IAM::Role
        Properties:
            AssumeRolePolicyDocument:
                Version: '2012-10-17'
                Statement:
                - Effect: Allow
                  Principal:
                    Service: lambda.amazonaws.com
                  Action: sts:AssumeRole
            ManagedPolicyArns:
            - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
            Policies:
            - PolicyName: PublishVersion
              PolicyDocument:
                Version: '2012-10-17'
                Statement:
                - Effect: Allow
                  Action: lambda:PublishVersion
                  Resource: '*'

    LambdaEdgeFunctionRole:
        Type: "AWS::IAM::Role"
        Properties:
            Path: "/"
            ManagedPolicyArns:
                - "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
            AssumeRolePolicyDocument:
                Version: "2012-10-17"
                Statement:
                -
                    Sid: "AllowLambdaServiceToAssumeRole"
                    Effect: "Allow"
                    Action: 
                        - "sts:AssumeRole"
                    Principal:
                        Service: 
                            - "lambda.amazonaws.com"
                            - "edgelambda.amazonaws.com"
    LambdaEdgeFunctionPolicy:
        Type: "AWS::IAM::Policy"
        Properties:
            PolicyName: MainEdgePolicy
            PolicyDocument:
                Version: "2012-10-17"
                Statement:
                    Effect: "Allow"
                    Action: 
                        - "lambda:GetFunction"
                        - "lambda:GetFunctionConfiguration"
                    Resource: !GetAtt AuthEdgeLambdaVersion.FunctionArn
            Roles:
                - !Ref LambdaEdgeFunctionRole


    ResourcesBucket:
        Type: AWS::S3::Bucket
        Properties:
            BucketName: ${self:custom.resourcesBucketName}
            AccessControl: Private
            CorsConfiguration:
                CorsRules:
                -   AllowedHeaders: ['*']
                    AllowedMethods: ['PUT']
                    AllowedOrigins: ['*']

    ResourcesBucketPolicy:
        Type: AWS::S3::BucketPolicy
        Properties:
            Bucket:
                Ref: ResourcesBucket
            PolicyDocument:
                Statement:
                # Read permission for CloudFront
                -   Action: s3:GetObject
                    Effect: "Allow"
                    Resource: 
                        Fn::Join: 
                            - ""
                            - 
                                - "arn:aws:s3:::"
                                - 
                                    Ref: "ResourcesBucket"
                                - "/*"
                    Principal:
                        CanonicalUser: !GetAtt CloudFrontOriginAccessIdentity.S3CanonicalUserId
                -   Action: s3:PutObject
                    Effect: "Allow"
                    Resource: 
                        Fn::Join: 
                            - ""
                            - 
                                - "arn:aws:s3:::"
                                - 
                                    Ref: "ResourcesBucket"
                                - "/*"
                    Principal:
                        AWS: !GetAtt LambdaEdgeFunctionRole.Arn

                -   Action: s3:GetObject
                    Effect: "Allow"
                    Resource: 
                        Fn::Join: 
                            - ""
                            - 
                                - "arn:aws:s3:::"
                                - 
                                    Ref: "ResourcesBucket"
                                - "/*"
                    Principal:
                        AWS: !GetAtt LambdaEdgeFunctionRole.Arn

    
    CloudFrontOriginAccessIdentity:
        Type: AWS::CloudFront::CloudFrontOriginAccessIdentity
        Properties:
            CloudFrontOriginAccessIdentityConfig:
                Comment:
                    Fn::Join: 
                        - ""
                        -
                            - "Identity for accessing CloudFront from S3 within stack "
                            - 
                                Ref: "AWS::StackName"
                            - ""


    # Cloudfront distro backed by ResourcesBucket
    ResourcesCdnDistribution:
        Type: AWS::CloudFront::Distribution
        Properties:
            DistributionConfig:
                Origins:
                    # S3 origin for private resources
                    -   DomainName: !Sub '${self:custom.resourcesBucketName}.s3.amazonaws.com'
                        Id: S3OriginPrivate
                        S3OriginConfig:
                            OriginAccessIdentity: !Sub 'origin-access-identity/cloudfront/#{CloudFrontOriginAccessIdentity}'
                    # S3 origin for public resources           
                    -   DomainName: !Sub '${self:custom.resourcesBucketName}.s3.amazonaws.com'
                        Id: S3OriginPublic
                        S3OriginConfig:
                            OriginAccessIdentity: !Sub 'origin-access-identity/cloudfront/#{CloudFrontOriginAccessIdentity}'
                Enabled: true
                Comment: CDN for public and provate static content.
                DefaultRootObject: index.html
                HttpVersion: http2
                DefaultCacheBehavior:
                    AllowedMethods:
                        - DELETE
                        - GET
                        - HEAD
                        - OPTIONS
                        - PATCH
                        - POST
                        - PUT
                    Compress: true
                    TargetOriginId: S3OriginPublic
                    ForwardedValues:
                        QueryString: false
                        Headers:
                        - Origin
                        Cookies:
                            Forward: none
                    ViewerProtocolPolicy: redirect-to-https
                CacheBehaviors:
                    - 
                        PathPattern: 'private/*'
                        TargetOriginId: S3OriginPrivate
                        AllowedMethods:
                        - DELETE
                        - GET
                        - HEAD
                        - OPTIONS
                        - PATCH
                        - POST
                        - PUT
                        Compress: true
                        LambdaFunctionAssociations:
                            - 
                                EventType: viewer-request
                                LambdaFunctionARN: !GetAtt AuthEdgeLambdaVersion.FunctionArn
                        ForwardedValues:
                            QueryString: false
                            Headers:
                                - Origin
                            Cookies:
                                Forward: none
                        ViewerProtocolPolicy: redirect-to-https
                    - 
                        PathPattern: 'public/*'
                        TargetOriginId: S3OriginPublic
                        AllowedMethods:
                        - DELETE
                        - GET
                        - HEAD
                        - OPTIONS
                        - PATCH
                        - POST
                        - PUT
                        Compress: true
                        ForwardedValues:
                            QueryString: false
                            Headers:
                                - Origin
                            Cookies:
                                Forward: none
                        ViewerProtocolPolicy: redirect-to-https

                PriceClass: PriceClass_200
 类似资料:
  • 我最近探索了serverless,我想为我的应用程序创建一个“简单”的后端。它应该像CRUD连接到DynamoDB,就像这里很好地显示的那样。然后转换成使用Cognoto记录用户。链接1和链接2( 在我的实施过程中,我遇到了一些问题,我想请您帮助,因为我不喜欢使用我只复制的东西,也不知道它是如何工作的: > 为什么我不需要设置CORS(标头)时初始化lambdas与无服务器,而不是在亚马逊控制台中

  • 我正在尝试部署一个简单的Slack lambda api,它使用库从特定通道中删除成员和固定消息。我遇到的问题是函数没有问题地执行,并且它没有问题地删除通道成员,但是我的Lambda函数不断返回: 作为反应体。当我使用检查日志时,也没有看到任何错误。我看到我的函数的console.log成功执行。 null 为什么会出现此错误,以及如何解决此错误? 在处理程序函数中引用了这一点之后,我使用了。使用

  • 预先定义的虚拟服务器 FreeRADIUS包括站点可用子目录下的虚拟服务器。有些可以按原样使用,而有些则是用于特殊要求的模板。以下是一些虚拟服务器: buffered-sql:此虚拟服务器用于克服大型SQL数据库(type = detail)的速度限制。 copy-acct-to-home-server:此虚拟服务器可用作模板,用于在两个位置记录一个计费请求(type = detail)。 coa

  • 示例:如何打包visual studio aws无服务器项目? 使用命令行和无服务器,需要做什么才能正确地将dotnet核心功能部署到AWS Lambda?这可能使用无服务器框架吗?

  • 如您所见,我正在使用codePipeline和codeBuild自动化部署。我的后端基于无服务器框架,它在触发命令时部署lambda函数。这就是我没有使用codeDeploy进行传统部署的原因<代码>构建规范。yml文件如下所示: 现在,我有3个关于CodeBuild和Serverless的问题: 问题1:命令依赖于一个名为的文件,其中包含数据库密码等秘密。此文件将不会被签入git。你认为在cod

  • 本文向大家介绍Node.js 服务器端应用开发框架 -- Hapi.js,包括了Node.js 服务器端应用开发框架 -- Hapi.js的使用技巧和注意事项,需要的朋友参考一下 Hapi.js 是一个用来构建基于 Node.js 的应用和服务的富框架,使得开发者把重点放在便携可重用的应用逻辑而不是构建架构。内建输入验证、缓存、认证和其他 Web 应用开发常用的功能。 示例代码: 附上github