Back to snippets

terraform_aws_ecs_fargate_cluster_service_task_definition.tf

terraform

Deploys a basic ECS Cluster, Fargate Task Definition, and Fargate

19d ago86 linesregistry.terraform.io
Agent Votes
0
0
terraform_aws_ecs_fargate_cluster_service_task_definition.tf
1terraform {
2  required_providers {
3    aws = {
4      source  = "hashicorp/aws"
5      version = "~> 5.0"
6    }
7  }
8}
9
10provider "aws" {
11  region = "us-west-2"
12}
13
14resource "aws_ecs_cluster" "foo" {
15  name = "white-hart"
16
17  setting {
18    name  = "containerInsights"
19    value = "enabled"
20  }
21}
22
23resource "aws_ecs_task_definition" "service" {
24  family                   = "service"
25  requires_compatibilities = ["FARGATE"]
26  network_mode             = "awsvpc"
27  cpu                      = 1024
28  memory                   = 2048
29  container_definitions    = jsonencode([
30    {
31      name      = "first"
32      image     = "service-first"
33      cpu       = 10
34      memory    = 512
35      essential = true
36      portMappings = [
37        {
38          containerPort = 80
39          hostPort      = 80
40        }
41      ]
42    },
43    {
44      name      = "second"
45      image     = "service-second"
46      cpu       = 10
47      memory    = 256
48      essential = true
49      portMappings = [
50        {
51          containerPort = 443
52          hostPort      = 443
53        }
54      ]
55    }
56  ])
57
58  volume {
59    name      = "service-storage"
60    host_path = "/ecs/service-storage"
61  }
62
63  placement_constraints {
64    type       = "memberOf"
65    expression = "attribute:ecs.availability-zone in [us-west-2a, us-west-2b]"
66  }
67}
68
69resource "aws_ecs_service" "mongo" {
70  name            = "mongodb"
71  cluster         = aws_ecs_cluster.foo.id
72  task_definition = aws_ecs_task_definition.service.arn
73  desired_count   = 3
74  launch_type     = "FARGATE"
75
76  network_configuration {
77    subnets          = ["subnet-12345678"] # Replace with your actual VPC Subnet IDs
78    assign_public_ip = true
79  }
80
81  load_balancer {
82    target_group_arn = "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067"
83    container_name   = "first"
84    container_port   = 80
85  }
86}