Bài toán ở đây là client sẽ đưa ra cho chúng ta 1 list subnet. Mục đích của chúng ta là chỉ lựa ra mỗi Zone chúng ta sẽ lấy ra 1 subnet để sử dụng để cài đặt hệ thông:
The Solution:
- Check the AZ of each subnet: We’ll fetch the AZ for each subnet.
- Only apply EFS Mount Targets to subnets in different AZs: Ensure we create EFS Mount Targets in unique AZs.
Step-by-Step Example
- List of Subnets: Let’s assume you provide a list of subnets like this:
variable "eks_private_subnets" {
type = list(string)
default = ["subnet-abc123", "subnet-def456", "subnet-ghi789"]
}
2. Fetch Subnet Information: You want to check the availability zone of each subnet. To do this, we use a data "aws_subnet" block to get the AZ of each subnet.
3. Create EFS Mount Targets in Different AZs: Now, we will apply the EFS Mount Target only in subnets that are in unique AZs.
# Fetch the AZ of each subnet
data "aws_subnet" "subnets" {
for_each = toset(var.eks_private_subnets)
id = each.value
}
# Extract the AZ for each subnet
locals {
subnet_azs = { for s in data.aws_subnet.subnets : s.id => s.availability_zone }
}
# Create EFS Mount Targets in different AZs only
resource "aws_efs_mount_target" "efs_mount_target" {
count = length(distinct(local.subnet_azs)) # Only count unique AZs
file_system_id = aws_efs_file_system.efs_file_system.id
subnet_id = element(var.eks_private_subnets, count.index)
security_groups = [aws_security_group.efs_allow_access.id]
}
Breakdown:
data "aws_subnet": This block fetches the AZ for each subnet invar.eks_private_subnets. It returns the AZ (likeus-east-1a,us-east-1b, etc.).locals { subnet_azs = ... }: We create a local mapsubnet_azsto store the AZ for each subnet. It looks something like this:
{
"subnet-abc123" = "us-east-1a",
"subnet-def456" = "us-east-1b",
"subnet-ghi789" = "us-east-1a"
}
3. resource "aws_efs_mount_target": In this block, we create an EFS Mount Target. The count is determined by the number of unique AZs in local.subnet_azs using distinct(). So, if two subnets are in the same AZ, it will only count once.
- If
subnet-abc123andsubnet-ghi789are in the same AZ (us-east-1a), then only 1 EFS Mount Target will be created for AZus-east-1aand another for AZus-east-1b.