【发布时间】:2021-03-09 04:47:41
【问题描述】:
我有以下变量
variable "instance_types" {
default = {
instances : [
{
count = 1
name = "control-plane"
ami = "ami-xxxxx"
instance_type = "t2.large"
iam_instance_profile = "xxx-user"
subnet_id = "subnet-xxxxx"
},
{
count = 3
name = "worker"
ami = "ami-xxxxx"
instance_type = "t2.large"
iam_instance_profile = "xxx-user"
subnet_id = "subnet-xxxxx"
}
]
}
}
使用以下实例声明(我正在尝试迭代)
resource "aws_instance" "k8s-node" {
# Problem here : How to turn an array of 2 objects into 4 (1 control_plane, 3 workers)
for_each = {for x in var.instance_types.instances: x.count => x}
ami = lookup(each.value, "ami")
instance_type = lookup(each.value, "instance_type")
iam_instance_profile = lookup(each.value, "iam_instance_profile")
subnet_id = lookup(each.value, "subnet_id")
tags = {
Name = lookup(each.value, "name")
Type = each.key
}
}
目标:让 aws_instance 迭代 4 次(1 个 control_plane + 3 个工作人员)并填充 instance_types 的索引值。
问题:无法正确迭代对象数组并获得所需的结果。在典型的编程语言中,这将在双 for 循环中实现。
【问题讨论】:
-
使用
count作为键的map(object))类型比使用for表达式数据转换的map(list(object))更容易。有什么阻碍你选择那种类型吗? -
不,我可以随意更改对象结构。您能否在您的建议中展示如何实现这一目标。请记住,对象并不是一个详尽的列表。计数相同的情况下可能会有更多
-
好的,所以我现在实际上更清楚地看到了您想要实现的目标。您希望将 k8s 工作程序和控制平面节点概括为单个 TF AWS 实例资源。我的评论现在稍微不那么有效了,但无论如何都按照相同的思路回答。
-
再次关闭实例数量是不够的,因为这两个之外的几种不同实例类型将包含在此映射中
-
不确定这与我解释前进道路的 cmets 有何关系,但答案很快就会完成。
标签: terraform terraform-provider-aws