Create an Amazon ECS Cluster Using Terraform

In this article, we’ll explore how to create an AWS ECS (Elastic Container Service) cluster using Terraform, a popular infrastructure as code tool.

Create an Amazon ECS Cluster Using Terraform 1

What is Amazon ECS?

Amazon ECS is a fully managed container orchestration service that allows you to run, stop, and manage Docker containers on a cluster. It takes care of the underlying infrastructure, including the provisioning and scaling of resources, allowing you to focus on your applications. ECS is designed to work seamlessly with other AWS services, providing a comprehensive container management solution.

Architecture of Amazon ECS

image 3

Amazon ECS (Elastic Container Service) architecture comprises several key components that work together to facilitate the deployment and management of containerized applications. Here’s a brief overview:

  1. ECS Clusters:
    • Logical groupings of EC2 instances, AWS Fargate containers, and other resources where containerized applications are deployed.
  2. Container Instances:
    • EC2 instances or AWS Fargate containers within a cluster that host containers and are registered with ECS.
  3. Task Definitions:
    • Blueprints specifying parameters for containers, including Docker image, CPU, memory, and network settings.
  4. Tasks:
    • Instantiation of a task definition, representing the execution of containers on a container instance within the ECS cluster.
  5. Services:
    • Manage continuous running and scaling of tasks, ensuring desired task count, and handling lifecycle management.
  6. Scheduler:
    • ECS component responsible for placing tasks on EC2 instances or AWS Fargate containers, considering resource requirements and availability.
  7. Amazon ECS Agent:
    • Runs on each EC2 instance, facilitating communication with ECS, receiving tasks, and managing container lifecycle.
  8. Elastic Load Balancing (ELB):
    • Distributes incoming traffic across multiple containers within an ECS service for high availability and efficiency.
  9. Amazon CloudWatch:
    • Integrated for monitoring, logging, and tracking metrics to provide insights into ECS task and container performance.
  10. Amazon ECR (Elastic Container Registry):
    • Fully-managed Docker container registry integrated with ECS for secure storage, management, and deployment of container images.
  11. Container Image:
    • A lightweight, standalone, executable package that includes everything needed to run a piece of software. Managed and stored in registries like Amazon ECR.
  12. Elastic Network Interface (ENI):
    • Virtual network interface that allows containers to communicate with the network and other resources in the ECS cluster.
  13. VPC (Virtual Private Cloud):
    • A logically isolated section of the AWS Cloud where ECS clusters and other AWS resources operate, providing control over the network environment.
  14. AWS Fargate:
    • A serverless compute engine for containers that abstracts away infrastructure management, allowing for simplified deployment and operation of containers.
  15. EC2 Instances:
    • Virtual servers in the cloud, forming the foundation of ECS clusters. They host containers when using the EC2 launch type.

Prerequisites

Before you start creating, you’ll need the following:

Once you have finished with the prerequisites, it is time to start writing the code to create an ECS cluster.

Steps for Deploying AWS ECS Using Terraform

File Structure:

Create an Amazon ECS Cluster Using Terraform 2

Step#1:Create provider.tf file

The provider.tf file in Terraform is a configuration file that specifies the cloud provider and its corresponding plugin that Terraform will use to manage resources in that provider.

provider.tf
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}
provider "aws" {
  region = "ap-south-1"
  profile = "default"
}
Create an Amazon ECS Cluster Using Terraform 3

Step#2:Create a virtual private cloud in AWS using Terraform

The next step is to create a virtual private cloud in AWS using the aws_vpc resource.

Let’s name it vpc.tf

vpc.tf
resource "aws_default_vpc" "ecs-vpc" {
  tags = {
    Name = "ECS-VPC"
  }
}

resource "aws_default_subnet" "ecs_az1" {
  availability_zone = "ap-south-1a"

  tags = {
    Name = "Default subnet for ap-south-1a"
  }
}

resource "aws_default_subnet" "ecs_az2" {
  availability_zone = "ap-south-1b"

  tags = {
    Name = "Default subnet for ap-south-1b"
  }
}

resource "aws_default_subnet" "ecs_az3" {
  availability_zone = "ap-south-1c"

  tags = {
    Name = "Default subnet for ap-south-1c"
  }
}
Create an Amazon ECS Cluster Using Terraform 4

Step#3:Create an IAM role by adding iam.tf file

To create an IAM role named “ecsTaskExecutionRole,” you can create an iam.tf file with the following content:

 iam.tf
resource "aws_iam_role" "ecsTaskExecutionRole" {
  name               = "ecsTaskExecutionRole"
  assume_role_policy = data.aws_iam_policy_document.assume_role_policy.json
}

data "aws_iam_policy_document" "assume_role_policy" {
  statement {
    actions = ["sts:AssumeRole"]
    principals {
      type        = "Service"
      identifiers = ["ecs-tasks.amazonaws.com"]
    }
  }
}
Create an Amazon ECS Cluster Using Terraform 5

Step#4:Create ecr.tf file

This Terraform file manages AWS ECR repositories for storing container images.

ecr.tf
resource "aws_ecr_repository" "my_first_ecr_repo" {
  name = "my-first-ecr-repo"
  tags = {
    Name="latest_ecr"
  }
}

Save this code in a file named ecr.tf in your Terraform project directory. This file will contain the configuration for managing your AWS ECR repositories.

Create an Amazon ECS Cluster Using Terraform 6

Step#5:Create taskdefination.tf file

This Terraform file defines an AWS ECS task definition for a containerized application.

taskdefination.tf
resource "aws_ecs_task_definition" "my_first_task" {
  family                    = "my-first-task"
  container_definitions     = <<DEFINITION
[
  {
    "name": "my-first-task",
    "image": "${aws_ecr_repository.my_first_ecr_repo.repository_url}",
    "essential": true,
    "portMappings": [
      {
        "containerPort": 80,
        "hostPort": 80
      }
    ],
    "memory": 512,
    "cpu": 256,
    "networkMode": "awsvpc"
  }
]
  DEFINITION
  requires_compatibilities  = ["EC2"]
  network_mode              = "awsvpc"
  memory                    = 512
  execution_role_arn        = aws_iam_role.ecsTaskExecutionRole.arn
  cpu                       = 256
}
Create an Amazon ECS Cluster Using Terraform 7

Step#6:Create ecs.tf file

This Terraform file manages AWS ECS resources such as clusters, services, and tasks.

ecs.tf
resource "aws_ecs_cluster" "my_cluster" {
  name = "my-ecs-cluster"
}

Save this code in a file named ecs.tf in your Terraform project directory. This file will contain the configuration for managing your AWS ECS resources.

Create an Amazon ECS Cluster Using Terraform 8

Step#7:Create service.tf file

This Terraform file manages AWS ECS services for deploying and managing containerized applications.

service.tf
resource "aws_ecs_service" "my_first_services" {
  name              = "gft-test-first-services"
  cluster           = aws_ecs_cluster.my_cluster.id
  task_definition   = aws_ecs_task_definition.my_first_task.arn
  launch_type       = "EC2"
  scheduling_strategy = "REPLICA"
  desired_count     = 1

  network_configuration {
    subnets          = [aws_default_subnet.ecs_az1.id]
    assign_public_ip = false
  }
}

Save this code in a file named service.tf in your Terraform project directory. This file will contain the configuration for managing your AWS ECS services.

Create an Amazon ECS Cluster Using Terraform 9

Step#8:Create an Amazon ECS Cluster Using Terraform

  • terraform init

The terraform init the command is used to initialize a new or existing Terraform configuration. This command downloads the required provider plugins and sets up the backend for storing state.

Create an Amazon ECS Cluster Using Terraform 10
  • terraform plan

The terraform plan the command is used to create an execution plan for the Terraform configuration. This command shows what resources Terraform will create, modify, or delete when applied.

Create an Amazon ECS Cluster Using Terraform 11
Create an Amazon ECS Cluster Using Terraform 12
  • terraform apply

The terraform apply the command is used to apply the Terraform configuration and create or modify resources in the target environment.

Create an Amazon ECS Cluster Using Terraform 13
  • terraform destroy

All the resources created will be destroy by using this command.

Step#9:Verify Result on AWS Console

Create an Amazon ECS Cluster Using Terraform 14
Create an Amazon ECS Cluster Using Terraform 15
Create an Amazon ECS Cluster Using Terraform 16

Conclusion

In conclusion, Terraform provides a powerful and efficient way to manage Amazon ECS clusters. By defining infrastructure as code, users can easily create, update, and manage ECS clusters in a repeatable and automated manner. This approach ensures consistency, reduces manual errors, and streamlines the deployment process for containerized applications on AWS ECS.

Reference:-

For reference visit the official website .

Any queries pls contact us @Fosstechnix.com.

Related Articles:

How to Create VPC in AWS using Terraform

How to Create Amazon ECS Cluster

Deploy Node.js app on Amazon ECS and Fargate

Akash Bhujbal

Hey, I am Akash Bhujbal, I am an aspiring DevOps and Cloud enthusiast who is eager to embark on a journey into the world of DevOps and Cloud. With a strong passion for technology and a keen interest in DevOps and Cloud based solutions, I am driven to learn and contribute to the ever-evolving field of DevOps and Cloud.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share via
Copy link
Powered by Social Snap