So the problem is that lambda needs to be able to read from a db which is in a vpc and start a ecs fargate task. But if the lambda is in a vpc then it does not start the task itself rather the lambda times out.
import json
import boto3
client = boto3.client('ecs')
cluster_name = 'as-dev'
task_name = 'as-dev:2'
def lambda_handler(event, context):
# TODO implement
try:
response = client.run_task(
cluster=cluster_name,
launchType = 'FARGATE',
taskDefinition=task_name,
count = 1,
platformVersion='LATEST',
networkConfiguration={
'awsvpcConfiguration': {
'subnets': [
'subnet-12345ab12345'
],
'securityGroups': [
'sg-123451234sasdqwe'
],
'assignPublicIp': 'ENABLED'
}
}
)
print(response)
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
}
except Exception as e:
print(e)
return {
'statusCode': 500,
'body': str(e)
}
(Configurations changed for obvious reasons)
The code works fine if run as a simple python program on ec2. Only when the vpc is added to the lambda does it stop working and times out.
By default, a lambda function in a VPC, has no internet access. A popular way to enable the access is through the use of NAT gateway and placing your lambda in a private subnet as explained in:
Alternative is to use VPC interface endpoints for ECS. Once you set them up properly, you don't need to use internet. Instead your function will access ECS using the endpoint privately.