ECS Task Definition Examples: Copy-Paste JSON for Fargate and EC2, Valid CPU and Memory Values, Secrets, Roles, Health Checks, Terraform and CloudFormation
An ECS task definition is the JSON recipe Amazon ECS uses to run your containers: which image, how much CPU and memory, which ports, environment variables and secrets, where logs go, which IAM roles the task uses, and how to check that it is healthy. A task is one running copy of that recipe, and a service keeps a chosen number of tasks running. Below are copy-paste examples: a Fargate web app, an EC2 worker with dynamic ports, and a two-container task with a migration step, EFS and a restart policy, plus the valid Fargate CPU and memory pairs, Terraform and CloudFormation versions, and how to update and delete revisions. The detail that catches most teams: secrets and environment variables are read once, when a task starts. Rotate a password in Secrets Manager and every running container keeps the old one until it is replaced, so a rotation needs a new deployment. The second one: a task definition can never be edited. Every "edit" is a new revision, and services keep running the old revision until you update them.
Jake's booking site moved from one server in the back office to Fargate, and Ethan wrote the task definition on a Sunday evening. On Monday the database password rotated on schedule, and on Tuesday half the tasks could not reach the database. The new tasks had the new password; the old ones were still holding the old one. "So the password changed and the app did not notice?" Jake asked. "The app was told the password once, when it started," Ethan said. This page is that task definition, written properly, with the parts Ethan wished he had known on Sunday.
New to Amazon ECS? It runs containers for you, either on Fargate (no servers to manage, you pay per task) or on EC2 instances you own. Everything ECS needs to know about your containers lives in the task definition, so it is the first thing you write and the thing you change most.
Task definition vs task vs service vs container definition
| Term | What it is | Docker Compose equivalent |
|---|---|---|
| Task definition | The recipe: one or more containers plus task-level settings (CPU, memory, network mode, roles, volumes). Identified by family:revision, for example booking-web:7 | The whole compose.yaml |
| Container definition | One container inside the task definition: image, ports, environment, logs, health check. Up to 10 per task definition | One entry under services: |
| Task | One running copy of a task definition revision | One docker compose up |
| Service | Keeps N tasks running, replaces failed ones, registers them with a load balancer, rolls out new revisions | No direct equivalent (closest: deploy.replicas in Swarm) |
| Cluster | The logical group where services and tasks run, on Fargate, EC2 or both | The Docker host |
Two rules follow from this. Containers that must share localhost, start together and scale together belong in one task definition (an app and its log or proxy sidecar). Containers that scale on their own belong in separate task definitions and separate services (the web app and the background worker). Putting the whole application in one giant task definition is the most common design mistake people carry over from Docker Compose.
Fargate task definition example (JSON)
A web app on Fargate, ARM (Graviton) for the lower price, running as a non-root user with a read-only root file system, one secret, logs to CloudWatch and a health check. Replace the account ID, image and ARNs with yours:
{
"family": "booking-web",
"requiresCompatibilities": ["FARGATE"],
"networkMode": "awsvpc",
"cpu": "512",
"memory": "1024",
"runtimePlatform": { "operatingSystemFamily": "LINUX", "cpuArchitecture": "ARM64" },
"executionRoleArn": "arn:aws:iam::111122223333:role/ecsTaskExecutionRole",
"taskRoleArn": "arn:aws:iam::111122223333:role/booking-web-task",
"containerDefinitions": [
{
"name": "web",
"image": "111122223333.dkr.ecr.us-east-1.amazonaws.com/booking-web:1.4.2",
"essential": true,
"user": "1000",
"readonlyRootFilesystem": true,
"portMappings": [{ "containerPort": 8080, "protocol": "tcp", "name": "http" }],
"environment": [{ "name": "APP_ENV", "value": "production" }],
"secrets": [{ "name": "DB_PASSWORD",
"valueFrom": "arn:aws:secretsmanager:us-east-1:111122223333:secret:booking/db-AbCdEf:password::" }],
"healthCheck": {
"command": ["CMD-SHELL", "curl -f http://localhost:8080/health || exit 1"],
"interval": 30, "timeout": 5, "retries": 3, "startPeriod": 60
},
"logConfiguration": {
"logDriver": "awslogs",
"options": {
"awslogs-group": "/ecs/booking-web",
"awslogs-region": "us-east-1",
"awslogs-stream-prefix": "web",
"awslogs-create-group": "true"
}
}
}
]
}
If you are coming from docker run, the mapping is direct: -p 8080:8080 becomes portMappings, -e becomes environment, --user becomes user, --read-only becomes readonlyRootFilesystem, and --health-cmd becomes healthCheck. The one thing with no docker run equivalent is the pair of IAM roles, which is where most first task definitions go wrong.
Register it with aws ecs register-task-definition --cli-input-json file://booking-web.json, or paste it into the console with Create new task definition with JSON. What each part is doing:
requiresCompatibilities: FARGATEmakes ECS check the definition against Fargate's rules at registration (valid CPU and memory pair,awsvpcnetworking).networkMode: awsvpcis required on Fargate: each task gets its own network interface and private IP, and security groups apply to the task. OnlycontainerPortmatters; there is no host port.cpuandmemoryat task level are required on Fargate and are what you pay for.runtimePlatformpicks Linux onARM64orX86_64(the default). The image must be built for that architecture, or the task stops with an exec format error.userandreadonlyRootFilesystemsatisfy two Security Hub checks, ECS.20 (non-root users in Linux container definitions) and ECS.5 (read-only root file systems). With a read-only root, give the app a writable volume for temporary files.awslogs-create-groupcreates the log group on first start; the execution role then also needslogs:CreateLogGroup. Leave it out if you create log groups with infrastructure code (and set a retention while you are at it).
Valid Fargate CPU and memory values
Fargate accepts only certain combinations. Anything else fails at registration with Invalid 'cpu' setting for task from the CLI, or No Fargate configuration exists for given values from Terraform:
| CPU (units / vCPU) | Memory | Operating systems |
|---|---|---|
| 256 (0.25) | 512 MiB, 1 GB, 2 GB | Linux |
| 512 (0.5) | 1 to 4 GB in 1 GB steps | Linux |
| 1024 (1) | 2 to 8 GB in 1 GB steps | Linux, Windows |
| 2048 (2) | 4 to 16 GB in 1 GB steps | Linux, Windows |
| 4096 (4) | 8 to 30 GB in 1 GB steps | Linux, Windows |
| 8192 (8) | 16 to 60 GB in 4 GB steps | Linux (platform 1.4.0+) |
| 16384 (16) | 32 to 120 GB in 8 GB steps | Linux (platform 1.4.0+) |
| 32768 (32) | 60 GB, 120 GB or 244 GB | Linux (platform 1.4.0+) |
Memory in the JSON is in MiB (1 GB = 1024), and CPU in units (1024 = 1 vCPU); you can also write them as strings like "1 vCPU" and "2 GB", which ECS converts on registration. On EC2, task-level CPU can be anything from 0.25 to 192 vCPUs and is optional. On Fargate, per-container cpu and memory are optional too; if you set them, their totals must fit inside the task values.
What it costs on Fargate, Linux, US East (N. Virginia), October 2026: $0.04048 per vCPU-hour and $0.004445 per GB-hour on x86, and $0.03238 and $0.00356 on ARM. The example above (0.5 vCPU, 1 GB) running all month (730 hours) is about $18.02 on x86 or $14.42 on ARM, a 20 percent saving for changing one line, if your image builds for ARM. The task definition itself costs nothing. Our ECS on EC2 vs Fargate guide compares the two at scale.
Create a task definition in the console, step by step
If you prefer clicking to JSON the first time, the console builds the same document for you, and you can copy its JSON afterwards to keep in your repository:
- Open the Amazon ECS console, choose Task definitions, then Create new task definition. (Choose Create new task definition with JSON instead if you want to paste one of the examples on this page.)
- Enter a task definition family name, such as
booking-web. Every later revision keeps this name. - Under Infrastructure requirements, choose AWS Fargate, the operating system and architecture, the task size (CPU and memory from the valid pairs), and the task role and task execution role. If you have no execution role yet, the console can create
ecsTaskExecutionRolefor you. - Under Container 1, enter the container name and image URI, mark it essential, and add the port mapping your app listens on.
- Add environment variables and, under the same section, secrets with ValueFrom pointing at the secret's ARN.
- Keep Log collection on (it sets up
awslogs), and add a health check if your image has a way to test itself. - Choose Create. Open the new revision and choose the JSON tab to copy the full definition into your code repository.
From then on, you change it by choosing Create new revision, which opens a copy of the latest revision for you to edit. The old revision stays exactly as it was.
EC2 launch type example with dynamic host ports
On EC2 instances you own, the common setup is bridge networking with dynamic host ports, so several copies of the same container can run on one instance behind a load balancer:
{
"family": "booking-worker-ec2",
"requiresCompatibilities": ["EC2"],
"networkMode": "bridge",
"executionRoleArn": "arn:aws:iam::111122223333:role/ecsTaskExecutionRole",
"containerDefinitions": [
{
"name": "worker",
"image": "111122223333.dkr.ecr.us-east-1.amazonaws.com/booking-worker:2.0.1",
"essential": true,
"cpu": 256,
"memory": 512,
"memoryReservation": 256,
"portMappings": [{ "containerPort": 8080, "hostPort": 0, "protocol": "tcp" }],
"logConfiguration": {
"logDriver": "awslogs",
"options": { "awslogs-group": "/ecs/booking-worker", "awslogs-region": "us-east-1", "awslogs-stream-prefix": "worker" }
}
}
]
}
hostPort: 0 asks ECS to pick a free port on the instance for each task; the target group then sends traffic to whichever port each task got. memory is a hard limit (the container is stopped if it goes over, exit code 137), while memoryReservation is a soft limit ECS uses to place tasks; the container can use more up to the hard limit when the instance has it. Setting only memoryReservation lets a container burst into free memory, at the risk of crowding its neighbors. Our exit code 137 guide covers sizing these.
The network modes, side by side:
| networkMode | How it works | Use it for |
|---|---|---|
awsvpc | Each task gets its own network interface, private IP and security groups | Fargate (required) and most new EC2 workloads |
bridge | Docker's virtual network on the instance; ports mapped to host ports | Packing many small tasks on EC2 with dynamic ports |
host | Containers use the instance's network directly; one task per port per instance | Rare, performance-sensitive cases (Security Hub ECS.17 flags it) |
none | No external networking | Batch jobs that need no network |
Environment variables, environment files and secrets
There are three ways to hand configuration to a container, and they are not interchangeable:
environment: plain name and value pairs written in the task definition. Anyone who can read the task definition can read them, so use it only for non-secret settings. Security Hub control ECS.8 flags secrets passed this way.environmentFiles: up to 10 files in S3, each with a.envextension and oneVARIABLE=VALUEper line. Handy for long lists; the execution role needss3:GetObjecton the file (ands3:GetBucketLocation). Not available for Windows containers on Fargate.secrets: a name plus avalueFrompointing at a Secrets Manager secret or a Systems Manager Parameter Store parameter. ECS fetches the value at start and passes it in as an environment variable; the task definition only holds the ARN.
The Secrets Manager valueFrom can point at one key inside a JSON secret, which is how you get just the password from a secret that holds a whole database connection. The full format is secret-arn:json-key:version-stage:version-id; leave the last two empty, but keep the colons:
"secrets": [
{ "name": "DB_PASSWORD",
"valueFrom": "arn:aws:secretsmanager:us-east-1:111122223333:secret:booking/db-AbCdEf:password::" },
{ "name": "DB_SECRET_JSON",
"valueFrom": "arn:aws:secretsmanager:us-east-1:111122223333:secret:booking/db-AbCdEf" },
{ "name": "API_KEY",
"valueFrom": "arn:aws:ssm:us-east-1:111122223333:parameter/booking/api-key" }
]
Two version requirements apply. Picking a single JSON key or a specific version of a secret needs Fargate platform version 1.4.0 or later on Linux (1.0.0 on Windows), or ECS agent 1.37.0 or later on EC2; injecting a whole secret needs platform 1.3.0 or agent 1.22.0. The default LATEST platform version meets all of these, so this only bites tasks pinned to an old platform or EC2 instances with an old agent. Secrets can also be passed to a log driver through secretOptions in logConfiguration, for example an API token for a third-party log service, so the token never appears in plain text in the task definition.
With no version stage, ECS takes the version labeled AWSCURRENT. And here is the rule from the top of the page: the value is read when the task starts. If the secret is updated or rotated afterwards, the container does not receive the new value automatically. Launch new tasks, or for a service, run a new deployment with Force new deployment (aws ecs update-service --cluster prod --service booking-web --force-new-deployment). If your application must pick up rotations without a redeploy, have it read the secret from Secrets Manager at runtime (with the task role) instead of from an environment variable.
That is what bit Jake's shop. Ethan now runs a forced deployment as the last step of the rotation, and the app reads the password at connection time as a second line of defense. "Belt and braces," Ethan said. "The rotation can still surprise us, but not for a whole day."
Execution role vs task role
Task execution role (executionRoleArn) | Task role (taskRoleArn) | |
|---|---|---|
| Used by | The ECS agent / Fargate, before and around your container | Your application code inside the container |
| Typical permissions | Pull from ECR, write to CloudWatch Logs, read the secrets and environment files the definition references | Whatever the app calls: S3, DynamoDB, SQS, Bedrock... |
| Managed policy to start from | AmazonECSTaskExecutionRolePolicy, plus secretsmanager:GetSecretValue, ssm:GetParameters and kms:Decrypt (custom keys) as needed | None; write a least-privilege policy for the app |
| Error when it is wrong | The task never starts: CannotPullContainerError or ResourceInitializationError | The task runs, and your app gets AccessDenied |
Both roles trust the ecs-tasks.amazonaws.com service principal. Mixing them up is the most common reason a task definition "looks right" and fails: putting S3 permissions on the execution role does nothing for your code, and putting ECR permissions on the task role does nothing for the image pull. If the task never starts, read the stopped reason (our CannotPullContainerError and ResourceInitializationError guides cover each cause).
Two containers in one task: dependsOn, essential, volumes and restarts
A task that runs database migrations before the API starts, mounts an EFS file system and a scratch volume, gets 50 GiB of disk, and restarts the API container in place if it crashes:
{
"family": "booking-api",
"requiresCompatibilities": ["FARGATE"],
"networkMode": "awsvpc",
"cpu": "1024",
"memory": "2048",
"executionRoleArn": "arn:aws:iam::111122223333:role/ecsTaskExecutionRole",
"ephemeralStorage": { "sizeInGiB": 50 },
"volumes": [
{ "name": "uploads" },
{ "name": "shared-files",
"efsVolumeConfiguration": { "fileSystemId": "fs-0123456789abcdef0",
"transitEncryption": "ENABLED", "authorizationConfig": { "iam": "ENABLED" } } }
],
"containerDefinitions": [
{
"name": "migrate",
"image": "111122223333.dkr.ecr.us-east-1.amazonaws.com/booking-api:3.2.0",
"essential": false,
"command": ["python", "manage.py", "migrate"]
},
{
"name": "api",
"image": "111122223333.dkr.ecr.us-east-1.amazonaws.com/booking-api:3.2.0",
"essential": true,
"entryPoint": ["gunicorn"],
"command": ["app:server", "--bind", "0.0.0.0:8000"],
"dependsOn": [{ "containerName": "migrate", "condition": "SUCCESS" }],
"portMappings": [{ "containerPort": 8000 }],
"mountPoints": [
{ "sourceVolume": "uploads", "containerPath": "/tmp/uploads" },
{ "sourceVolume": "shared-files", "containerPath": "/mnt/shared" }
],
"stopTimeout": 60,
"restartPolicy": { "enabled": true, "ignoredExitCodes": [0, 143], "restartAttemptPeriod": 300 },
"environmentFiles": [{ "value": "arn:aws:s3:::booking-config/api.env", "type": "s3" }]
}
]
}
The pieces that matter:
essential: if an essential container stops for any reason, ECS stops the whole task. It defaults to true. The migration container is marked false so its normal exit does not end the task (our "essential container exited" guide covers the other side).dependsOnconditions:START(the other container has started),COMPLETE(it ran and exited, any code),SUCCESS(it exited with code 0) andHEALTHY(its health check passed). Here the API waits for a successful migration. The order reverses on shutdown.entryPointvscommand: they replace the image's DockerENTRYPOINTandCMD. Set onlycommandto pass different arguments to the image's own entry point; set both to run something else entirely.- Volumes: a volume with only a name is a bind mount on the task's ephemeral storage, shared by the containers that mount it and gone when the task stops. An EFS volume is persistent and shared between tasks (EFS explained); Security Hub control ECS.18 wants
transitEncryptionenabled on it. ephemeralStorage: Fargate tasks on platform 1.4.0 or later get 20 GiB by default and up to 200 GiB with this setting; your image counts against it. Storage above 20 GiB costs $0.000111 per GB-hour in us-east-1, so the extra 30 GiB here is about $2.43 a month per task running full time.stopTimeout: how long ECS waits after SIGTERM before killing the container; 30 seconds by default, 120 at most. Give web servers enough time to finish in-flight requests.restartPolicy: lets ECS restart a crashed container inside the running task instead of replacing the whole task.ignoredExitCodes(up to 50) lists exits that should not trigger a restart (here a clean exit, 0, and 143, the code a process returns when it is stopped with SIGTERM), and the container must have run forrestartAttemptPeriodseconds (60 at minimum) before a restart is attempted.
Container health check example and defaults
A container health check runs a command inside the container on a schedule. An exit code of 0 means healthy; anything else is a failure. The fields and their defaults:
"healthCheck": {
"command": ["CMD-SHELL", "curl -f http://localhost:8080/health || exit 1"],
"interval": 30,
"timeout": 5,
"retries": 3,
"startPeriod": 60
}
interval: seconds between checks, 5 to 300, default 30.timeout: seconds before one check counts as failed, 2 to 60, default 5.retries: failures in a row before the container is unhealthy, 1 to 10, default 3.startPeriod: a grace period of 0 to 300 seconds after start when failures do not count; off by default. Slow-starting apps (Java, large Python apps) need it.
Two things trip people up. The command runs inside your image, so curl must exist there; minimal and distroless images often lack it, and the check then fails forever (use a small binary of your own, or a language one-liner your image does have). And a container health check is separate from a load balancer health check: a service behind an ALB is judged by both, and either can stop the task. Our failed health checks guide separates the two.
Logging options: awslogs and FireLens
Every container should have a logConfiguration; Security Hub control ECS.9 checks for it, and without one a crash leaves no trace. The awslogs driver sends the container's standard output and standard error to CloudWatch Logs, with these options:
awslogs-groupandawslogs-region: where logs go.awslogs-stream-prefix: required on Fargate; streams are namedprefix/container-name/task-id, which makes a task's logs easy to find.awslogs-create-group: create the group if it does not exist (needslogs:CreateLogGroupon the execution role).modeandmax-buffer-size:non-blockingmode with a buffer (for example25m) keeps the app running if CloudWatch Logs is slow, at the cost of dropping logs when the buffer fills.
For sending logs elsewhere (OpenSearch, S3 through Firehose, a third-party service), ECS offers FireLens: a Fluent Bit or Fluentd sidecar container in the same task, with your app's logConfiguration set to the awsfirelens driver. It is more moving parts, so start with awslogs unless you need another destination. Either way, CloudWatch log groups never expire by default; set a retention on the group so old logs stop adding to the bill.
Update, deregister and delete task definitions
Task definition revisions cannot be changed after registration. Updating means registering a new revision and pointing the service at it:
- Edit your JSON (new image tag, more memory, a new variable) and register it:
aws ecs register-task-definition --cli-input-json file://booking-web.json. ECS gives it the next revision number in the family, for examplebooking-web:8. - Update the service to the new revision:
aws ecs update-service --cluster prod --service booking-web --task-definition booking-web:8. Leave off the revision (--task-definition booking-web) to use the latest active one. - Watch the deployment:
aws ecs wait services-stable --cluster prod --services booking-web, or the service's Deployments tab. If it never settles, our stuck deployment guide helps. - When you no longer need an old revision, deregister it:
aws ecs deregister-task-definition --task-definition booking-web:6. It becomesINACTIVE: running tasks and services using it keep working (services can even still scale), but you cannot run new tasks, create services or roll a service back to it. - To remove it completely, delete it (only
INACTIVErevisions can be deleted):aws ecs delete-task-definitions --task-definitions booking-web:6. Its status becomesDELETE_IN_PROGRESSuntil ECS removes it.
In the console, "editing" is Create new revision on the task definition page, which opens a copy for you to change, then Update service to use it. A family can have up to 1,000,000 revisions, and deregistered or deleted revisions still count toward that, so a pipeline that registers a revision on every commit is fine for a very long time, but not forever.
One more default worth knowing: ECS resolves your image tag to a digest when it deploys (the versionConsistency setting, enabled by default). All tasks of one deployment run the exact same image even if someone pushes a new :latest halfway through. To pick up a new image under the same tag, force a new deployment; better, use a unique tag per build.
Run a one-off task from a task definition
You do not need a service to use a task definition. For a migration, a report or a quick test, you can run a single task and let it stop when the container exits. On Fargate you must tell ECS which subnets and security groups to use, because the task gets its own network interface:
aws ecs run-task --cluster prod --launch-type FARGATE \
--task-definition booking-api:12 \
--network-configuration "awsvpcConfiguration={subnets=[subnet-0abc1234],securityGroups=[sg-0def5678],assignPublicIp=DISABLED}" \
--overrides '{"containerOverrides":[{"name":"api","command":["python","manage.py","send_reminders"]}]}'
The --overrides part lets you run a different command, environment or size for this one run without registering a new revision, which is ideal for occasional admin jobs. In a private subnet, your task needs a NAT gateway or VPC endpoints to reach ECR, CloudWatch Logs and Secrets Manager; without them it fails before your code starts (the ResourceInitializationError guide covers the endpoints). For jobs on a timetable, an EventBridge Scheduler or EventBridge rule can run the same task definition for you.
Images from Docker Hub and other private registries
Images in Amazon ECR need nothing extra beyond the execution role's ECR permissions. For a private image on Docker Hub, GitHub Container Registry or another registry, you store the registry login in Secrets Manager and point the container at it with repositoryCredentials:
"containerDefinitions": [{
"name": "web",
"image": "docker.io/jakesshop/booking-web:1.4.2",
"repositoryCredentials": {
"credentialsParameter": "arn:aws:secretsmanager:us-east-1:111122223333:secret:dockerhub-login-AbCdEf"
},
"essential": true
}]
The secret holds a JSON object with username and password keys, and the execution role needs secretsmanager:GetSecretValue on it (plus kms:Decrypt if you encrypted it with your own key). Public images on Docker Hub work without credentials, but anonymous pulls are rate limited; if you pull often, an ECR pull through cache keeps a copy in your own registry.
Windows containers in a task definition
Windows tasks follow the same structure with a few differences you should plan for. On Fargate, set runtimePlatform.operatingSystemFamily to one of the Windows Server values, such as WINDOWS_SERVER_2022_CORE or WINDOWS_SERVER_2025_FULL, matching the base image your container was built on. Windows on Fargate needs at least 1 vCPU (see the CPU table), costs more per hour (in us-east-1, $0.046552 per vCPU-hour and $0.00511175 per GB-hour, plus a Windows OS charge of $0.046 per vCPU-hour), and does not support environment files, read-only root file systems or Fargate ephemeral storage bind mounts. On EC2, task-level CPU and memory are ignored for Windows containers, so size each container instead.
Terraform task definition example
In Terraform, the task-level settings are arguments of aws_ecs_task_definition, and the containers are a JSON string, usually built with jsonencode:
resource "aws_ecs_task_definition" "booking_web" {
family = "booking-web"
requires_compatibilities = ["FARGATE"]
network_mode = "awsvpc"
cpu = 512
memory = 1024
execution_role_arn = aws_iam_role.ecs_execution.arn
task_role_arn = aws_iam_role.booking_web_task.arn
runtime_platform {
operating_system_family = "LINUX"
cpu_architecture = "ARM64"
}
container_definitions = jsonencode([{
name = "web"
image = "${aws_ecr_repository.booking_web.repository_url}:${var.image_tag}"
essential = true
portMappings = [{ containerPort = 8080, protocol = "tcp" }]
secrets = [{ name = "DB_PASSWORD", valueFrom = "${aws_secretsmanager_secret.db.arn}:password::" }]
logConfiguration = {
logDriver = "awslogs"
options = {
awslogs-group = aws_cloudwatch_log_group.booking_web.name
awslogs-region = "us-east-1"
awslogs-stream-prefix = "web"
}
}
}])
}
Inside jsonencode, the keys keep the ECS API's camelCase (portMappings, logConfiguration), while the resource's own arguments use Terraform's snake_case. Mixing them up is the usual reason Terraform plans a replacement on every run: ECS returns the definition with defaults filled in, Terraform compares, sees a difference and registers a new revision. Writing out the defaults you rely on (for example essential = true) keeps plans quiet. Changing any argument registers a new revision; the aws_ecs_service then needs to reference aws_ecs_task_definition.booking_web.arn to roll it out.
CloudFormation task definition example
BookingWebTaskDefinition:
Type: AWS::ECS::TaskDefinition
Properties:
Family: booking-web
RequiresCompatibilities: [FARGATE]
NetworkMode: awsvpc
Cpu: "512"
Memory: "1024"
ExecutionRoleArn: !GetAtt EcsExecutionRole.Arn
TaskRoleArn: !GetAtt BookingWebTaskRole.Arn
RuntimePlatform:
OperatingSystemFamily: LINUX
CpuArchitecture: ARM64
ContainerDefinitions:
- Name: web
Image: !Sub "${AWS::AccountId}.dkr.ecr.${AWS::Region}.amazonaws.com/booking-web:1.4.2"
Essential: true
PortMappings:
- ContainerPort: 8080
Secrets:
- Name: DB_PASSWORD
ValueFrom: !Sub "${DbSecret}:password::"
LogConfiguration:
LogDriver: awslogs
Options:
awslogs-group: !Ref BookingWebLogGroup
awslogs-region: !Ref AWS::Region
awslogs-stream-prefix: web
CloudFormation uses PascalCase for every property, including inside containers, and the log options keep their own lowercase names. !Ref on the task definition returns its full revision ARN, so a service that uses TaskDefinition: !Ref BookingWebTaskDefinition always points at the revision this stack registered. If you use the CDK, the FargateTaskDefinition construct writes this resource for you, creates the execution role and log group if you let it, and adds the permissions for any secrets you reference.
Any change to the task definition resource registers a new revision and, if a service references it with !Ref, rolls the service onto it in the same stack update.
Task definition best practices checklist
Before you register a task definition for production, run through this list. Each item is one of the problems on this page, prevented in advance:
- Pin the image to a unique tag or digest per build, never
:latest, so you always know what is running. - Size from data: start with the smallest valid Fargate pair that runs your app under load, watch CPU and memory in Container Insights for a week, then adjust.
- Use ARM64 if your image and dependencies build for it; it is about 20 percent cheaper on Fargate.
- Run as a non-root user and with a read-only root file system, with volumes for the paths your app writes.
- Keep secrets in
secrets, never inenvironment, and add a forced deployment to your rotation process. - Give the execution role and the task role separate, minimal policies.
- Log every container with
awslogsand a stream prefix, and set a retention on the log group. - Add a health check with a
startPeriodlong enough for a cold start, using a tool that exists in the image. - Set
stopTimeoutlong enough for graceful shutdown, and handle SIGTERM in your app. - Keep the JSON in your repository and register it from your pipeline, so every change is reviewed and you can roll back by redeploying an older revision.
Task definition limits worth knowing
- 10 containers per task definition (cannot be raised).
- 1,000,000 revisions per family; deregistered and deleted revisions still count.
- 50 tags per task definition; Security Hub ECS.15 wants task definitions tagged.
- 10 environment files per container.
- Health check interval 5 to 300 s, timeout 2 to 60 s, retries 1 to 10, start period 0 to 300 s.
- stopTimeout up to 120 s (default 30).
- Fargate ephemeral storage 20 GiB default, 200 GiB maximum.
The revision limit is the one teams with busy pipelines eventually think about. You can see how many revisions a family has and tidy up old ones from the command line; this keeps the five newest active revisions and deregisters the rest (deregistering does not affect tasks already running them):
aws ecs list-task-definitions --family-prefix booking-web --status ACTIVE \
--sort DESC --query "taskDefinitionArns[5:]" --output text | tr '\t' '\n' |
while read -r arn; do
[ -n "$arn" ] && aws ecs deregister-task-definition --task-definition "$arn" --query "taskDefinition.revision"
done
Check first which revisions your services use. A service on a deregistered revision keeps running and can still scale up and down, but you can no longer run new standalone tasks from that revision, create a service with it, or update a service back to it, so a rollback to it is no longer possible. You can delete the deregistered revisions afterwards if you want them gone from the console, but they keep counting toward the million either way.
Task definition problems, by symptom
"Invalid 'cpu' setting for task" or "No Fargate configuration exists for given values"
The CPU and memory pair is not one Fargate supports. Pick a pair from the table above; memory is in MiB.
The task stops with "exec format error"
The image's architecture does not match runtimePlatform. Build the image for ARM64 (or multi-arch), or set cpuArchitecture to X86_64.
Tasks still use the old password after a rotation
Secrets are injected only at task start. Force a new deployment, or read the secret at runtime with the task role.
"ResourceInitializationError: unable to pull secrets"
The execution role lacks secretsmanager:GetSecretValue, ssm:GetParameters or kms:Decrypt, or the task cannot reach those services from its subnet. Fix the role, then check NAT or VPC endpoints.
My app gets AccessDenied calling S3 or DynamoDB
The permission is on the execution role instead of the task role, or taskRoleArn is missing. Your code uses the task role.
The container is unhealthy forever
The health check command is missing from the image (often curl) or the app needs a startPeriod. Test the command with ECS Exec inside a running container.
"Read-only file system" errors after enabling readonlyRootFilesystem
The app writes to its own directories. Mount a volume at the paths it writes to, such as /tmp.
Terraform registers a new revision on every apply
The container definition JSON differs from what ECS returns, usually missing defaults or wrong key case. Write out the defaults and keep camelCase inside jsonencode.
"The specified log group does not exist" when the task starts
The awslogs group is missing. Create it, or add awslogs-create-group set to true and give the execution role logs:CreateLogGroup; our log group guide covers the other causes.
"Port is already allocated" on EC2
Two tasks on one instance asked for the same fixed host port. Use hostPort 0 for dynamic ports with bridge mode, or switch to awsvpc.
The task stops with "OutOfMemoryError: Container killed due to memory usage"
The container passed its hard memory limit (exit code 137). Raise memory, or find the leak; the exit code 137 guide shows how to size it.
The service is still running the old revision
Registering a revision does not update services. Run update-service with the new revision, or point infrastructure code at the new ARN.
ECS task definitions: frequently asked questions
What is an ECS task definition?
A JSON document that tells Amazon ECS how to run one or more containers: image, CPU and memory, ports, environment, secrets, logging, IAM roles and health checks. Each version is a numbered revision in a family.
What is the difference between an ECS task and a task definition?
The task definition is the recipe; a task is one running copy of a specific revision. One task definition can run as many tasks.
What is the difference between an ECS service and a task definition?
A service keeps a chosen number of tasks from a task definition running, replaces failed ones and handles deployments and load balancer registration. The task definition only describes the containers.
How do I update an ECS task definition?
Register a new revision with your changes, then update the service to use it. Existing revisions cannot be edited.
How do I delete an ECS task definition?
Deregister the revision so it becomes INACTIVE, then run aws ecs delete-task-definitions on it. Only inactive revisions can be deleted.
What is the difference between the task role and the execution role?
The execution role is used by ECS to pull images, write logs and fetch secrets before your app starts. The task role is what your application code uses to call AWS services.
How do I pass secrets to an ECS task?
Use the secrets field with the ARN of a Secrets Manager secret or Parameter Store parameter, and give the execution role permission to read it. ECS injects the value as an environment variable at start.
Do ECS tasks get updated secrets automatically?
No. Secrets are read when the task starts. Force a new deployment after a rotation, or read the secret at runtime.
What CPU and memory values does Fargate support?
Fixed pairs from 0.25 vCPU with 512 MiB up to 32 vCPU with 244 GB. For example, 0.5 vCPU allows 1 to 4 GB and 1 vCPU allows 2 to 8 GB.
What network mode should I use for ECS?
awsvpc, which Fargate requires and which gives each task its own IP and security groups. Use bridge on EC2 when you want dynamic host ports on shared instances.
What is the difference between entryPoint and command in ECS?
They override the image's ENTRYPOINT and CMD. Set command alone to change the arguments; set both to run a different program.
How do I add a health check to an ECS task definition?
Add healthCheck to the container definition with a command such as CMD-SHELL curl -f http://localhost:8080/health || exit 1. Defaults are a 30-second interval, 5-second timeout and 3 retries.
How many containers can an ECS task definition have?
Up to 10 container definitions per task definition. Containers that scale independently belong in separate task definitions.
How much does an ECS task definition cost?
Nothing; you pay for what runs. On Fargate in us-east-1, Linux x86 is $0.04048 per vCPU-hour and $0.004445 per GB-hour, and ARM is about 20 percent cheaper.
Can I convert a Docker Compose file to an ECS task definition?
Yes, by hand: each Compose service becomes a container definition, and services that scale separately should become separate task definitions and ECS services.
Why do Security Hub controls flag my task definition?
Common findings are a root user (ECS.20), a writable root file system (ECS.5), secrets in environment variables (ECS.8), no logging configuration (ECS.9) and host network mode (ECS.17).
For readers preparing for an AWS certification
We have been covering AWS certifications alongside our fixes, so here is a short extra for readers studying for one. If you only came for the fix, you already have it; feel free to skip this part.
Exams that test this topic: Developer – Associate (DVA-C03 from December 1, 2026) • CloudOps Engineer – Associate (SOA-C03) • Solutions Architect – Associate (SAA-C03) • DevOps Engineer – Professional (DOP-C02).
Here are the exam-style questions this topic tends to raise, with the reasoning you need to answer them:
1. Application code in an ECS task gets AccessDenied when writing to S3, but the image pulls and logs work. What is wrong?
The S3 permission is missing from the task role (taskRoleArn); the execution role only covers image pulls, logs and secrets retrieval.
2. A database password must not appear in the task definition. How should it reach the container?
Store it in Secrets Manager or Parameter Store and reference its ARN in the secrets field; the execution role needs permission to read it.
3. After a secret is rotated, running ECS tasks still use the old value. What is the fix?
Secrets are injected at task start, so force a new deployment of the service (or have the app read the secret at runtime).
4. Registering a Fargate task definition fails with "Invalid 'cpu' setting for task". Why?
The CPU and memory pair is not a supported Fargate combination, for example 256 CPU units allow only 512 MiB, 1 GB or 2 GB.
5. Which network mode is required for tasks on Fargate?
awsvpc, which gives each task its own elastic network interface and security groups.
6. How do you change the image of a running ECS service?
Register a new task definition revision with the new image, then update the service to that revision; existing revisions cannot be edited.
Exam codes and dates change often. Our AWS certification changes page keeps track of what is current.
The next rotation went through on a Thursday afternoon without anyone noticing: the rotation finished, the forced deployment replaced the tasks one by one, and the booking page never blinked. Jake asked whether that meant they could stop thinking about it. "It means the task definition remembers for us," Ethan said. "That was the point of writing it down."
📌 If you keep one line from this page
A task definition is an immutable, versioned recipe: register a new revision for every change and update the service to it, use a valid Fargate CPU and memory pair, keep secrets in the secrets field and redeploy after rotations, and give the execution role and the task role their separate jobs.
10 containers per definition · 20 to 200 GiB Fargate storage · health check 30 s / 5 s / 3 retries · Fargate x86 $0.04048 per vCPU-hour (us-east-1).
Revision note. Written October 22, 2026, with Amazon ECS parameters, quotas and US East (N. Virginia) Fargate prices of that date. "The palest ink is better than the best memory," the proverb says; a task definition is that ink for your containers.