Tasks

A task is a running instance of a task definition — the unit ECS actually schedules.

A task is what ECS places onto compute. When you run a task, ECS pulls the images, starts the containers, and reports their status.

Task lifecycle

  1. PROVISIONING — networking is being set up.
  2. PENDING — images are being pulled.
  3. RUNNING — containers are up.
  4. STOPPED — the task finished or was stopped.

Run a standalone task with run-task for batch work, or let a service manage tasks for you.

Example

Example · bash
# One-off task, e.g. a database migration
aws ecs run-task \
  --cluster prod \
  --launch-type FARGATE \
  --task-definition migrate:5 \
  --network-configuration 'awsvpcConfiguration={subnets=[subnet-abc],securityGroups=[sg-123]}'

When to use it

  • A developer watches task state transitions in the console to debug why a newly deployed task keeps going from PENDING to STOPPED.
  • A scheduled EventBridge rule runs an ECS task every night to generate reports, replacing a cron job on an EC2 instance.
  • A CI pipeline waits for a run-task command to return STOPPED status and checks the exit code before marking a build as passing.

More examples

Run a One-Off Task and Wait

Runs a one-off task and blocks the shell script until the task reaches the STOPPED state before continuing.

Example · bash
TASK_ARN=$(aws ecs run-task \
  --cluster prod-cluster \
  --task-definition report-gen:2 \
  --launch-type FARGATE \
  --network-configuration 'awsvpcConfiguration={subnets=[subnet-a],securityGroups=[sg-jobs],assignPublicIp=DISABLED}' \
  --query 'tasks[0].taskArn' --output text)

aws ecs wait tasks-stopped --cluster prod-cluster --tasks "$TASK_ARN"
echo "Task finished"

Describe a Stopped Task's Exit Code

Retrieves the exit code and stop reason for each container in a stopped task to diagnose failures.

Example · bash
aws ecs describe-tasks \
  --cluster prod-cluster \
  --tasks arn:aws:ecs:us-east-1:123456789012:task/prod-cluster/abc123 \
  --query 'tasks[0].containers[*].{name:name,exit:exitCode,reason:reason}'

Schedule a Nightly Task via EventBridge

Creates an EventBridge cron rule that launches the report-gen ECS task every night at 02:00 UTC.

Example · bash
aws events put-rule \
  --name nightly-report \
  --schedule-expression 'cron(0 2 * * ? *)'

aws events put-targets \
  --rule nightly-report \
  --targets '[{"Id":"1","Arn":"arn:aws:ecs:us-east-1:123456789012:cluster/prod-cluster","RoleArn":"arn:aws:iam::123456789012:role/events-ecs-role","EcsParameters":{"TaskDefinitionArn":"arn:aws:ecs:us-east-1:123456789012:task-definition/report-gen:2","LaunchType":"FARGATE","NetworkConfiguration":{"awsvpcConfiguration":{"Subnets":["subnet-a"],"SecurityGroups":["sg-jobs"]}}}}]'

Discussion

  • Be the first to comment on this lesson.