【问题标题】:AWS Terraform error: "expected cidr_block to contain a valid Value, got: with err: invalid CIDR address:"AWS Terraform 错误:“预期 cidr_block 包含有效值,得到:错误:无效 CIDR 地址:”
【发布时间】:2021-11-17 18:56:56
【问题描述】:

在 Terraform 中使用 AWS 安全组进行练习。我对 TF 有一定的经验,但 SG 一直很棘手。我有以下 main.tf:

provider "aws" {
region = "us-east-1"
}

resource "aws_vpc" "test" {
cidr_block = var.cidr_block
}

resource "aws_security_group" "sg" {
name = var.name
vpc_id = aws_vpc.test.id
description = var.description
}

resource "aws_security_group_rule" "ingress_rule" {
type = "ingress"
from_port = var.from_port
to_port = var.to_port
protocol = var.protocol
cidr_blocks = var.cidr_blocks
security_group_id = aws_security_group.sg.id
}

我在 variables.tf 文件中有上述变量(可根据要求显示),我的模块如下:

provider "aws" {
region = "us-east-1"
}

module "vpc" {
source = "../"
cidr_block = "10.0.0.0/16"
}

module "TestSG1" {
source = "../"
name = "Test"
description = "Test"
type = "ingress"
from_port = 0
to_port = 65535
protocol = "tcp"
cidr_blocks = ["192.168.0.0/16"]
}

在上述配置上运行 Terraform Plan 时,我收到此错误:

错误:预期 cidr_block 包含有效值,得到:错误: 无效的 CIDR 地址:

在 ..\vpc.tf 第 6 行,在资源“aws_vpc”“test”中:

6: cidr_block = var.cidr_block

现在,如果我从 vpc 模块中删除 cidr_block 行,而是将相同的 cidr_block 值硬编码到 main.tf 中,如下所示:

resource "aws_vpc" "test" {
cidr_block = "10.0.0.0/16"
}

....然后我可以应用代码没有问题,两个模块部署成功。所以只有当我将 cidr_block 行插入 VPC 模块时才会出现问题。如果我单独运行 VPC 模块——除了 SG 资源和模块——它在模块 aws 中的 cidr_block 变量运行良好。两者之间的相互作用出现了问题。用尽了我的研究,所以转向 Stackoverflow 智囊团。有什么想法吗?

更新:也分享我的变量,这是很好的衡量标准。

variable "cidr_block" {
description = ""
type = string
default = ""
}

variable "name" {
description = ""
type = string
default = ""
}

variable "description" {
description = ""
type = string
default = ""
}

variable "type" {
description = ""
type = string
default = ""
}

variable "from_port" {
description = ""
type = number
default = 0
}

variable "to_port" {
description = ""
type = number
default = 0
}

variable "protocol" {
description = ""
type = string
default = ""
}

variable "cidr_blocks" {
description = ""
type = list(string)
default = []
}

【问题讨论】:

  • 您的 cidr_block 变量似乎为空。你想从variables.tf 文件中读取值,还是从模块中加载它?
  • 我想从模块中读取它,所以我将变量的默认值设置为“”。
  • 你可以在你的模块中define an output value,然后像this一样访问它的值,例如module.vpc.cdir_block

标签: amazon-web-services terraform terraform-provider-aws


【解决方案1】:

在我看来,您使用不同的参数两次调用同一个模块(代码):

  • 曾经是module vpc
  • 还有一次module TestSG1

由于您为大多数 var 设置了 default = "",因此在以 TestSG1 调用模块时,它采用您在 variables.tf 中的 cidr_block 的默认值,并且您看到它是空的:

Error: expected cidr_block to contain a valid Value, got: with err: invalid CIDR address:=.

为了修复它,您要么只需通过正确传递所有必需参数来调用该模块一次,要么将 VPC 创建与安全组创建分开在一个单独的模块中。

【讨论】:

  • 好的,我想我明白了。使用另一个评论提到的输出,我能够成功部署模块 - 但我会建立多个安全组和 VPC,并且我意识到 TestSG1 模块正在调用 VPC 代码并建立额外的 VPC。不是世界末日,而是混乱,我相信它可能会导致问题。我想我现在明白为什么 SG 不经常包含在 VPC 存储库中,而是单独调用。谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-05
  • 1970-01-01
  • 1970-01-01
  • 2021-03-31
相关资源
最近更新 更多