Run Container on AWS ECs service using Terraform
Amazon Elas c Container Service (ECS) is a fully managed container orchestra on service
that simplifies the deployment, management, and scaling of containerized applica ons. It
deeply integrates with the AWS ecosystem, offering an easy-to-use solu on for running
container workloads in the cloud and on-premises via Amazon ECS Anywhere.
Here's a breakdown of key aspects of AWS ECS:
Core Concepts:
Containers: ECS is designed to run Docker containers.
Tasks: A task is the instan a on of a task defini on within a cluster. It represents one
or more containers defined in a task defini on.
Task Defini on: A JSON file that describes one or more containers that form your
applica on. It specifies details like Docker images, resource requirements (CPU,
memory), networking, and volume mounts.
Services: A service allows you to run and maintain a specified number of instances of
a task defini on simultaneously in an ECS cluster. If any of your tasks fail or stop, the
ECS service scheduler launches another instance to replace it and maintain the
desired count.
Clusters: A logical grouping of container instances (EC2 instances) or Fargate
infrastructure where your tasks run.
Launch Types:
o EC2 Launch Type: You provision and manage the underlying EC2 instances
that run your containers. This gives you more control over the infrastructure.
o Fargate Launch Type: AWS manages the underlying infrastructure for you.
You specify the CPU and memory requirements for your tasks, and Fargate
handles the provisioning and scaling of the compute resources. This is a
serverless op on for running containers.
o External Launch Type (ECS Anywhere): Allows you to register your own on-
premises servers or virtual machines as part of an ECS cluster and run
containers on them, managed by the AWS control plane.
Container Agent: Runs on each container instance within your cluster. It sends
informa on about the instance's current state to ECS and starts and stops containers
as directed by ECS.
Benefits of Using Amazon ECS:
Simplified Container Management: ECS takes away the complexity of managing
container orchestra on infrastructure.
Scalability: Easily scale your containerized applica ons up or down based on
demand. ECS integrates with AWS Auto Scaling.
High Availability: ECS can automa cally recover unhealthy containers and distribute
tasks across mul ple Availability Zones.
Security: Integrates with AWS security services like IAM for granular permissions and
VPC for network isola on. Fargate provides inherent isola on by running each task in
its own kernel.
Cost-Effec veness: Pay-as-you-go pricing with op ons like Fargate and EC2 Spot
Instances can help op mize costs. ECS itself has no addi onal charge; you pay for the
underlying AWS resources.
Integra on with AWS Services: Seamlessly integrates with other AWS services like
Elas c Load Balancing (ELB), Amazon ECR (Elas c Container Registry), AWS
CloudWatch, and AWS IAM.
Choice of Launch Types: Flexibility to choose the launch type that best suits your
needs for control, management overhead, and cost.
ECS Anywhere: Extends the benefits of ECS to on-premises environments for hybrid
deployments.
Use Cases:
Microservices Architectures: ECS is well-suited for deploying and managing
distributed microservices.
Web Applica ons: Easily scale and run web applica ons with high availability.
Batch Processing: Run batch compu ng workloads efficiently.
Machine Learning: Train and run ML models without managing infrastructure using
ECS with Fargate.
Applica on Moderniza on: Migrate monolithic applica ons to containerized
microservices.
Pricing:
There is no addi onal charge for using Amazon ECS. You pay for the underlying AWS
resources used to run your containerized applica ons. Pricing varies based on the launch
type:
EC2 Launch Type: You pay for the EC2 instances you provision. You can leverage EC2
On-Demand Instances, Reserved Instances, or Spot Instances to op mize costs. You
also pay for any EBS volumes you use for storage.
Fargate Launch Type: You pay for the vCPU and memory resources consumed by
your tasks, from the me the container image is downloaded un l the task
terminates. Pricing is per second with a one-minute minimum. You also pay for any
ephemeral storage beyond the default 20GB provided per task. Different opera ng
systems (Linux, Windows) and CPU architectures (x86, ARM) have different pricing.
Fargate Spot offers discounted pricing for interrup ble workloads.
ECS Anywhere: You pay an hourly rate for each on-premises instance registered with
and managed by ECS Anywhere. You are also responsible for the cost of your on-
premises infrastructure.
AWS Outposts: Pricing includes the cost of the Outposts infrastructure, including
compute, storage, and networking resources, over a 3-year term with different
payment op ons (All Upfront, Par al Upfront, No Upfront).
Steps
Create main.tf file and add following
main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "us-east-1"
}
# Create VPC
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
}
resource "aws_subnet" "subnet" {
vpc_id = aws_vpc.main.id
cidr_block = "10.0.1.0/24"
availability_zone = "us-east-1a"
}
resource "aws_internet_gateway" "igw" {
vpc_id = aws_vpc.main.id
}
resource "aws_security_group" "ecs_sg" {
vpc_id = aws_vpc.main.id
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
# ECS Cluster
resource "aws_ecs_cluster" "main" {
name = "my-ecs-cluster"
}
# IAM Role for ECS task execution
resource "aws_iam_role" "ecs_task_exec_role" {
name = "ecsTaskExecutionRole"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Action = "sts:AssumeRole"
Principal = {
Service = "ecs-tasks.amazonaws.com"
}
Effect = "Allow"
}]
})
}
resource "aws_iam_role_policy_attachment" "ecs_task_exec_policy" {
role = aws_iam_role.ecs_task_exec_role.name
policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"
}
# ECS Task Definition
resource "aws_ecs_task_definition" "nginx" {
family = "nginx-task"
network_mode = "awsvpc"
requires_compatibilities = ["FARGATE"]
cpu = "256"
memory = "512"
execution_role_arn = aws_iam_role.ecs_task_exec_role.arn
container_definitions = jsonencode([
{
name = "nginx"
image = "nginx:latest"
portMappings = [
{
containerPort = 80
hostPort = 80
}
]
}
])
}
# ECS Service
resource "aws_ecs_service" "nginx" {
name = "nginx-service"
cluster = aws_ecs_cluster.main.id
task_definition = aws_ecs_task_definition.nginx.arn
launch_type = "FARGATE"
desired_count = 1
network_configuration {
subnets = [aws_subnet.subnet.id]
security_groups = [aws_security_group.ecs_sg.id]
assign_public_ip = true
}
terraform init
Ini alizes the working directory containing Terraform configura on files.
Downloads the required provider plugins (e.g., AWS).
Sets up the backend if using remote state.
Must be run once before any other commands.
terraform plan
Generates an execu on plan, showing what Terraform will do without actually applying
changes.
Compares your code with the current infrastructure state.
Highlights which resources will be created, changed, or destroyed.
terraform apply
Applies the changes required to reach the desired state defined in your . files.
Check Cluster Created:
Click on Cluster and check nginx-service :