【问题标题】:Call a lambda function from another lambda function从另一个 lambda 函数调用一个 lambda 函数
【发布时间】:2022-12-05 20:13:57
【问题描述】:

我是aws的新手。我正在使用 AWS 学习者实验室。我想要做的是,当我运行第一个 lambda 函数时,我希望第二个函数也能运行。第二个函数将文件上传到 S3。但是我有点挣扎,不确定为什么我的功能不起作用。当我运行第一个函数时,文件没有上传到 S3。如果我测试第二个功能,它就会工作。

第一个函数是使用 js 第二个函数是使用 python。

第一个功能 索引.js

var aws = require('aws-sdk');
var lambda = new aws.Lambda({
  region: 'us-east-1' //change to your region
});
exports.handler = async (event, context, callback) => {
lambda.invoke({
  FunctionName: 'arn:aws:lambda:us-west-1:294593484020:function:UploadFileS3Bucket',
  Payload: JSON.stringify(event, null, 2) // pass params
}, function(error, data) {
  if (error) {
    context.done('error', error);
  }
  if(data.Payload){
   context.succeed(data.Payload)
  }
})}; 

第二功能 lambda_函数.py

import json
import boto3

def lambda_handler(event, context):
    # TODO implement
    with open('/tmp/dummy.txt','w') as f:
        f.write('dummy\n')
        f.close()
        
    s3 = boto3.client('s3')
    s3.upload_file('/tmp/dummy.txt','htp-iot-bucket', 'dummy.txt')
    
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }

【问题讨论】:

  • 到底是什么不起作用?你从这两个函数得到什么日志输出?

标签: amazon-web-services amazon-s3 aws-lambda


【解决方案1】:

要从 AWS 中的第一个函数调用第二个 lambda 函数,您可以使用适用于 JavaScript 的 AWS 开发工具包 (AWS-SDK) 通过 invoke() 方法调用该函数。例如:

const AWS = require('aws-sdk');

exports.handler = async (event, context) => {
    // Create a client for AWS Lambda
    const lambda = new AWS.Lambda();
    
    // Invoke the lambda function using the function name and the payload
    const result = await lambda.invoke({
        FunctionName: 'my_second_function',
        Payload: JSON.stringify(event)
    }).promise();
    
    // Get the response data from the invoked lambda function
    const responseData = JSON.parse(result.Payload);
    
    // Process the response data as needed
    ...
};

或者,您可以使用 AWS Lambda API 通过 HTTP POST 请求直接调用函数。例如:

const https = require('https');

exports.handler = async (event, context) => {
    // Set the URL for the AWS Lambda API
    const apiUrl = `https://${context.invokedFunctionArn.split(':')[3]}.execute-api.${context.invokedFunctionArn.split(':')[3]}.amazonaws.com/${context.invokedFunctionArn.split(':')[7]}/`;
    
    // Invoke the lambda function using an HTTP POST request with the payload
    const result = await new Promise((resolve, reject) => {
        const request = https.request(
            `${apiUrl}my_second_function`,
            {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            },
            response => {
                let data = '';
                response.on('data', chunk => data += chunk);
                response.on('end', () => resolve(data));
            }
        );
        request.on('error', error => reject(error));
        request.write(JSON.stringify(event));
        request.end();
    });
    
    // Get the response data from the invoked lambda function
    const responseData = JSON.parse(result);
    
    // Process the response data as needed
    ...
};

请注意,当从另一个 lambda 函数调用 lambda 函数时,您需要确保调用函数具有调用目标函数的适当权限。这可以通过将基于资源的 IAM 策略添加到允许调用函数调用它的目标函数来完成。有关详细信息,请参阅 Granting Permissions to Use a Function in the AWS Lambda 文档。

【讨论】:

  • OP 已经知道如何调用第二个函数。这没有提供任何新的细节。 OP的问题是什么当前的执行?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-26
  • 2018-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多