1

I have a lambda function that is supposed to start an ecs task when invoked. It gets all the way down to the "Starting execution..." log then it logs "done.". It seems to just skip right over ecs.runTask(). I have tried getting the returned json output by setting the runtask function to a variable, but that has not helped. I have also tried changing some of my parameters and that has not worked as well.

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

exports.handler = async (event) => {
var params = {
  cluster: "ec2-cluster",
  enableECSManagedTags: true,
  launchType: "FARGATE",
  count: 1,
  platformVersion: 'LATEST',
  networkConfiguration: { 
    awsvpcConfiguration: { 
        assignPublicIp: "ENABLED",
        securityGroups: [ "sg" ],
        subnets: [ "subnet" ]
    }
  },
  startedBy: "testLambda",
  taskDefinition: "definition"
}

console.log("Starting execution...");

ecs.runTask(params, function(err, data) {
  console.log(err, data)  
});
// console.log(myReturn)
console.log("done.")

}

When I run this locally everything works great. When I run this in lambda however it does not start my task.

goodkid38
  • 79
  • 10
  • 1
    why are you using credentials inside your `lambda`? amende the permissions to the lambda role. – samtoddler Mar 22 '21 at 20:54
  • I forgot to remove them when testing locally. I removed them above. I have AmazonEC2FullAccess attached and am still not seeing results. – goodkid38 Mar 22 '21 at 21:01

1 Answers1

0

In your case, you will need to add Promise to ecs.runTask(). In the AWS Lambda documentation, they mentioned that we have to

Make sure that any background processes or callbacks in your code are complete before the code exits.

meaning that we need to await for the ecs.runTask() process to resolve. Here is an example of how we can apply async/await on aws-sdk. From the references above, the way to make your code work would be:

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

exports.handler = async (event) => {
var params = {
  cluster: "ec2-cluster",
  enableECSManagedTags: true,
  launchType: "FARGATE",
  count: 1,
  platformVersion: 'LATEST',
  networkConfiguration: { 
    awsvpcConfiguration: { 
        assignPublicIp: "ENABLED",
        securityGroups: [ "sg" ],
        subnets: [ "subnet" ]
    }
  },
  startedBy: "testLambda",
  taskDefinition: "definition"
}

console.log("Starting execution...");

// Added promise here
await ecs.runTask(params).promise();
// console.log(myReturn)
console.log("done.")

This is a common mistake that we might make when we first get into Lambda, especially when we try to make our Lambda functions work with some other AWS services via aws-sdk.

H.Y Hu
  • 1
  • 2