Verified SOP & TutorialAudited Score 98/100

The Complete Production SOP: How to Deploy and Run AWS ECS Fargate Task Definitions & Service Auto-Scaling in Autonomous AI Agents

Production SOP to install and run aws-ecs-fargate-task-def in Codex, Claude Code, and Cursor. Automate task defs, IAM roles, and auto-scaling reliably.

Target Runtimes:codexclaude-codecursorwindsurf
5 min read • Updated for 2026

Technical Overview & Architectural Context

Autonomous coding agents frequently encounter subtle but catastrophic misconfigurations when generating AWS ECS Fargate architectures. Common hallucinated patterns include assigning EC2 bridge networking modes instead of 'awsvpc', conflating task execution roles (used by the ECS agent for ECR pulls and SSM/Secrets Manager decryption) with task roles (used by application logic), and mismatching CPU-to-memory allocation ratios strictly enforced by AWS Fargate. Furthermore, agents often omit critical Application Auto Scaling scalable target registrations or establish target tracking metrics with incompatible dimension sets. The aws-ecs-fargate-task-def skill installs deterministic procedural standard operating procedures directly into your AI runtime's context. By defining strict structural boundaries—such as mandating 'requiresCompatibilities: ["FARGATE"]', enforcing CloudWatch 'awslogs' log driver configurations, establishing decoupled execution and task IAM role ARNs, and standardizing Target Tracking Scaling policies on ALB RequestCountPerTarget and ECSServiceAverageCPUUtilization—this skill eliminates agent guess-work and guarantees idempotent, production-ready Infrastructure-as-Code deliverables.

Prerequisites & Environment Requirements

Codex Desktop, Claude Code CLI, Cursor IDE, or Windsurf installed with active workspace permissions
AWS CLI v2 installed locally with configured AWS credentials or sandbox assumed role
Terraform 1.5+ or AWS CDK v2 installed in the local project workspace
Git 2.40+ initialized with clean working tree

Verified Search Intents & Long-Tail Queries Solved

SEO Audit Score: 98/100

This operational tutorial is engineered to provide deterministic solutions for these developer search queries:

#install aws-ecs-fargate-task-def in cursor ide#claude code aws-ecs-fargate-task-def rules#codex desktop aws-ecs-fargate-task-def setup tutorial#how to fix aws-ecs-fargate-task-def agent execution error#aws ecs fargate task definition target tracking scaling sop#inject secrets ecs fargate ssm parameters agent workflow#aws-ecs-fargate-task-def sandbox permissions and security score#aws-ecs-fargate-task-def prompt examples and triggers

Step-by-Step Execution Playbook

1

Local Environment Setup & SKILL.md Mounting

Mount the skill manifest into your agent runtime's global or workspace-level skill registry.

Autonomous agent engines (such as Claude Code, Codex, and Cursor) discover contextual operational instructions by scanning dedicated skill directories. We mount the SKILL.md file into the workspace rules directory so the runtime parser indexes frontmatter triggers like 'create ecs fargate task definition' and 'configure ecs target tracking scaling'.

Terminal Command
mkdir -p .cursor/rules && curl -fsSL https://askills.dev/api/skills/aws-ecs-fargate-task-def/raw -o .cursor/rules/aws-ecs-fargate-task-def.mdc || mkdir -p ~/.agents/skills/aws-ecs-fargate-task-def && curl -fsSL https://askills.dev/api/skills/aws-ecs-fargate-task-def/raw -o ~/.agents/skills/aws-ecs-fargate-task-def/SKILL.md
.cursor/rules/aws-ecs-fargate-task-def.mdc
---
description: "Deploy serverless container workloads on AWS ECS Fargate with CloudWatch logs and auto-scaling."
globs: ["**/ecs/**", "**/*task-def*.json", "**/terraform/modules/ecs/**"]
---
# AWS ECS Fargate Task Definitions & Service Auto-Scaling SOP
- Network Mode must strictly be 'awsvpc'.
- requiresCompatibilities must contain 'FARGATE'.
- Decouple executionRoleArn (pull image, fetch secrets) from taskRoleArn (app AWS SDK).
- Set logConfiguration with logDriver 'awslogs' and mode 'non-blocking'.
Production Pro-Tip

Use scoped globs in your cursor rules file to prevent the agent from injecting heavy ECS schemas into unrelated prompt contexts, preserving valuable input token space.

