# AWS ECS Fargate Terraform

Creates a VPC spanning 2–3 Availability Zones, public and private subnets, NAT, an internet-facing Application Load Balancer, an ECS Fargate cluster/service/task definition, IAM roles, CloudWatch logs, and optional CPU target-tracking autoscaling.

## Prerequisites

- Terraform >= 1.6
- AWS CLI configured with credentials
- AWS permissions to create VPC/networking, ELB, ECS, IAM, CloudWatch, and Application Auto Scaling resources

## Deploy

```bash
cp terraform.tfvars.example terraform.tfvars
# Edit terraform.tfvars for your application and environment.

terraform init
terraform fmt -recursive
terraform validate
terraform plan -out=tfplan
terraform apply tfplan
```

When deployment completes, Terraform prints `application_url` and other resource outputs.

## Customize

Set variables in `terraform.tfvars` or pass `-var` values. Important variables:

- `aws_region`: AWS region (default `ap-south-1`)
- `project_name`, `environment`: resource naming
- `vpc_cidr`, `availability_zone_count`: network sizing
- `container_image`, `container_port`, `health_check_path`: application settings
- `cpu`, `memory`, `desired_count`: Fargate sizing and initial scale
- `single_nat_gateway`: one lower-cost NAT Gateway or one per AZ
- `enable_autoscaling`, `autoscaling_min_capacity`, `autoscaling_max_capacity`: optional scaling
- `alb_ingress_cidrs`: allowed inbound client ranges

Fargate CPU and memory combinations must be valid for AWS. Check the AWS Fargate task CPU/memory matrix before changing them.

## Application image

The default image is public NGINX and listens on port 80. For your own application, publish an image to Amazon ECR or another registry reachable by ECS, then set `container_image`. If the registry is private, configure the required image-pull permissions/secrets.

## Important production considerations

- The ALB currently exposes HTTP/80. For production, add an ACM certificate, HTTPS/443 listener, and redirect HTTP to HTTPS.
- Restrict `alb_ingress_cidrs`; the default permits the internet.
- Use immutable image tags or image digests instead of floating tags.
- The task role is intentionally empty. Add least-privilege permissions required by the application.
- Consider one NAT Gateway per AZ for stronger AZ-level resilience; NAT Gateways incur hourly and data-processing charges.
- Consider VPC endpoints for ECR, S3, CloudWatch Logs, and Secrets Manager to reduce NAT dependency/cost.
- Configure secrets through Secrets Manager or SSM Parameter Store; never put credentials in Terraform files or source control.
- This example uses the default Terraform local state. For team use, configure an encrypted, versioned S3 backend with state locking appropriate to your Terraform version and your organization's standards.
- Review AWS costs before applying. NAT Gateways and ALBs incur ongoing charges.

## Destroy

```bash
terraform destroy
```

Review the plan carefully before destroying shared or production resources.
