使用 Terraform 创建子网时出错

问题描述 投票:0回答:2

我创建了一个variable.tf 文件并添加了以下VPC 和子网代码。

variable "VPC_ID" {
  description = "This is VPC created using variables and not as hard coded information."
  type        = string
  default     = "My-VPC"
}

variable "cidr" {
  description = "Setting up with the IPv4 CIDR blocks which can be used for this testing project."
  type        = string
  default     = "10.0.0.0/16"
}

variable "Public_Subnet" {
  description = "Creating an Ip4 Public Subnet."
  type        = list(string)
  default     = ["10.0.1.0/24"]
}

variable "Public_AVZ" {
  description = "This needs to be used for public availability zone only."
  type        = string
  default     = "aps1-az1"
}

然后,我为 VPC 和子网创建了 2 个单独的 .tf 文件,并将以下代码添加到其中。

resource "aws_vpc" "My-VPC" {
  cidr_block       = var.cidr
  instance_tenancy = var.Instance_tenancy

  tags = {
    Name = var.VPC_ID
  }
}


resource "aws_subnet" "Public_Subnet" {
  vpc_id     = var.VPC_ID
  cidr_block = var.cidr
}

现在,当我运行验证和计划命令时,它不会显示任何错误并显示全部正确。但是,当我运行 apply 命令时,出现以下错误。

Error: creating EC2 Subnet: InvalidVpcID.NotFound: The vpc ID 'My_VPC' does not exist
│       status code: 400, request id: 5d6d19ed-2067-4653-8611-c6fdc48b24f4
│ 
│   with aws_subnet.Public_Subnet,
│   on subnets.tf line 3, in resource "aws_subnet" "Public_Subnet":
│    3: resource "aws_subnet" "Public_Subnet" {
│ 

你能帮忙吗?

尝试了几个博客并调整了设置,但没有成功。

terraform terraform-provider-aws
2个回答
0
投票

VPC ID 不是您定义的值。创建VPC资源后提供。 VPC ID 的格式如下:

vpc-01abcdefff3456789

您可以在AWS控制台中找到它:

由于您使用的是 terraform,因此您也可以使用数据源来获取 VPC ID。


0
投票

您为VPC分配的名称不是VPC的ID,它只是一个名称。您可能应该将变量重命名为

VPC_NAME
之类的名称。

VPC 的 ID 是 AWS 在创建 VPC 时分配给您的 VPC 的 ID。它在 Terraform 中可作为 VPC 资源的属性使用。

您的子网需要引用 VPC 资源的 ID 属性,如下所示:

resource "aws_vpc" "My-VPC" {
  cidr_block       = var.cidr
  instance_tenancy = var.Instance_tenancy
}


resource "aws_subnet" "Public_Subnet" {
  vpc_id     = aws_vpc.My-VPC.id
  cidr_block = var.cidr
}
© www.soinside.com 2019 - 2024. All rights reserved.