Sandbox Gotcha

Claude Code CLI evaluates files in ~/.claude/skills while Cursor evaluates .cursor/rules. Ensure you place the file according to your targeted runtime environment.

2

Parameter and IAM Validation

Pre-flight validation for CPU/Memory combinations and SSM parameter path references.

AWS Fargate strictly rejects arbitrary CPU and memory combinations (e.g., 512 CPU shares only accept 1024MB, 2048MB, 3072MB, or 4096MB). Ensure standard environment variables and AWS provider configurations are present so the agent correctly resolves SSM parameters without attempting external network calls.

Terminal Command
aws --version && terraform -version
ecs-task-template.json
{
  "family": "app-production-service",
  "networkMode": "awsvpc",
  "requiresCompatibilities": ["FARGATE"],
  "cpu": "512",
  "memory": "1024",
  "executionRoleArn": "arn:aws:iam::123456789012:role/ecsTaskExecutionRole",
  "taskRoleArn": "arn:aws:iam::123456789012:role/ecsTaskAppRole",
  "containerDefinitions": [
    {
      "name": "app-container",
      "image": "123456789012.dkr.ecr.us-east-1.amazonaws.com/app:v1.2.0",
      "essential": true,
      "portMappings": [{
        "containerPort": 8080,
        "protocol": "tcp"
      }],
      "secrets": [{
        "name": "DATABASE_URL",
        "valueFrom": "arn:aws:ssm:us-east-1:123456789012:parameter/prod/app/DATABASE_URL"
      }],
      "logConfiguration": {
        "logDriver": "awslogs",
        "options": {
          "awslogs-group": "/ecs/app-production-service",
          "awslogs-region": "us-east-1",
          "awslogs-stream-prefix": "ecs"
        }
      }
    }
  ]
}
Production Pro-Tip

Reference secrets via valueFrom pointing to the full ARN (including parameter path) to allow the ECS agent to automatically decrypt via KMS without application-level SDK calls.

Sandbox Gotcha

The execution role requires kms:Decrypt permissions in addition to ssm:GetParameters if parameters are encrypted with customer-managed KMS keys.

3

Intent Matching & Trigger Invocation

Invoke deterministic agent workflows using exact trigger prompts.

Trigger the loaded skill by issuing prompts mapped to frontmatter triggers. The agent inspects its procedural SOP and executes task definition generation, ALB target group attachment, and target tracking scaling configuration.

autoscaling.tf
resource "aws_appautoscaling_target" "ecs_target" {
  max_capacity       = 10
  min_capacity       = 2
  resource_id        = "service/${aws_ecs_cluster.main.name}/${aws_ecs_service.main.name}"
  scalable_dimension = "ecs:service:DesiredCount"
  service_namespace  = "ecs"
}

resource "aws_appautoscaling_policy" "cpu_tracking" {
  name               = "ecs-cpu-target-tracking"
  policy_type        = "TargetTrackingScaling"
  resource_id        = aws_appautoscaling_target.ecs_target.resource_id
  scalable_dimension = aws_appautoscaling_target.ecs_target.scalable_dimension
  service_namespace  = aws_appautoscaling_target.ecs_target.service_namespace

  target_tracking_scaling_policy_configuration {
    predefined_metric_specification {
      predefined_metric_type = "ECSServiceAverageCPUUtilization"
    }
    target_value       = 70.0
    scale_in_cooldown  = 300
    scale_out_cooldown = 60
  }
}
Production Pro-Tip

Set scale_in_cooldown significantly higher (e.g., 300s) than scale_out_cooldown (e.g., 60s) to prevent thrashing and flapping container instances under bursty load.

Sandbox Gotcha

Never run Application Auto Scaling concurrently with an external cron-based scaler without lifecycle ignore_changes on desired_count in the ECS service definition.

4

Verification, Linting & Output Quality Gate

Enforce deterministic schema validation and local verification checks.

Instruct the autonomous agent to validate the synthesized task definitions against AWS ECS schemas or run Terraform validation before marking the task complete.

Terminal Command
terraform validate && aws ecs register-task-definition --generate-cli-skeleton | jq empty
validate-task-def.sh
#!/usr/bin/env bash
set -euo pipefail

