AWS

Simple AWS ECS example based on Teraform

CK CK 3788 
Created at  
986 0 0

AWS ECS (Elastic Container Service) is a fully managed container orchestration service that allows you to run and manage Docker containers at scale on AWS. It offers benefits like automated deployments, scaling, load balancing, and security, making it easy to run and manage containerized applications without the complexities of managing infrastructure. 
 

Here's a simple Terraform example to deploy an ECS (Elastic Container Service) cluster on AWS, complete with an ECS cluster, a task definition, and a service running a container. This configuration assumes you have Docker images already available in Amazon ECR (Elastic Container Registry) or another container registry.

 

Example: Simple ECS Cluster and Service

This example will:

  1. Create an ECS Cluster.
  2. Define an ECS Task Definition for a container.
  3. Launch an ECS Service that will run the container.

 

Prerequisites

Make sure you have the following:

  • An Amazon ECR repository with a Docker image pushed to it.
  • An AWS IAM role with permissions for ECS and EC2 (required for the ECS tasks).

 

Step 1: Define Variables (variables.tf)

Define variables for flexibility. This example assumes the Docker image URI is stored in Amazon ECR.

variable "region" {
  default     = "us-west-2"
  description = "AWS region"
}

variable "ecs_cluster_name" {
  default     = "simple-ecs-cluster"
  description = "Name of the ECS cluster"
}

variable "ecr_image_uri" {
  description = "ECR URI of the Docker image"
}

variable "task_cpu" {
  default     = 256
  description = "CPU units for the ECS task"
}

variable "task_memory" {
  default     = 512
  description = "Memory for the ECS task"
}

 

Step 2: Create an ECS Cluster and ECS Service (main.tf)

provider "aws" {
  region = var.region
}

# ECS Cluster
resource "aws_ecs_cluster" "ecs_cluster" {
  name = var.ecs_cluster_name
}

# IAM Role for ECS Task
resource "aws_iam_role" "ecs_task_execution_role" {
  name = "ecsTaskExecutionRole"

  assume_role_policy = jsonencode({
    Version = "2012-10-17",
    Statement = [
      {
        Action = "sts:AssumeRole",
        Effect = "Allow",
        Principal = {
          Service = "ecs-tasks.amazonaws.com"
        }
      }
    ]
  })
}

resource "aws_iam_role_policy_attachment" "ecs_task_execution_role_policy" {
  role       = aws_iam_role.ecs_task_execution_role.name
  policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"
}

# ECS Task Definition
resource "aws_ecs_task_definition" "ecs_task" {
  family                   = "simple-task"
  cpu                      = var.task_cpu
  memory                   = var.task_memory
  network_mode             = "awsvpc"
  requires_compatibilities = ["FARGATE"]
  execution_role_arn       = aws_iam_role.ecs_task_execution_role.arn

  container_definitions = jsonencode([{
    name      = "my-simple-container"
    image     = var.ecr_image_uri
    cpu       = var.task_cpu
    memory    = var.task_memory
    essential = true
    portMappings = [
      {
        containerPort = 80
        hostPort      = 80
        protocol      = "tcp"
      }
    ]
  }])
}

# ECS Service
resource "aws_ecs_service" "ecs_service" {
  name            = "simple-ecs-service"
  cluster         = aws_ecs_cluster.ecs_cluster.id
  task_definition = aws_ecs_task_definition.ecs_task.arn
  desired_count   = 1
  launch_type     = "FARGATE"

  network_configuration {
    subnets         = ["<subnet-id-1>", "<subnet-id-2>"]  # Replace with your VPC subnets
    security_groups = ["<security-group-id>"]  # Replace with a security group that allows inbound traffic
    assign_public_ip = true
  }
}

 

Step 3: Provide the terraform.tfvars File

Create a terraform.tfvars file to set the values for required variables, especially ecr_image_uri.

ecr_image_uri = "YOUR_ECR_IMAGE_URI"
region        = "us-west-2"

 

