在Terraform中有一些关于计数的问题,想知道是否有人可以提供建议。我有一组三个实例,在我的一个模块中安装了EBS卷。请参阅以下代码摘录:
resource "aws_instance" "xxxx" {
count = "${length(data.aws_availability_zones.all.names)}"
ami = "${var.ami}"
instance_type = "t2.small"
vpc_security_group_ids = ["${module.xxxx-sg.this_security_group_id}"]
key_name = "${var.key_name}"
subnet_id = "${element(module.vpc.xxxx_subnets, count.index)}"
user_data = "${module.xxxx-userdata.template_file}"
tags {
Name = "${local.xxxx_name}"
}
root_block_device = [
{
volume_size = 20
volume_type = "gp2"
delete_on_termination = true
},
]
}
这与以下代码配对以创建和附加EBS卷:
resource "aws_ebs_volume" "xxxx-ebs" {
count = "${length(data.aws_availability_zones.all.names)}"
availability_zone = "${element(data.aws_availability_zones.all.names, count.index)}"
size = 100
type = "gp2"
tags {
Name = "${local.xxxx_name}"
}
}
resource "aws_volume_attachment" "xxxx-ebs-attachment" {
count = "${length(data.aws_availability_zones.all.names)}"
device_name = "/dev/sdg"
volume_id = "${aws_ebs_volume.xxxx-ebs.*.id[count.index]}"
instance_id = "${aws_instance.xxxx.*.id[count.index]}"
}
所以上面使用的语法(aws_ebs_volume.xxxx-ebs。*。id [count.index])最初使用的是Terraform中的element()函数,但我遇到了一个实例,当一个实例被终止/编辑时。 .Terraform会尝试将所有EBS重新附加到所有实例,而不仅仅是已更改的实例。我修改了,目前正在使用上面的语法,它在过去几周一直运行正常,直到今天早上Terraform运行时抛出了以下问题。
为了给你一个状态的当前视图,两个xxxx实例已被终止,所以我希望它重新创建这两个实例并重新附加现有的EBS卷。错误
* module.prod-env0.aws_volume_attachment.xxxx-ebs-attachment: 2 error(s) occurred:
* module.prod-env0.aws_volume_attachment.xxxx-ebs-attachment[1]: index 1 out of range for list aws_instance.xxxx.*.id (max 1) in:
${aws_instance.xxxx.*.id[count.index]}
* module.prod-env0.aws_volume_attachment.xxxx-ebs-attachment[2]: index 2 out of range for list aws_instance.xxxx.*.id (max 1) in:
${aws_instance.xxxx.*.id[count.index]}
我有兴趣了解其他人如何管理他们的EBS卷。
答案 0 :(得分:0)
你的语法错了。你应该做
resource "aws_volume_attachment" "xxxx-ebs-attachment" {
count = "${length(data.aws_availability_zones.all.names)}"
device_name = "/dev/sdg"
volume_id = "${element(aws_ebs_volume.xxxx-ebs.*.id, count.index)}"
instance_id = "${element(aws_instance.xxxx.*.id, count.index)}"
}