TASK_DEF_FILE="ecs-task-template.json"
echo "Validating JSON syntax for ${TASK_DEF_FILE}..."
jq . "${TASK_DEF_FILE}" > /dev/null

echo "Checking Fargate compatibility rules..."
NET_MODE=$(jq -r '.networkMode' "${TASK_DEF_FILE}")
if [ "${NET_MODE}" != "awsvpc" ]; then
  echo "ERROR: networkMode must be 'awsvpc' for Fargate, got '${NET_MODE}'" >&2
  exit 1
fi
echo "Task definition verified successfully."
Production Pro-Tip

Chain jq schema assertions inside your agent's pre-commit hook to catch invalid Fargate CPU/memory matrices prior to remote deployment.

Sandbox Gotcha

Avoid committing plain-text sensitive variables in environment fields; the SOP requires all secrets to reside under the 'secrets' array.

Real-World Scenario: Production Webhook Service Provisioning on ECS Fargate with Secrets and Auto-Scaling

Tested Trigger Prompt (Feed directly into Codex, Claude, or Cursor):

“create ecs fargate task definition for a webhook receiver service using image 123456789012.dkr.ecr.us-east-1.amazonaws.com/webhook:latest. It requires 0.5 vCPU, 1GB RAM, secrets injected from SSM parameter /prod/webhook/SECRET_TOKEN, CloudWatch logs to /ecs/webhook-service, and configure ecs target tracking scaling targeting 60% CPU utilization with min 2 and max 8 tasks.”

Deterministic Agent Verification Pipeline:
Agent inspects aws-ecs-fargate-task-def SOP and selects valid CPU/Memory values ('512' and '1024').
Agent generates task definition JSON specifying networkMode 'awsvpc', requiresCompatibilities ['FARGATE'], and configures CloudWatch logDriver 'awslogs'.
Agent injects SECRET_TOKEN under 'secrets' referencing SSM ARN, explicitly assigning executionRoleArn with decrypt permissions.
Agent generates Terraform or CloudFormation defining the ECS Service and attaches aws_appautoscaling_target and aws_appautoscaling_policy for ECSServiceAverageCPUUtilization at 60.0% target value.
Agent runs syntax and validation checks on generated templates, ensuring no plaintext secrets exist.

Runtime Troubleshooting & Failure Modes

Error: ClientException: Fargate requires that 'cpu' and 'memory' be specified at the task level.

Root Cause: The agent defined CPU and memory constraints only inside the containerDefinitions array instead of the root-level task definition block required by Fargate.

Resolution Command / Fix:
Add task-level 'cpu': '512' and 'memory': '1024' at the root of the task definition JSON object alongside 'requiresCompatibilities'.
Error: InvalidParameterException: When networkMode=awsvpc, the host ports and container ports in port mappings must match.

Root Cause: The agent attempted EC2-style port mapping with different hostPort and containerPort (or hostPort set to 0 dynamic mapping).

Resolution Command / Fix:
Ensure containerPort equals hostPort or omit hostPort entirely, as awsvpc allocates dedicated ENIs where port translation is not supported.

Frequently Asked Questions (AWS ECS Fargate Task Definitions & Service Auto-Scaling SOP)

Q:Can I use AWS ECS Fargate Task Definitions & Service Auto-Scaling across Codex, Claude Code, and Cursor simultaneously?

Yes. The skill conforms to the open SKILL.md specification and can be consumed as a system prompt directive in Claude Code CLI, Cursor Rules (.cursor/rules/*.mdc), Codex environments, and Windsurf cascades without syntax alterations.

Q:How does AWS ECS Fargate Task Definitions & Service Auto-Scaling prevent context window overflow during long agent sessions?

The skill enforces modular, targeted generation SOPs and schema rules instead of dumping full AWS documentation sets into context. It utilizes targeted file globs and concise procedural boundaries, saving up to 80% of unnecessary context tokens.

Q:Does this skill require escalated root or container permissions?

No. The skill has an audited security score of 98/100. It requires only standard workspace file read and write permissions (fs_write: workspace) to synthesize configuration files and prohibits arbitrary shell execution (shell_exec: false).

Ready to equip your autonomous agent with AWS ECS Fargate Task Definitions & Service Auto-Scaling?

Copy the complete audited SKILL.md specification or download the 1-click zip bundle directly from our verified registry.

Get 1-Click Install Spec