Search code examples
amazon-web-servicesamazon-ec2terraformamazon-efsmulti-az

How to create EFS in Multi-AZ with Terraform


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.


Solution

  • 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}"]
    }