如何 运行 来自 AWS Lambda 函数的 ECS 任务?

How to run an ECS task from AWS Lambda function?

我已经创建了一个 ECS 任务定义,并且 运行 使用 AWS 控制台和 AWS CLI 成功创建了它。这些任务的多个实例将 运行 在一个集群中。这些是长期 运行ning 任务(几个月到几年)。

我正在尝试使用 AWS Lambda 函数 运行 此任务的一个实例,但它不起作用。没有错误被抛出,任务也没有 运行。我已将 AdministratorAccess 添加到 lambda 使用的执行角色。 VPC、子网组和安全组在 Lambda 中配置(选项卡配置 > VPC)

目标是 运行 任务而不是等待响应(因为这些是长 运行ning 任务):

var aws = require('aws-sdk');
var ecs = new aws.ECS();

exports.handler = async (event) => {
     
   var params = {
        cluster: "default", 
        count: 1,
       launchType: "FARGATE",
       networkConfiguration: { 
         awsvpcConfiguration: { 
         assignPublicIp: "ENABLED",
         securityGroups: [ "sg-79002b" ],
         subnets: [ "subnet-f4b4bf" ]
        }
       },
    taskDefinition: "ecs-test-job-TestTaskDefinition-RgKHGrRzWZOq:1"
 };
 ecs.runTask(params, function(err) {
      if (err) { console.warn('error: ', "Error while starting task: " + err); }
 });
};

回复:

Function Logs
START RequestId: 3f89e3d7-b997-4cda-a939-1ad806812c31 Version: $LATEST
END RequestId: 3f89e3d7-b997-4cda-a939-1ad806812c31
REPORT RequestId: 3f89e3d7-b997-4cda-a939-1ad806812c31  Duration: 50.20 ms  Billed Duration: 51 ms  Memory Size: 1280 MB    Max Memory Used: 87 MB  Init Duration: 417.57 ms

异步函数 exports.handler 在你的 ecs.runTask promise 被解析之前返回尝试像这样包装它:

var myprom = ecs.runTask(params).promise();
var result = await myprom;  //Old syntax is myprom.then(()=>{})

Try this code for checking if Lambda can connect to the internet.

连接到互联网网关的 public 子网上的 Lambda 将无法访问互联网。

.

For Lambda to have access to the internet via VPC it should be in the Private Subnet with NAT Gateway attached.

Attach NAT Gateway instead of igw-xxxxxx in route table of your current subnet