我正在尝试使用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.
任何有关从可用区域读取信息以及分配这些公共子网的建议都将受到赞赏。
更新 我取得了一些进展,更新了我的代码以将其与数据资源的“长度”一起使用。请参见下面的代码和错误:
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
答案 0 :(得分:2)
不确定您要达到的目标,但这是不正确的:
for_each = length(local.az_names)
应该是:
for_each = toset(local.az_names)
由于现在设置了local.az_names
,所以您只能使用each.key
(each.value
与each.key
相同)。例如:
availability_zone = each.key
以下代码在每个可用区中创建一个子网:
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
}