根据 Terraform 可用区中的足够容量过滤掉子网 ID

Filter out Subnet IDs based on sufficient capacity in availability zones in Terraform

我正在尝试部署一个 EKS 集群,一切似乎都很好,除了一个!

外观模块如下所示:

module "eks" {
  source = "../../../../infrastructure_modules/eks"

  ## EKS ##
  create_eks      = var.create_eks
  cluster_version = var.cluster_version
  cluster_name    = local.cluster_name
  vpc_id          = data.aws_vpc.this.id
  subnets         = data.aws_subnet_ids.this.ids

  # note: either pass worker_groups or node_groups
  # this is for (EKSCTL API) unmanaged node group
  worker_groups = var.worker_groups

  # this is for (EKS API) managed node group
  node_groups = var.node_groups

  ## Common tag metadata ##
  env      = var.env
  app_name = var.app_name
  tags     = local.eks_tags
  region   = var.region
}

通过以下块检索 VPC id

data "aws_vpc" "this" {
  tags = {
    Name = "tagName"
  }
}

然后用于检索 subnet_IDs,如下所示:

data "aws_subnet_ids" "this" {
  vpc_id = data.aws_vpc.this.id
}

然而,部署它会导致错误,说明:

Error: error creating EKS Cluster (data-layer-eks): UnsupportedAvailabilityZoneException: Cannot create cluster 'data-layer-eks' because us-east-1e, the targeted availability zone, does not currently have sufficient capacity to support the cluster.

这是一个众所周知的错误,即使是 EC2,任何人都可能遇到。

我可以通过简单地对子网值进行硬编码来解决这个问题,但这确实是不可取的,而且很难维护。

所以问题是,如何根据具有足够容量的可用性区域过滤掉subnet_IDs?

首先您需要收集子网及其所有属性:

data "aws_subnets" "this" {
  filter {
    name   = "vpc-id"
    values = [data.aws_vpc.this.id]
  }
}

data "aws_subnet" "this" {
  for_each = toset(data.aws_subnets.this.ids)
  id       = each.value
}

data.aws_subnet.this 现在是具有所有子网及其属性的 map(object)。您现在可以相应地按可用性区域进行过滤:

subnets = [for subnet in data.aws_subnet.this : subnet.id if subnet.availability_zone != "us-east-1e"]

如果条件对您来说更容易,您也可以按真实条件进行过滤:

subnets = [for subnet in data.aws_subnet.this : subnet.id if contains(["us-east-1a", "us-east-1b", "us-east-1c", "us-east-1d"], subnet.availability_zone)]

这取决于您的个人使用情况。