使用 Terraform 在多个子网中创建 EC2 实例
Creating EC2 instances in multiple subnets with Terraform using for each
我目前在一个 VPC 中为一个区域内的每个可用区创建了多个子网。我现在正尝试在每个可用区内为每个子网创建一个 EC2 实例,运行 遇到了问题。下面是我的代码,我在获取子网 ID 以附加到 EC2 实例时遇到了一些问题。如有任何建议,我们将不胜感激。
实例
resource "aws_instance" "public" {
for_each = aws_subnet.public
ami = data.aws_ami.ec2.id
instance_type = var.tableau_instance
key_name = aws_key_pair.main.key_name
subnet_id = [for subnet in aws_subnet.public : subnet.id]
}
子网
locals {
az_names = data.aws_availability_zones.azs.names
}
resource "aws_subnet" "public" {
for_each = { for index, az_name in local.az_names : index => az_name }
vpc_id = aws_vpc.main.id
cidr_block = cidrsubnet(var.vpc_cidr, 8, each.key + 1)
availability_zone = local.az_names[each.key]
map_public_ip_on_launch = true
tags = {
Name = "${var.vpc_tags}_PubSubnet"
}
}
错误
Error: Incorrect attribute value type
on vpc.tf line 18, in resource "aws_instance" "public":
18: subnet_id = [for subnet in aws_subnet.public : subnet.id]
|----------------
| aws_subnet.public is object with 3 attributes
Inappropriate value for attribute "subnet_id": string required.
实例代码如下:
resource "aws_instance" "public" {
for_each = aws_subnet.public
ami = data.aws_ami.ec2.id
instance_type = var.tableau_instance
key_name = aws_key_pair.main.key_name
subnet_id = each.value.id
}
这将在每个子网中放置 1 个实例。
我目前在一个 VPC 中为一个区域内的每个可用区创建了多个子网。我现在正尝试在每个可用区内为每个子网创建一个 EC2 实例,运行 遇到了问题。下面是我的代码,我在获取子网 ID 以附加到 EC2 实例时遇到了一些问题。如有任何建议,我们将不胜感激。
实例
resource "aws_instance" "public" {
for_each = aws_subnet.public
ami = data.aws_ami.ec2.id
instance_type = var.tableau_instance
key_name = aws_key_pair.main.key_name
subnet_id = [for subnet in aws_subnet.public : subnet.id]
}
子网
locals {
az_names = data.aws_availability_zones.azs.names
}
resource "aws_subnet" "public" {
for_each = { for index, az_name in local.az_names : index => az_name }
vpc_id = aws_vpc.main.id
cidr_block = cidrsubnet(var.vpc_cidr, 8, each.key + 1)
availability_zone = local.az_names[each.key]
map_public_ip_on_launch = true
tags = {
Name = "${var.vpc_tags}_PubSubnet"
}
}
错误
Error: Incorrect attribute value type
on vpc.tf line 18, in resource "aws_instance" "public":
18: subnet_id = [for subnet in aws_subnet.public : subnet.id]
|----------------
| aws_subnet.public is object with 3 attributes
Inappropriate value for attribute "subnet_id": string required.
实例代码如下:
resource "aws_instance" "public" {
for_each = aws_subnet.public
ami = data.aws_ami.ec2.id
instance_type = var.tableau_instance
key_name = aws_key_pair.main.key_name
subnet_id = each.value.id
}
这将在每个子网中放置 1 个实例。