我遇到了这个错误:
Inappropriate value for attribute "vpc_zone_identifier": element 0: string required.
变量应该是字符串列表,因此元素 0 应该是字符串。
这是代码:
专有网络模块:
resource "aws_subnet" "terraform-pub-sn" {
count = "${length(data.aws_availability_zones.all.names)}"
vpc_id = "${aws_vpc.terraform-vpc.id}"
cidr_block = "${element(var.vpc_subnet_cidr, count.index)}"
availability_zone = "${data.aws_availability_zones.all.names[count.index]}"
}
输出:
output "terraform_subnet_ids" {
value = ["${aws_subnet.terraform-pub-sn.*.id}"]
}
Main.tf:
module "auto_scaling_group" {
source = "./modules/AutoScalingGroup"
terraform_subnet_ids = ["${module.vpc.terraform_subnet_ids}"]
}
ASG 模块:
variable "terraform_subnet_ids"{}
resource "aws_autoscaling_group" "terraform-asg" {
vpc_zone_identifier = ["${var.terraform_subnet_ids}"]
...
}
我花了半天时间试图解决这个问题,不确定还有什么要尝试的,以及应该如何定义它。AFAIK 添加 [] 将使变量成为字符串列表,当它选择元素 0 并返回错误时,元素在技术上应该是一个字符串,所以不知道问题是什么。也许有一种方法可以在飞行中检查它是什么?
完整的错误在这里:
Error: Incorrect attribute value type
on modulesAutoScalingGroupasg.tf line 43, in resource "aws_autoscaling_group" "terraform-asg":
43: vpc_zone_identifier = ["${var.terraform_subnet_ids}"]
Inappropriate value for attribute "vpc_zone_identifier": element 0: string
required.
你的一个例子如下:
output "terraform_subnet_ids" {
value = ["${aws_subnet.terraform-pub-sn.*.id}"]
}
这包括两个操作:aws_subnet.terraform-pub-sn.*.id
返回 id 列表,然后[ ... ]
从其内容构造列表。所以这个表达式正在构造一个列表列表,看起来像这样:
[
["subnet-abc123", "subnet-123abc"]
]
在module
块中有一个类似的表达式:
terraform_subnet_ids = ["${module.vpc.terraform_subnet_ids}"]
这也有[ ...
],所以它添加了另一个级别的列表:
[
[
["subnet-abc123", "subnet-123abc"]
]
]
最后,当您在自动缩放组配置中引用此内容时,我们还有一个[ ... ]
表达式:
vpc_zone_identifier = ["${var.terraform_subnet_ids}"]
因此,当它到达此处时,分配给此参数的值为:
[
[
[
["subnet-abc123", "subnet-123abc"]
]
]
]
此列表的元素 0 是字符串列表的列表,因此 Terraform 报告类型错误。
综上所述,我认为按照您的意图进行这项工作的方法是从所有这些表达式中删除[ ... ]
列表构造括号:
output "terraform_subnet_ids" {
# A list of subnet ids
value = aws_subnet.terraform-pub-sn.*.id
}
module "auto_scaling_group" {
source = "./modules/AutoScalingGroup"
# still a list of subject ids
terraform_subnet_ids = module.vpc.terraform_subnet_ids
}
variable "terraform_subnet_ids" {
# Setting an explicit type for your variable can be helpful to
# catch this sort of problem at the caller, rather than in
# the usage below. I used set(string) rather than list(string)
# here because vpc_zone_identifier is an unordered set of subnet
# ids; list(string) would work too, since Terraform will convert
# to a set just in time to assign to vpc_zone_identifier.
type = set(string)
}
resource "aws_autoscaling_group" "terraform-asg" {
# because of the type declaration above, this is now a set
# of strings, which is the type this argument is expecting.
vpc_zone_identifier = var.terraform_subnet_ids
}