属性值不合适 cidr_block 需要字符串

Inappropriate value for the attribute cidr_block string is required

嗨,我的地形代码在这里

main.tf

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 3.0"
    }
  }
}
# Configure the AWS Provider
provider "aws" {
  region = var.region
}

# DATA

data "aws_availability_zones" "available" {}

data "template_file" "public_cidrsubnet" {
  count    = var.subnet_count
  template = "$${cidrsubnet(vpc_cidr,8,current_count)}"
  vars = {
    vpc_cidr      = var.network_address_space
    current_count = count.index
  }
}

resource "aws_vpc" "tf-aws-vn" {
  cidr_block = var.network_address_space
  tags       = local.common_tags
  #name       = var.name
}
resource "aws_subnet" "tf-aws-sn" {
  count             = length(data.aws_availability_zones.available.names)
  vpc_id            = aws_vpc.tf-aws-vn.id
  cidr_block        = [data.template_file.public_cidrsubnet[*].rendered]
  availability_zone = slice(data.aws_availability_zones.available.names, 0, var.subnet_count)
  tags              = local.common_tags
}

variables.tf

variable "region" {
  default = "us-east-1"
}
variable network_address_space {}

variable name {
  type = string
}
variable "subnet_count" {
  type = number
}

终于来了! terraform.tfvars

network_address_space = "10.0.0.0/16"
subnet_count          = 2

我收到如下错误:

Error: Incorrect attribute value type

  on main.tf line 36, in resource "aws_subnet" "tf-aws-sn":
  36:   cidr_block        = [data.template_file.public_cidrsubnet[*].rendered]

Inappropriate value for attribute "cidr_block": string required.

有什么问题?

我想为我提供的任何地址范围创建 n 个子网

我的 terraform 版本是 0.13.5

您正在将数组传递给 cidr_block,这会导致给定错误。您需要将字符串传递给 cidr 块。

cidr_block = data.template_file.public_cidrsubnet[count.index].rendered

您还需要将 * 更改为实际计数。否则你会得到一个错误,抱怨它是一个有 2 个元素的元组。 使用您的代码 data.template_file.public_cidrsubnet[*].rendered 的结果是

cidr_output = [
  "10.0.0.0/24",
  "10.0.1.0/24",
]

那么您将面临的下一个问题是计数本身。您使用可用性区域的总数作为计数,但您希望计数为 subnet_count。您在 public_cidrsubnet 模板中只创建了 2 个子网,因此您无法在每个可用区中创建一个子网。 然后,您还需要将 count.index 传递给 availability_zone 参数的切片。

应该工作的正确 aws_subnet 资源

resource "aws_subnet" "tf-aws-sn" {
  count             = var.subnet_count
  vpc_id            = aws_vpc.tf-aws-vn.id
  cidr_block        = data.template_file.public_cidrsubnet[count.index].rendered
  availability_zone = slice(data.aws_availability_zones.available.names, 0, var.subnet_count)[count.index]

}