我有2个子网(每个可用区1个子网(
resource "aws_subnet" "infrastructure_services" {
count = "${var.enable_infrastructure_services_subnet ? 2 : 0}"
vpc_id = "${aws_vpc.this.id}"
cidr_block = "${cidrsubnet(var.cidr_block,5,count.index + 6)}"
availability_zone = "${element(var.availability_zones, count.index)}"
map_public_ip_on_launch = false
tags = "${
merge( map("Name", format("%s %s %s", var.env_name, count.index == 0 ? "Infrastructure Services A" : "Infrastructure Services B", "Subnet")),
var.global_tags,
var.vpc_tags)}"
}
我想将这2个子网添加到EC2实例:
resource "aws_instance" "this" {
count = "${length(var.instance_names)}"
ami = "${var.ami}"
instance_type = "${element(var.instance_type, count.index)}"
availability_zone = "${element(var.availability_zones, count.index)}"
disable_api_termination = "${var.disable_api_termination}"
key_name = "${var.key_name}"
ebs_optimized = "${var.ebs_optimized}"
subnet_id="${element(aws_subnet.infrastructure_services.id,count.index)}"
vpc_security_group_ids=["${aws_security_group.infrastructure_services.id}"]
但是得到:
aws_instance.this[0]: Resource 'aws_subnet.infrastructure_services' not found for variable 'aws_subnet.infrastructure_services.id'
* aws_instance.this[1]: Resource 'aws_subnet.infrastructure_services' not found for variable 'aws_subnet.infrastructure_services.id'
您的列表中缺少*
splat运算符语法。相反,您应该使用aws_subnet.infrastructure_services.*.id
来引用资源列表。
因此,您的实例资源应该如下所示:
resource "aws_instance" "this" {
count = "${length(var.instance_names)}"
ami = "${var.ami}"
instance_type = "${element(var.instance_type, count.index)}"
availability_zone = "${element(var.availability_zones, count.index)}"
disable_api_termination = "${var.disable_api_termination}"
key_name = "${var.key_name}"
ebs_optimized = "${var.ebs_optimized}"
subnet_id = "${element(aws_subnet.infrastructure_services.*id, count.index)}"
vpc_security_group_ids = ["${aws_security_group.infrastructure_services.id}"]
}
可能还值得注意的是,除非您需要使用列表长度的模对列表进行循环,否则您可以使用更简单的list[index]
语法,而不是element(list, index])
:
resource "aws_instance" "this" {
count = "${length(var.instance_names)}"
ami = "${var.ami}"
instance_type = "${var.instance_type[count.index]}"
availability_zone = "${var.availability_zones[count.index])}"
disable_api_termination = "${var.disable_api_termination}"
key_name = "${var.key_name}"
ebs_optimized = "${var.ebs_optimized}"
subnet_id = "${aws_subnet.infrastructure_services.*id[count.index])}"
vpc_security_group_ids = ["${aws_security_group.infrastructure_services.id}"]
}