AWS ECS Fargate - Terraform Configurations
provider "aws" {
region = var.aws_region
}
resource "aws_ecs_cluster" "cluster" {
name = "nginx-cluster"
}
resource "aws_iam_role" "ecs_task_execution_role" {
name = "ecsTaskExecutionRole"
assume_role_policy = jsonencode({
Version = "2012-10-17",
Statement = [{
Effect = "Allow",
Principal = {
Service = "ecs-tasks.amazonaws.com"
},
Action = "sts:AssumeRole"
}]
})
managed_policy_arns = [
"arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy",
"arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"
]
}
resource "aws_ecs_task_definition" "nginx" {
family = "nginx"
network_mode = "awsvpc"
requires_compatibilities = ["FARGATE"]
cpu = 256
memory = 512
execution_role_arn = aws_iam_role.ecs_task_execution_role.arn
task_role_arn = aws_iam_role.ecs_task_execution_role.arn
container_definitions = jsonencode([{
name = "nginx"
image = "nginx:latest"
essential = true
logConfiguration = {
logDriver = "awslogs"
options = {
"awslogs-group" = "/ecs/nginx"
"awslogs-region" = var.aws_region
"awslogs-stream-prefix" = "ecs"
}
}
}])
}
resource "aws_ecs_service" "nginx" {
name = "nginx"
cluster = aws_ecs_cluster.cluster.id
task_definition = aws_ecs_task_definition.nginx.arn
desired_count = 1
network_configuration {
subnets = var.subnet_ids
security_groups = [aws_security_group.allow_rdp.id]
assign_public_ip = true
}
enable_execute_command = true
}
resource "aws_security_group" "allow_tls" {
name = "terraform-firewall"
description = "Managed from Terraform"
vpc_id = var.vpc_id
}
resource "aws_vpc_security_group_ingress_rule" "allow_http_ipv4" {
security_group_id = aws_security_group.allow_tls.id
cidr_ipv4 = ["0.0.0.0/0"]
from_port = "80"
ip_protocol = "tcp"
to_port = "80"
}
resource "aws_vpc_security_group_egress_rule" "allow_all_traffic_ipv4" {
security_group_id = aws_security_group.allow_tls.id
cidr_ipv4 = ["0.0.0.0/0"]
ip_protocol = "-1" # semantically equivalent to all ports
}
output "cluster_id" {
description = "The ID of the ECS cluster"
value = aws_ecs_cluster.cluster.id
}
output "task_definition_arn" {
description = "The ARN of the ECS task definition"
value = aws_ecs_task_definition.nginx.arn
}
output "service_name" {
description = "The name of the ECS service"
value = aws_ecs_service.nginx.name
}