Terraform AWS如何创建每个实体都有自己子网的计数实例



我创建两个子网:

resource "aws_subnet" "ws_net_public-a" {
vpc_id = aws_vpc.ws_net.id
cidr_block = "10.0.10.0/24"
map_public_ip_on_launch = true
availability_zone = data.aws_availability_zones.available.names[0]
tags = {
"Name" = "WS Public-A"
}
}
resource "aws_subnet" "ws_net_public-b" {
vpc_id = aws_vpc.ws_net.id
cidr_block = "10.0.20.0/24"
map_public_ip_on_launch = true
availability_zone = data.aws_availability_zones.available.names[1]
tags = {
"Name" = "WS Public-B"
}
}

并创建两个带有"count"的实例(我知道没有"count"怎么做很简单,但使用"count"做(:

resource "aws_instance" "webserver" {
count = 2
ami = lookup(var.ec2_ami, var.region) 
instance_type = lookup(var.instance_type, var.region)
root_block_device {
volume_type = "gp2"
volume_size = 8
encrypted = false
}
tags = {
Name = "ws-${count.index}"
}
// key_name = var.key_name
vpc_security_group_ids = [aws_security_group.ws_sg.id]
subnet_id = format("%s/%s/%s",aws_subnet.ws_net_public-,var.zones[count.index],".id")
}

我得到错误:

"A managed resource "aws_subnet" "ws_net_public" has not been declared in the root module".

这是正确的。但如何解决呢?

您必须在两个位置都使用count元参数,即在子网和实例代码中。所以你必须做出的改变是:

resource "aws_subnet" "ws_net_public" {
count                   = 2
vpc_id                  = aws_vpc.ws_net.id
cidr_block              = "10.0.${count.index+1}0.0/24"
map_public_ip_on_launch = true
availability_zone       = data.aws_availability_zones.available.names[count.index]
tags = {
"Name" = "WS Public-${count.index}"
}
}
resource "aws_instance" "webserver" {
count         = 2
ami           = lookup(var.ec2_ami, var.region) 
instance_type = lookup(var.instance_type, var.region)
root_block_device {
volume_type = "gp2"
volume_size = 8
encrypted = false
}
tags = {
Name = "ws-${count.index}"
}
// key_name = var.key_name
vpc_security_group_ids = [aws_security_group.ws_sg.id]
subnet_id              = aws_subnet.ws_net_public[count.index].id
}

相关内容

  • 没有找到相关文章

最新更新