Ali CAKIL
Ali CAKIL

Reputation: 428

how to start ecs fARGATE Task using AWS Lambda dotnet? timeout problem

I prepared a lambda function to start an ECS Fargate Task. When I debug it locally using "Mocked Lambda Test Tool" it works fine and starts it less then a minute! But when I deploy it and test in on AWS Console it throws a timeout error all the time! (in 7mins).

I created a role for the lambda and attached AdministratorAccess and AmazonECS_FullAccess policies to make sure about permission issues. And the security group allows all trafic for inbound/outbound. Lambda and ecs cluster are in the same subnet, same region. But result is the same,it gives timeout when executing RunTaskAsync!

What could be the reason for the timeout?

public async Task<string> FunctionHandler(ILambdaContext context)
{
    Console.WriteLine("Lambda starting...");
    IAmazonECS ecsClient = new AmazonECSClient();
    RunTaskRequest runTaskRequest = new RunTaskRequest
    {
        Cluster = "my-cluster",
        TaskDefinition = "my-task-definition-name",
        LaunchType = LaunchType.FARGATE,
        
        NetworkConfiguration = new NetworkConfiguration
        {
            AwsvpcConfiguration = new AwsVpcConfiguration
            {
                Subnets = new List<string> { "subnet-id-1", "subnet-id-2" },
                SecurityGroups = new List<string> { "security-group-id" }
            }                
        }
    };

    Console.WriteLine("RunTaskRequest instance prepared");
    var startTaskResponse = await ecsClient.RunTaskAsync(runTaskRequest);
    return "Task started successfully!";
}

Upvotes: 0

Views: 630

Answers (1)

Mark B
Mark B

Reputation: 200446

When you deploy a Lambda function to a VPC, it does not get a public IP address. That means it can't communicate with anything outside of the VPC. The ECS API, which the function is trying to communicate with exists outside of the VPC. The Lambda function is not trying to communicate directly with the ECS cluster, it is trying to communicate with the public AWS API, to tell AWS to create a new task inside the ECS cluster.

Here are your options for solving this issue:

  1. If you switch your VPC to IPv6, your Lambda functions will get a public IP and have access to the Internet.
  2. If you add a NAT Gateway, and move the Lambda function to private VPC subnets that have a route to the NAT Gateway, then the functions will have access to the Internet.
  3. If your function doesn't need to access anything else outside the VPC other than the AWS API, then you can add a VPC Endpoint that allows direct communication from your resources in your VPC to that AWS service, without going over the Internet.
  4. If your Lambda function doesn't actually need to access anything inside the VPC, then by far the easiest way to solve your issue is just to remove the VPC configuration from the Lambda function, and it will then have access to the Internet.

Upvotes: 1

Related Questions