Amazon ECS task with maximum lifespan
About
In some cases you may wish to limit how long a task can run for. This can be used to prevent a batch job from running too long, or to provide a maximum lifespan for an ephemeral game server or similar server that should boot clients after a period of time.
This pattern will show how to use a sidecar container to trigger Amazon ECS task to stop the task after a duration that you set.
Task Definition
Create a task definition using one of the following methods:
- AWS CloudFormation
- Raw JSON
AWSTemplateFormatVersion: '2010-09-09'
Description: An example task definition that has a maximum lifespan. After
the duration is up, the task automatically stops.
Resources:
SampleTaskDefinition:
Type: AWS::ECS::TaskDefinition
Properties:
Family: lifespan
Cpu: 256
Memory: 512
RequiresCompatibilities:
- FARGATE
NetworkMode: awsvpc
ContainerDefinitions:
# The application container
- Name: nginx
Image: public.ecr.aws/nginx/nginx:mainline
Essential: true
# Sidecar container that gives this task a lifetime
- Name: lifespan
Image: public.ecr.aws/docker/library/busybox:stable
Command:
- "sh"
- "-c"
- "sleep $LIFESPAN_SECONDS"
Environment:
- Name: LIFESPAN_SECONDS
Value: 60
Essential: true
Deploy the CloudFormation template above by using the AWS CloudFormation web console. Alternatively you can deploy from the command line with:
aws cloudformation deploy \
--stack-name sample-task-definition \
--template-file task-definition.yml
Test it Out
You can use the Amazon ECS console to launch a copy of the task as a standalone task. After 60 seconds you should see the task stop with a final message of "Essential container in task exited"