对于 AWS 区域内的每个可用区

For Each availability zone within an AWS region

我正在尝试使用 Terraform 在一个区域内的可用性区域内创建一个子网。我有以下代码,但在让我的子网读入该区域的可用区时遇到了一些问题。下面也是我的错误。

data "aws_availability_zones" "azs" {
  state = "available"
}
locals {
  az_names = data.aws_availability_zones.azs.names
}

resource "aws_vpc" "main" {
  for_each   = var.environment
  cidr_block = var.vpc_cidr

  tags = {
    Name = var.vpc_tags
  }
}

resource "aws_subnet" "public" {
  for_each                = var.public_sub_cidr
  vpc_id                  = aws_vpc.main[each.key].id
  cidr_block              = cidrsubnet(var.vpc_cidr, 0, each.value.public_subnet)
  availability_zone       = local.az_names[each.key]
  map_public_ip_on_launch = true
  tags = {
    Name = "${var.vpc_tags}-PubSubnet"
  }
}

错误

Error: Unsupported attribute



on vpc.tf line 17, in resource "aws_subnet" "public":
  17:   cidr_block              = cidrsubnet(var.vpc_cidr, 0, each.value.public_subnet)
    |----------------
    | each.value is ""

This value does not have any attributes.

Error: Invalid index



on vpc.tf line 18, in resource "aws_subnet" "public":
  18:   availability_zone       = local.az_names[each.key]
    |----------------
    | each.key is ""
    | local.az_names is list of string with 3 elements

The given key does not identify an element in this collection value: a number
is required.

任何关于从可用性区域读取以及分配这些 public 子网的建议都将不胜感激。

更新 我取得了一些进展,更新了我的代码以使用我的数据资源的“长度”。请参阅下面的代码和错误:

resource "aws_subnet" "public" {
  for_each                = length(local.az_names)
  vpc_id                  = aws_vpc.tableau[each.key].id
  cidr_block              = cidrsubnet(var.vpc_cidr, 8, each.value)
  availability_zone       = local.az_names[each.key]
  map_public_ip_on_launch = true
  tags = {
    Name = "${var.vpc_tags}-PubSubnet"
  }
}
Error: Invalid for_each argument



 on vpc.tf line 15, in resource "aws_subnet" "public":
  15:   for_each                = length(local.az_names)

The given "for_each" argument value is unsuitable: the "for_each" argument
must be a map, or set of strings, and you have provided a value of type
number.

make: *** [apply] Error 1

不确定您要达到什么目的,但这是不正确的:

for_each                = length(local.az_names)

应该是:

for_each                = toset(local.az_names)

由于现在设置了local.az_names,您只能使用each.keyeach.valueeach.key相同)。例如:

availability_zone       = each.key

以下代码在每个 AZ 中创建一个子网:

provider "aws" {
  # your details
}

data "aws_availability_zones" "azs" {
  state = "available"
}

locals {
  az_names = data.aws_availability_zones.azs.names
}

variable "vpc_cidr" {
  default = "10.0.0.0/16"
}

resource "aws_vpc" "main" {
  cidr_block = var.vpc_cidr
}

resource "aws_subnet" "public" {
  for_each                = {for idx, az_name in local.az_names: idx => az_name}
  vpc_id                  = aws_vpc.main.id
  cidr_block              = cidrsubnet(var.vpc_cidr, 8, each.key)
  availability_zone       = local.az_names[each.key]
  map_public_ip_on_launch = true
}