【问题标题】:Reference local code in SAM using CfnFunction in the CDK with Python使用 CDK 中的 CfnFunction 引用 SAM 中的本地代码和 Python
【发布时间】:2020-12-04 10:15:50
【问题描述】:

我正在使用 AWS CDK 创建 SAM CfnFunction

对于codeUri 属性,它需要引用S3LocationProperty

当使用 SAM CLI 时,我可以做这样的事情

Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello_world/

hello_world 有我的函数的代码。

运行 sam buildsam deploy 完成打包代码并将代码上传到 S3 的工作,并在 S3 中部署具有正确 CodeUri 路径的 Cloudformation 模板。

我尝试使用 CDK (Python) 做类似的事情,但 SAM cli 完成的幕后工作没有发生

from aws_cdk import (
    core,
    aws_sam as sam
)

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

        sam_stack = sam.CfnFunction(
            self, "MySamFunction",
            code_uri="lambda",  # Directory with my code
            runtime="python3.8",
            handler="MyFunction.handler",
            # other properties removed
        )

在创建堆栈时运行 cdk deploy 错误

Transform AWS::Serverless-2016-10-31 failed with: Invalid Serverless Application Specification document. Number of errors found: 1. Resource with id [InferenceSam] is invalid. 'CodeUri' is not a valid S3 Uri of the form 's3://bucket/key' with optional versionId query parameter.

有没有办法使用 CDK 自动打包和上传我的 python 代码到 S3?

【问题讨论】:

    标签: python amazon-web-services amazon-cloudformation aws-cdk aws-sam


    【解决方案1】:

    我做过类似的事情,以下是我使用的方法

    cdk-project
     | package.json
     | cdk.json
     | stack.ts
     |- lambda (sam application directory)
        | template.yaml
        |- solution
           | requirements.txt
           |- app       
              | index.py 
    

    template.yaml 内部

    Resources:
      SolutionAPIFunction:
        Type: AWS::Serverless::Function 
        Properties:
          CodeUri: solution/
          Handler: app.index.lambda_handler
    

    package.json 里面

     "scripts": {
        "build": "cd lambda && sam build && cd .. && tsc",
        "watch": "tsc -w",
        "test": "jest",
        "cdk": "cdk"
      },
    

    所以当运行“npm run build”时,它会运行sam build,它会在cdk-project/lambda/.aws-sam下创建一个文件夹

    stack.ts内部

        const aFunction = new Function(this, "aFunction", {
          runtime: Runtime.PYTHON_3_8,
          handler: "app.index.lambda_handler",
          code: Code.asset('./lambda/.aws-sam/build/SolutionAPIFunction')
          timeout: cdk.Duration.minutes(3),
          logRetention: logs.RetentionDays.THREE_MONTHS      
        })
    

    【讨论】:

      【解决方案2】:

      这个帖子有点老了,但我遇到了这个问题,这很令人费解,所以我想分享我的解决方案。我能够通过使用aws_s3_assets lib 为我的部署解决这个问题,并将local 标志传递到无服务器堆栈中,以决定是否将资产上传到合成器上,或者使用本地执行的路径。

      例如:

      import aws_cdk.core as cdk
      from aws_cdk import aws_sam as sam
      from aws_cdk import aws_s3_assets as s3_assets
      
      
      class ServerlessStack(cdk.Stack):
      
          def __init__(
              self, scope: cdk.Construct, id: str, local: bool = False, **kwargs
          ) -> None:
      
          # function_kwargs is a dict containing specific function params
          # see: https://docs.aws.amazon.com/cdk/api/latest/python/aws_cdk.aws_sam/CfnFunction.html
      
          if not local:
              function_kwargs['code_uri'] = s3_assets.Asset(
                  scope=self,
                  id=f"{function}asset",
                  path=function_kwargs.pop('code_uri')
              ).s3_object_url
      
          # Create the function resource
          sam.CfnFunction(
              scope=self,
              id=function,
              runtime="python3.8",
              **function_kwargs
          )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-29
        • 1970-01-01
        • 1970-01-01
        • 2022-01-15
        • 2021-04-06
        相关资源
        最近更新 更多