【发布时间】: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