Home > Software design >  How to run an ECS task from AWS Lambda function?
How to run an ECS task from AWS Lambda function?

Time:09-23

I have created an ECS task definition and that runs successfully using AWS console and AWS CLI. Multiple instances of these tasks would run in a cluster. These are long-running tasks (few months to years).

I'm trying to run an instance of this task using the AWS Lambda function but it's not working. No error is thrown and a task does not run. I have added AdministratorAccess to the execution role used by the lambda. The VPC, subnet group, and security groups are configured in Lambda (tab Configuration > VPC)

Goal is to run the task and not wait for response (as these are long running tasks):

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); }
 });
};

Response:

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

enter image description here

CodePudding user response:

The async function exports.handler is returning before your ecs.runTask promise is being resolved try wrapping it like:

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.

Lambda on a public subnet that is connected to Internet Gateway won't have access to the internet.

Excerpt from another answer on Stackoverflow.

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

  • Related