可以在同一个资源语句中使用for_each和dynamic块吗?或者可以在资源语句/创建2个EC2实例/中使用多个EC2
resource "aws_instance" "ABC" {
count = 2
ami = var.AMIX
instance_type = "t3.small"
subnet_id = xxx
vpc_security_group_ids = [data.aws_security_group.SG.id]
key_name = var.AMIX-KEY
tags = {
Name = abc)
}
}/创建具有子网名称和子网id /的本地dict,其中ec2实例1有2个子网,ec2实例2有2个子网
locals {
# With List
subnets = flatten([
for subnet_details in aws_subnet.SUBNET : {
subnet_name = subnet_details.tags.Name,
subnet_id = subnet_details.id
} if contains(["abc", "xyz"], subnet_details.tags.Name)
])
}/当地子网输出。
dev = [
+ {
+ subnet_id = "A"
+ subnet_name = "DEV1"
},
+ {
+ subnet_id = "B"
+ subnet_name = "DEV1"
},
+ {
+ subnet_id = "C"
+ subnet_name = "DEV2"
},
+ {
+ subnet_id = "D"
+ subnet_name = "DEV2"
},
]/如何将EC2实例与网络接口连接?在附件中循环两次,因为我需要根据subnet_name 2子网绑定两个subnet_name实例,获取ec2-1和2个子网,得到ec2-2,并在此基础上得到device_index /。
resource "aws_network_interface" "NICS" {
for_each = {
for subnet_id, subnet_name in local.subnets : subnet_id => subnet_name
}
subnet_id = each.value.subnet_id
security_groups = [data.aws_security_group.SG.id]
tags = {
Name = each.value.subnet_name
}
attachment {
instance = ?
device_index = 1
}
}发布于 2021-03-03 00:34:16
下面的代码版本呢?我还没有运行代码,但是您可以考虑它背后的想法:
variable "instance_name" {
default = ["Y", "Z"]
}
resource "aws_instance" "ABC" {
for_each = var.instance_name
ami = var.AMIX
instance_type = "t3.small"
subnet_id = xxx
vpc_security_group_ids = [data.aws_security_group.SG.id]
key_name = var.AMIX-KEY
tags = {
Name = each.key
}
}然后,当您还指定实例名称时,将基于local.subnets创建四个NIC。此外,我还将使用附件将NIC的创建与它们的附件分开。
locals {
subnets = [
{
subnet_id = "A"
subnet_name = "DEV1"
instance_name = "Y"
},
{
subnet_id = "B"
subnet_name = "DEV1"
instance_name = "Y"
},
{
subnet_id = "C"
subnet_name = "DEV2"
instance_name = "Z"
},
{
subnet_id = "D"
subnet_name = "DEV2"
instance_name = "Z"
}
]
}
resource "aws_network_interface" "NICS" {
for_each = {for subnet in local.subnets : (subnet.subnet_name) => subnet}
subnet_id = each.value.subnet_id
security_groups = [data.aws_security_group.SG.id]
tags = {
Name = each.value.subnet_name
}
}
resource "aws_network_interface_attachment" "test" {
for_each = {for subnet in local.subnets : (subnet.subnet_name) => subnet}
instance_id = aws_instance.ABC[each.value.instance_name].id
network_interface_id = aws_network_interface.NICS[each.key].id
device_index = 0
}https://stackoverflow.com/questions/66446095
复制相似问题