Step 4: Run Terraform Commands

  1. Initialize Terraform:

    terraform init
    
  2. Plan the infrastructure:

    terraform plan
    
  3. Apply the configuration:

    terraform apply
    

    Type yes to confirm.

 

Summary

  • aws_ecs_cluster: Creates the ECS cluster.
  • aws_ecs_task_definition: Defines the Docker container configuration.
  • aws_ecs_service: Runs the task within the ECS cluster using Fargate.

This setup creates a simple ECS service that uses a single container. For production setups, consider load balancers, autoscaling, and additional security configurations.

Tags AWS ECS Teraform AWS Teraform Teraform Teraform Example Facebook X
Comments 0
Similar posts
  1. AWS Lambda Example based on Teraform
    899
  2. Teraform from the scratch
    1,352
  1. Understanding Amazon Bedrock Agent for AI-based ChatBot
    642
  2. Media sharing service architecture in AWS
    10,364
  3. Enterprise Data Lake Architecture based on AWS
    10,403
  4. "502 Bad Gateway" Error easy to happen at the combination of nginx and node.js in AWS Elastic Beanstalk
    10,485
  5. How to Set Up and Deploy Containerized Applications with AWS ECS
    10,672
  6. Power of Containerized Deployment with AWS ECS
    10,594
  7. FAISS Already Does ANN... So Why Do Top Teams Still Pay for SageMaker?
    307
  8. Recommended Vector DB Structure for Amazon Bedrock Integration
    388
  9. Product Marketing & Recommendation Architecture in AWS for e-commerce website
    10,733
  10. What cause a 502 bad gateway error in AWS environment?
    443
  11. Building an AWS SAM(Serverless Application Model) Project
    897
  12. Teraform from the scratch
    1,352
  13. Check incomplete multipart uploads if AWS S3 storage size is abnormally big huge compared to the origin storage
    11,597
  14. Importing a wild card domain SSL certificate into AWS Certificate Manager
    10,348
  15. AWS Lambda Example based on Teraform
    899
  16. Web front-end architecture in AWS for e-commerce website
    364
  17. Web Application Hosting provides the reliable, scalable, secure, and high-performance infrastructure
    10,614
  18. Time series processing architecture in AWS
    10,557
  19. Synchronous online gaming architecutre in AWS - Highly Available, Scalable & Elastic to support Millions of Players
    10,414
  20. Secure and Scalable LAMP Service Architecture in AWS
    10,658
  21. Live streaming / Static Content & Media Service based on AWS
    10,651
  22. Large scale messenger service architecture in AWS - Slack case study
    11,673
  23. Large scale computing based on huge data sets in AWS
    10,607
  24. Image Moderation Chatbot - a serverless chatbot on AWS that monitors chat channels and removes images suggestive or explicit image
    10,423
  25. Financial services grid computing in AWS
    10,354
  26. File synchronization service architecture in AWS
    10,375
  27. Fault Tolerance & High Availability based on multi Availability zones in AWS
    10,800
  28. Disaster recovery solution in AWS for local applications
    11,176
  29. Content Distribution for VOD streaming services in AWS
    10,354
  30. Checkout service architecture in AWS for e-commerce website
    11,007
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    27
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    24
  3. How do I create animated background for Google Meet?
    19,729
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    217
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    86
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    153
  7. Array of arguments passed to script in PHP
    85
  8. Invalid Auction Storms in Ad Tech
    93
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    198
  10. The Two Clocks of Ad Server Architecture
    63
  11. Frequency Cap Architecture Overview
    509
  12. Collecting Proof-of-Play from 100,000 Screens
    141
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    280
  14. What is RedisVL?
    105
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    224
  16. TPU & GPU Cluster Management Tools
    234
  17. The Concept of Scaffolding in AI Agents
    222
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    576
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    253
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    328
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    197
  22. Machine Learning: Training vs. Ranking
    213
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    217
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    189
  25. Designing a Data Curation System Around a Vector Database
    215
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    229
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    649
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    185
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    207
  30. Understanding Data Lineage
    252