Skip to content

Instantly share code, notes, and snippets.

@gregeinfrank
Last active May 16, 2017 03:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gregeinfrank/8d75bdae630493dc9152da1db7d7b4c2 to your computer and use it in GitHub Desktop.
Save gregeinfrank/8d75bdae630493dc9152da1db7d7b4c2 to your computer and use it in GitHub Desktop.
Lambda function to run a scheduled task in ECS
import boto3
import os
def event_handler(event, context):
"""
Lambda function that will run a task on ECS with the given command on the given
task definition family. The ECS task will run a wrapper script that handles the
dynamodb lock and will exit if the task is already running.
"""
ecs_client = boto3.client('ecs')
cluster_arn = os.environ['ECS_CLUSTER_ARN']
task_definition_family = os.environ['ECS_TASK_DEFINITION_FAMILY']
container_name = os.environ['CONTAINER_NAME']
task_name = os.environ['SCHEDULED_TASK_NAME']
command = os.environ['SCHEDULED_TASK_COMMAND']
function_name = os.environ['AWS_LAMBDA_FUNCTION_NAME']
task_command = [
'/usr/local/bin/scheduled_task_runner.py', # This wrapper scripts handles the locking code
'--task_name', task_name,
command,
]
task_definition = get_task_definition(ecs_client, task_definition_family)
response = ecs_client.run_task(
cluster=cluster_arn,
taskDefinition=task_definition,
startedBy="{}/{}".format(function_name, context.aws_request_id)[0:36],
overrides={'containerOverrides': [
{
'name': container_name,
'command': task_command,
}
]}
)
if response['failures']:
raise RuntimeError("Failure for task name {}".format(task_name))
return {"completed": True}
def get_task_definition(client, family):
task_definition = client.describe_task_definition(taskDefinition=family)
if not task_definition:
raise ValueError("Unable to find task definition corresponding to {}".format(family))
revision = task_definition['taskDefinition']['revision']
return "{}:{}".format(family, revision)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment