top of page
  • Writer's pictureVaughn Geber

🌩️🔧A Comprehensive Guide to AWS ECS with Terraform🚀👨‍💻

In the era of microservices and cloud-native applications, containerization has become a fundamental aspect of modern application development. It allows developers to create lightweight, portable, and scalable applications that can be deployed and managed with ease. Amazon Web Services (AWS) provides a managed container orchestration service called Elastic Container Service (ECS) that simplifies the process of running containerized applications. In this guide, we will be focusing on using Terraform, a popular Infrastructure as Code (IaC) tool, to deploy and manage AWS ECS resources.

1. Overview of AWS ECS a. What is Amazon Elastic Container Service (ECS)?

Amazon Elastic Container Service (ECS) is a fully managed container orchestration service provided by AWS. It enables you to run, manage, and scale Docker containers on AWS infrastructure. ECS eliminates the need to install and operate your own container orchestration software, making it easy to deploy and manage containerized applications.


b. Key features of ECS

  • Managed container orchestration: Simplifies deployment, management, and scaling of containerized applications.

  • Deep integration with other AWS services: Seamless integration with services like Elastic Load Balancing, Amazon RDS, and AWS IAM.

  • Flexible deployment options: Supports both Amazon EC2 and AWS Fargate launch types for running containers.

  • Advanced scheduling capabilities: Offers advanced scheduling options for containers, such as task placement constraints and strategies. c. Benefits of using ECS

  • Simplified container management: ECS takes care of underlying infrastructure and orchestration, allowing developers to focus on application development.

  • Scalability: ECS makes it easy to scale containerized applications horizontally and vertically.

  • High availability: Supports running applications across multiple availability zones for increased reliability and fault tolerance.

  • Security: Provides robust security through integration with AWS IAM, VPCs, and security groups. d. ECS terminology: Clusters, Services, Tasks, and Task Definitions

  • Clusters: Logical grouping of resources, such as EC2 instances or Fargate containers, where ECS tasks are run.

  • Services: Manages the desired state of tasks, ensuring that the specified number of tasks is running and healthy.

  • Tasks: A single instantiation of a container or a group of containers that are treated as a single unit.

  • Task Definitions: A blueprint for running tasks that specifies container image, resources, environment variables, and other configuration options.


2. Creating an ECS Cluster with Terraform a. Overview of ECS clusters


An ECS cluster is a logical grouping of resources, such as EC2 instances or Fargate containers, where your ECS tasks are run. Clusters serve as the foundation for deploying and managing containerized applications in ECS. You can create multiple clusters within an AWS account to isolate different environments or applications.


b. Creating an ECS cluster resource

To create an ECS cluster using Terraform, you need to define a resource block for the aws_ecs_cluster resource type in your Terraform configuration file. The following is an example of a minimal configuration for creating an ECS cluster:

resource "aws_ecs_cluster" "example" {
  name = "example-cluster"
}

This configuration creates an ECS cluster named "example-cluster" using the Fargate launch type by default.


c. Example Terraform code

Here's an example of a complete Terraform configuration for creating an ECS cluster:

provider "aws" {
  region = "us-west-2"
}

resource "aws_ecs_cluster" "example" {
  name = "example-cluster"

  setting {
    name  = "containerInsights"
    value = "enabled"
  }

  tags = {
    Terraform = "true"
    Environment = "dev"
  }
}

This configuration creates an ECS cluster in the us-west-2 region, enables Container Insights for monitoring and observability, and adds tags to the cluster for better resource management.


3. Deploying a containerized application using ECS a. Creating a Docker container image

Before you can deploy a containerized application to ECS, you need to create a Docker container image for your application. This involves writing a Dockerfile that defines the base image, application dependencies, and runtime configuration for your application. Once you've created the Dockerfile, you can build the container image using the docker build command.


b. Uploading the image to Amazon ECR

After building the container image, you need to upload it to a container registry, such as Amazon Elastic Container Registry (ECR). To do this, first create a new repository in ECR using the AWS Management Console or AWS CLI. Then, tag your local container image and push it to the ECR repository using the docker tag and docker push commands, respectively.


c. Creating an ECS task definition with Terraform

An ECS task definition is a blueprint for running tasks that specifies the container image, resources, environment variables, and other configuration options. To create a task definition using Terraform, define a resource block for the aws_ecs_task_definition resource type in your Terraform configuration file.


Here's an example of a minimal task definition configuration:

resource "aws_ecs_task_definition" "example" {
  family                   = "example-family"
  network_mode             = "awsvpc"
  requires_compatibilities = ["FARGATE"]
  cpu                      = "256"
  memory                   = "512"

  container_definitions = jsonencode([{
    name  = "example-container"
    image = "aws_account_id.dkr.ecr.region.amazonaws.com/example-repo:latest"
    portMappings = [{
      containerPort = 80
      hostPort      = 80
      protocol      = "tcp"
    }]
  }])
}

This configuration creates a task definition for a Fargate task with one container using the specified container image from the ECR repository. The task requires 256 CPU units and 512 MB of memory, and exposes port 80.


d. Example Terraform code

Here's a more comprehensive example of a Terraform configuration for creating an ECS task definition:

resource "aws_ecs_task_definition" "example" {
  family                   = "example-family"
  network_mode             = "awsvpc"
  requires_compatibilities = ["FARGATE"]
  cpu                      = "256"
  memory                   = "512"

  container_definitions = jsonencode([{
    name  = "example-container"
    image = "aws_account_id.dkr.ecr.region.amazonaws.com/example-repo:latest"

    environment = [
      {
        name  = "ENV_VAR_NAME"
        value = "ENV_VAR_VALUE"
      }
    ]

    portMappings = [{
      containerPort = 80
      hostPort      = 80
      protocol      = "tcp"
    }]

    logConfiguration = {
      logDriver = "awslogs"
      options = {
        "awslogs-region"        = "us-west-2"
        "awslogs-group"         = "/ecs/example-family"
        "awslogs-stream-prefix" = "ecs"
      }
    }
  }])
}

In this example, we have added an environment variable to the container configuration and specified a log configuration to send logs to Amazon CloudWatch Logs.


4. Configuring an ECS Service with Terraform a. Overview of ECS services

An ECS service is responsible for managing the desired state of tasks, ensuring that the specified number of tasks is running and healthy. Services can also be configured with load balancers for distributing traffic across tasks, and with auto-scaling policies for adjusting the number of tasks based on demand.


b. Creating an ECS service resource

To create an ECS service using Terraform, define a resource block for the aws_ecs_service resource type in your Terraform configuration file. You need to specify the ECS cluster where the service will run and the task definition that the service will use.


Here's an example of a minimal service configuration:

resource "aws_ecs_service" "example" {
  name            = "example-service"
  cluster         = aws_ecs_cluster.example.id
  task_definition = aws_ecs_task_definition.example.arn
  desired_count   = 1

  launch_type     = "FARGATE"

  network_configuration {
    subnets = ["subnet-xxxxxxxx", "subnet-yyyyyyyy"]
  }
}

This configuration creates an ECS service named "example-service" that runs one task using the specified task definition and cluster.


c. Configuring desired task count, placement strategies, and load balancing

To configure the desired task count, you can modify the desired_count attribute in the aws_ecs_service resource block. For example, to run three tasks, you would set desired_count to 3.


To configure placement strategies and constraints, you can use the placement_strategy and placement_constraints attributes, respectively. These options allow you to control how tasks are distributed across your cluster.


To configure load balancing, you can use the load_balancer attribute in the aws_ecs_service resource block. You need to specify the target group ARN and container name and port for the load balancer to route traffic to.


d. Example Terraform code

Here's an example of a complete Terraform configuration for creating an ECS service:

resource "aws_ecs_service" "example" {
  name            = "example-service"
  cluster         = aws_ecs_cluster.example.id
  task_definition = aws_ecs_task_definition.example.arn
  desired_count   = 3

  launch_type     = "FARGATE"

  placement_strategy {
    type  = "spread"
    field = "attribute:ecs.availability-zone"
  }

  network_configuration {
    subnets = ["subnet-xxxxxxxx", "subnet-yyyyyyyy"]

    security_groups = [aws_security_group.example.id]

    assign_public_ip = true
  }

  load_balancer {
    target_group_arn = aws_lb_target_group.example.arn
    container_name   = "example-container"
    container_port   = 80
  }

  depends_on = [aws_lb_listener.example]
}

resource "aws_security_group" "example" {
  name = "example"
  # Additional security group configuration...
}

resource "aws_lb" "example" {
  name = "example"
  # Additional load balancer configuration...
}

resource "aws_lb_target_group" "example" {
  name = "example"
  # Additional target group configuration...
}

resource "aws_lb_listener" "example" {
  load_balancer_arn = aws_lb.example.arn
  # Additional listener configuration...
}

In this example, the ECS service is configured to run three tasks using the specified task definition and cluster. The service uses the FARGATE launch type and a spread placement strategy to distribute tasks evenly across availability zones. The network configuration includes subnets, security groups, and public IP assignment. The service is integrated with a load balancer by specifying the target group, container name, and container port.


Conclusion

In this guide, we have demonstrated how to create an ECS cluster, deploy a containerized application, and configure an ECS service using Terraform. By leveraging Infrastructure as Code, you can easily manage and scale your containerized applications on AWS ECS. We encourage you to explore more advanced features of ECS and Terraform to further optimize your deployment and management processes.


13 views0 comments

Комментарии


bottom of page