Skip to content

Instantly share code, notes, and snippets.

@gnumilanix
Last active February 23, 2023 03:17
Show Gist options
  • Save gnumilanix/9d906f49774878c3637b7fdb45265eea to your computer and use it in GitHub Desktop.
Save gnumilanix/9d906f49774878c3637b7fdb45265eea to your computer and use it in GitHub Desktop.
Mounting EFS volume to ECS task (EC2) with Terraform

This gist provides a sample terraform configuration to use EFS volume in ECS task running on EC2:

  1. Create a security group A for service B
  2. Create a security group for EFS to allow B
  3. Create EFS file system C and mount target on multiple subnets
  4. Create ECS task D with EFS volume C
  5. Create ECS service for ECS task C with security group A
locals {
..
subnets = [aws_subnet.a.id, aws_subnet.b.id, aws_subnet.c.id]
}
resource "aws_efs_file_system" "elasticsearch_data" {
creation_token = "elasticsearch-data"
performance_mode = "maxIO"
tags = {
Name = "elasticsearch-data"
}
}
resource "aws_efs_mount_target" "elasticsearch_data" {
count = length(local.subnets)
file_system_id = aws_efs_file_system.elasticsearch_data.id
subnet_id = local.subnets.subnets[count.index]
security_groups = [aws_security_group.efs.id]
}
[
{
...,
"mountPoints": [
{
"sourceVolume": "elasticdata",
"containerPath": "/usr/share/elasticsearch/data"
}
],
...
}
]
resource "aws_security_group" "elasticsearch" {
description = "Elasticsearch rules"
name = "Elasticsearch rules"
tags = {
Name = "Elasticsearch",
CreatedBy = "Terraform"
}
vpc_id = aws_vpc.default.id
ingress {
cidr_blocks = [
aws_vpc.default.cidr_block
]
description = "Elassticsearch Binary"
from_port = 9300
protocol = "tcp"
to_port = 9300
}
ingress {
cidr_blocks = [
aws_vpc.default.cidr_block
]
description = "Elassticsearch HTTP"
from_port = 9200
protocol = "tcp"
to_port = 9200
}
egress {
cidr_blocks = [
"0.0.0.0/0"
]
from_port = 0
protocol = "-1"
to_port = 0
}
}
resource "aws_security_group" "efs" {
name = "EFS rules"
description = "EFS rules"
vpc_id = aws_vpc.default.id
tags = {
Name = "EFS",
CreatedBy = "Terraform"
}
ingress {
security_groups = [aws_security_group.elasticsearch.id]
from_port = 2049
to_port = 2049
protocol = "tcp"
}
egress {
security_groups = [aws_security_group.elasticsearch.id]
from_port = 0
to_port = 0
protocol = "-1"
}
}
resource "aws_ecs_service" "elasticsearch" {
name = "elasticsearch"
..
task_definition = aws_ecs_task_definition.elasticsearch.arn
..
network_configuration {
assign_public_ip = false
security_groups = var.elasticsearch_security_groups
subnets = var.subnets
}
..
}
resource "aws_ecs_task_definition" "elasticsearch" {
container_definitions = file("./elasticsearch.json")
family = "elasticsearch"
..
network_mode = "awsvpc"
volume {
name = "elasticdata"
efs_volume_configuration {
file_system_id = aws_efs_file_system.elasticsearch_data.id
}
}
requires_compatibilities = [
"EC2"
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment