我对terraform真的很陌生,想要做这项工作。我能够创建vpc,公共子网并获取它们的ID,现在我想在每个子网内创建一个ec2实例,当我尝试运行ec2模块时,它只在第一个子网内创建实例并忽略其他子网。这是我的代码片段。
输出子网ID:
output "public_subnets_id" {
value = "${join(",", aws_subnet.public.*.id)}"
}
这里的示例输出:
public_subnets_id = subnet-84aae6f4,subnet-a12124e8
这是我的代码,我试图将其拆分并在每个子网内创建实例,但只能创建到第一个子网。
subnet_id = "${element(split(",", var.subnet_id), count.index)}"
答案 0 :(得分:11)
我在不同的可用区域中展开EC2实例,如下所示:
variable "zones" {
default = {
zone0 = "us-east-1a"
zone1 = "us-east-1b"
zone2 = "us-east-1c"
}
}
variable "cidr_blocks" {
default = {
zone0 = "172.32.0.0/20"
zone1 = "172.32.16.0/20"
zone2 = "172.32.32.0/20"
}
}
variable "dockerhost_instances" {
default = "5"
}
resource "aws_subnet" "public-subnet" {
...
cidr_block = "${lookup(var.cidr_blocks, format("zone%d", count.index))}"
availability_zone = "${lookup(var.zones, format("zone%d", count.index))}"
count = 3
}
resource "aws_instance" "host" {
...
subnet_id = "${element(aws_subnet.public-subnet.*.id,count.index)}"
count = "${var.dockerhost_instances}"
}
由于${element(...)}
函数包含,结果是三个子网和五个主机分布在子网上:
us-east-1a : host.0 host.3
us-east-1b : host.1 host.4
us-east-1c : host.2
答案 1 :(得分:1)
似乎问题出在resource "aws_instance"
define,
count ="${length(split(",", var.subnet_id))}"
如果你直接将count设置为2,你会得到两个实例吗?
我的理解是,ec2资源的计数应该设置为默认值,例如2,或者直接将ec2_num
定义为variable.tf中的数字,然后在资源ec2中通过var.ec2_num
调用它