How to create EFS in Multi-AZ with Terraform

7.5k views Asked by At

I have launched two EC2 instances in two availability zones and I need to mount the EFS in both the instances using Terraform.

resource "aws_efs_file_system" "magento-efs" {
   creation_token = "efs-demo"
   performance_mode = "generalPurpose"
   throughput_mode = "bursting"
   encrypted = "true"
 tags = {
     Name = "Magento-EFS"
   }
 }

resource "aws_efs_mount_target" "efs-mount" {
   file_system_id  = "${aws_efs_file_system.magento-efs.id}"
   subnet_id = "${aws_subnet.public_subnet.0.id}"
   security_groups = ["${aws_security_group.efs-sg.id}"]
}

Using the above code I am able to create EFS in us-east-1a. I need to make it available in both us-east-1a and us-east-1b.

3

There are 3 answers

5
StephenKing On BEST ANSWER

You just need to add another mount target in a subnet in AZ us-east-1b:

resource "aws_efs_mount_target" "efs-mount-b" {
   file_system_id  = "${aws_efs_file_system.magento-efs.id}"
   subnet_id = "${aws_subnet.public_subnet.1.id}"
   security_groups = ["${aws_security_group.efs-sg.id}"]
}

More elegant (using count dependent on the number of subnets):

resource "aws_efs_mount_target" "efs-mount" {
   count = "length(aws_subnet.public_subnet.*.id)"
   file_system_id  = "${aws_efs_file_system.magento-efs.id}"
   subnet_id = "${element(aws_subnet.public_subnet.*.id, count.index)}"
   security_groups = ["${aws_security_group.efs-sg.id}"]
}
0
Super Kai - Kazuya Ito On

I use the terraform version 0.14.10. This will work.

resource "aws_efs_mount_target" "efs-mount-a" {
   file_system_id  = aws_efs_file_system.magento-efs.id
   subnet_id = aws_subnet.public_subnet.0.id
   security_groups = [aws_security_group.efs-sg.id]
}

resource "aws_efs_mount_target" "efs-mount-b" {
   file_system_id  = aws_efs_file_system.magento-efs.id
   subnet_id = aws_subnet.public_subnet.1.id
   security_groups = [aws_security_group.efs-sg.id]
}
0
Matías Fernández On

Based on response from Kai - Kazuya Ito I configure it with Terraform v1.3.7 and ecs_vpc module reference. Very similar but little differences.

resource "aws_efs_mount_target" "shared_ecs_efs_0" {
  file_system_id  = aws_efs_file_system.shared_ecs_efs.id
  subnet_id       = module.ecs_vpc.private_subnets[0]
  security_groups = [aws_security_group.efs_sg.id]
}

resource "aws_efs_mount_target" "shared_ecs_efs_1" {
  file_system_id  = aws_efs_file_system.shared_ecs_efs.id
  subnet_id       = module.ecs_vpc.private_subnets[1]
  security_groups = [aws_security_group.efs_sg.id]
}