简体   繁体   English

从在本地系统而非 S3 上运行的 node.js 应用程序调用 AWS Lambda

[英]Invoke AWS Lambda from a node.js app running on local system not S3

I would like to invoke AWS Lambda from a node.js file receding on my system.我想从我系统上的 node.js 文件调用 AWS Lambda。 I followed Invoking a Lambda Function in a Browser Script and created a Congnito Identity Pool for Unauthenticated user and embedded the IdentityPoolId in the node js file like below:我按照在浏览器脚本中调用 Lambda 函数并为未经身份验证的用户创建了一个 Congnito 身份池,并将 IdentityPoolId 嵌入到节点 js 文件中,如下所示:

 let AWS = require('aws-sdk'); AWS.config.region = '<my-region>'; let lambda = new AWS.Lambda(); AWS.config.credentials = new AWS.CognitoIdentityCredentials({ IdentityPoolId: '<my-identity-pool-id>' }); let params = { FunctionName: '<my-lambda-function>', InvocationType: 'RequestResponse', LogType: 'Tail', Payload: '{ "name": "my-name" }' } lambda.invoke(params, (err, data) => { if (err) { console.log(err); } else { if (data.Payload) { console.log('my-lambda-function said: ' + data.Payload); } } });

My Lambda Function:我的 Lambda 函数:

 exports.handler = function(event, context) { context.succeed('Hello ' + event.name); };

I have created an IAM Role with AWSLambdaExecute, AWSLambdaBasicExecutionRole and AmazonCognitoReadOnly policies attached and I am using the same role while creating Lambda as well as I have updated the same roles in the Identity Pool I have created in Cognito for Unauthorized access.我创建了一个附加了 AWSLambdaExecute、AWSLambdaBasicExecutionRole 和 AmazonCognitoReadOnly 策略的 IAM 角色,我在创建 Lambda 时使用相同的角色,并且我在 Cognito 中为未经授权的访问创建的身份池中更新了相同的角色。

When I run node app.js all I get is the error: UnrecognizedClientException: The security token included in the request is invalid.当我运行 node app.js 时,我得到的只是错误:UnrecognizedClientException:请求中包含的安全令牌无效。

Can somebody point me in the right direction to invoke an AWS lambda by writing a simple NodeJS file on my local system without uploading any HTML/CSS/JS files in an S3 Bucket and without using AccessKeyID, SecretKeyId, Just using roles associated with Lambda.有人可以通过在我的本地系统上编写一个简单的 NodeJS 文件而不在 S3 存储桶中上传任何 HTML/CSS/JS 文件并且不使用 AccessKeyID、SecretKeyId,仅使用与 Lambda 关联的角色来指出我调用 AWS lambda 的正确方向。

Thanks in Advance.提前致谢。

There are many ways to invoke a Lambda Function.调用 Lambda 函数的方法有很多种。

  • AWS services events (example: SNS triggered) AWS 服务事件(例如:SNS 触发)
  • API created through AWS API Gateway.通过 AWS API Gateway 创建的 API。
  • Amazon CloudWatch cron jobs Amazon CloudWatch cron 作业
  • API calls leveraging AWS Lambda APIs.利用 AWS Lambda API 的 API 调用。

If your aim is to use your function as API, which can send and receive request and responses, You probably should go for API Gateway Integration.如果您的目标是将您的功能用作可以发送和接收请求和响应的 API,您可能应该选择 API 网关集成。

It's super easy to get started with API Gateway. API Gateway 上手非常简单。

  • Get your Lambda function ready.准备好您的 Lambda 函数。
  • Set Up an IAM Role and Policy for an API to Invoke Lambda Functions为 API 设置 IAM 角色和策略以调用 Lambda 函数

    { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "lambda:InvokeFunction", "Resource": "*" } ] }
  • Create API Resources for the Lambda Function为 Lambda 函数创建 API 资源

    1. In the API Gateway console, create an API.在 API 网关控制台中,创建一个 API。

    2. Create the /ResourceName resource off the API's root.在 API 的根目录下创建/ResourceName资源。

    3. Create a GET or POST method based on you requirements.根据您的要求创建 GET 或 POST 方法。

    4. Choose AWS Service for Integration type and Select Lambda Function you created in the respective region.为集成类型选择 AWS 服务,然后选择您在相应区域创建的 Lambda 函数。

  • Now, you can customize integration Request based on your requirements with body mapping templates .现在,您可以根据您的要求使用身体映射模板自定义集成请求。

  • You may look into detailed documentation for API Gateway Integration with Lambda :您可以查看API Gateway Integration with Lambda的详细文档:

    In this section, we walk you through the steps to integrate an API with a Lambda function using the AWS Service and Lambda Function integration types.在本节中,我们将引导您完成使用 AWS 服务和 Lambda 函数集成类型将 API 与 Lambda 函数集成的步骤。

  • Once, your test invocation succeeds, you can then use the API invocation URL from API_NAME/Dashboard , which will look something like:一旦您的测试调用成功,您就可以使用API_NAME/Dashboard中的 API 调用 URL,它类似于:

     https:// ###****.execute-api.us-west-2.amazonaws.com/{APIStageName}/ https:// ###****.execute-api.us-west-2.amazonaws.com/{APIStageName}/

which can be used as REST endpoint and can be called from your Node js function locally.它可以用作 REST 端点,并且可以从本地的 Node js 函数调用。 Don't forget to enable authentication for your API with API keys.不要忘记使用 API 密钥为您的 API 启用身份验证。

Also, go through Production Checklist, if you are going to use it in Such Environment.此外,如果您要在此类环境中使用它,请查看生产清单。

I had the same issue, and I was able to resolve it using a Kinesis Stream.我有同样的问题,我能够使用 Kinesis Stream 解决它。 the Lambda function was acting as consumer. Lambda 函数充当消费者。 you have to create a trigger for the Lambda function as follows:您必须为 Lambda 函数创建一个触发器,如下所示:

 function createTrigger (kinesisArn, lambdaName) { // Create params const for trigger const params = { EventSourceArn: kinesisArn, FunctionName: lambdaName, StartingPosition: 'LATEST', BatchSize: 100 } return new Promise((resolve, reject) => { lambda.createEventSourceMapping(params, (err, data) => { if (err) reject(err) else resolve(data) }) }) }

each time a new piece of data is being pushed on the Kinesis stream, your Lambda function will be called.每次将新数据推送到 Kinesis 流时,都会调用您的 Lambda 函数。

here is an example of how sending data on AWS Kinesis stream:以下是如何在 AWS Kinesis 流上发送数据的示例:

 function send(streamName, partition, msg) { const params = { Data: JSON.stringify(msg), // data you want to send to your Lambda function PartitionKey: partition, // an id for each shard StreamName: streamName } return new Promise((resolve, reject) => { kinesis.putRecord(params, (err, data) => { if(err) reject(err) else resolve(data); }) }); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM