在本地运行现有的 AWS Lambda

问题描述

我使用 Visual Studio 在 C# 中创建了 AWS Lambda,它从 API 端点返回一些 JSON。现在我想在本地运行那个 lambda。所有示例都使用 AWS SAM,但它们使用 SAM 模板创建了一个函数

当我运行命令 sam local start-lambda 时,我收到一条错误消息,指出找不到模板。那么可以肯定的是,我需要 template.yaml,但我不确定有没有办法为现有的 Lambda 生成这个模板?

感谢任何帮助!

解决方法

Check out the Template Anatomy resource on the AWS documentation

你可能会发现这个例子很有帮助(它被大大简化了)。我使用 NodeJS 进行开发,但是在创建 SAM 模板时编程语言之间的差异是微不足道的。该示例是 API 网关 (HTTP) 事件调用的简单 Lambda 函数 someFunction 的概要。


AWSTemplateFormatVersion: '2010-09-09'
Transform: 'AWS::Serverless-2016-10-31'
Description: My Serverless Application
Parameters:
  # Manually define this in AWS IAM for just the services needed.
  lambdaExecutionRole:
    Description: 'Required. The role used for lambda execution.'
    Type: 'String'
    Default: 'arn:aws:iam::nnnnnnnnnnnn:role/LambdaExecutionRole'


Globals:
  Function:
    Runtime: nodejs10.x
  #   Environment:
  #     Variables:
  #       NODE_ENV: test
  #       DEBUG: myapp:foo

Resources:

  performSomeFunction:
    Type: 'AWS::Serverless::Function'
    Properties:
      FunctionName: performSomeFunction
      Handler: lambda.someFunction
      CodeUri: ./
      Description: description of the function being performed
      MemorySize: 256
      Timeout: 60
      Role:
        Ref: lambdaExecutionRole
      Events:
        # API Gateway proxy endpoint.
        ProxyApiRoot:
          Type: Api
          Properties:
            Path: '/'
            Method: ANY
        ProxyApiGreedy:
          Type: Api
          Properties:
            Path: '/{proxy+}'
            Method: ANY

当您开始使用 AWS Lambda 时,需要牢记的重要概念之一是您的函数将如何触发。函数由不同种类的事件触发,可以有many many different types of events。我倾向于使用 API Gateway、Simple Queue Service 和 CloudWatch Events 来触发我的,但这完全取决于您的用例。

,

原来可以导出Lambda函数,得到生成的.yaml模板,正是我需要的。