如何使用 Terraform 在多可用区中创建 EFS

How to create EFS in Multi-AZ with Terraform

我在两个可用区启动了两个 EC2 实例,我需要使用 Terraform 在两个实例中安装 EFS。

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

使用上面的代码,我能够在 us-east-1a 中创建 EFS。我需要让它在 us-east-1a 和 us-east-1b 中可用。

您只需要在 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}"]
}

更优雅(根据子网数量使用count):

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

我使用的是 terraform 版本 0.14.10。这会起作用。

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