Terraform是否支持map of list?如何表示给定YAML对应的数据结构
Terraform map of list类型支持及变量定义方案
类型支持说明
Terraform完全原生支持map of list类型,对于你给出的YAML结构,最佳实践是结合object类型做属性约束,既能完美匹配结构,还能自动校验每个字段的类型,避免传入非法值。
对应Terraform变量定义
你可以直接使用下面的变量声明匹配需求:
variable "env_members" { type = map(list(object({ name = string type = string }))) description = "各环境的人员配置,key为环境名,value为对应环境的人员列表" default = { Dev = [ { name = "Michael", type = "Senior" }, { name = "Ron", type = "Junior" }, { name = "Lex", type = "Senior" }, { name = "Rocky", type = "Junior" } ] Test = [ { name = "Rony", type = "Junior" }, { name = "Ryan", type = "Junior" }, { name = "John", type = "Senior" }, { name = "Brad", type = "Junior" } ] } }
补充使用提示
- 如果你需要从外部YAML文件读取这个结构,可以搭配
yamldecode函数直接解析,解析结果可以直接赋值给上述变量,无需额外转换:locals { env_members = yamldecode(file("${path.module}/你的配置文件路径.yaml")) } - 遍历取值时可以直接用嵌套的for/for_each表达式处理,比如提取所有Dev环境的高级成员:
output "dev_senior_staff" { value = [for staff in var.env_members.Dev : staff.name if staff.type == "Senior"] }
内容的提问来源于stack exchange,提问作者mystack
相关产品推荐
相关产品推荐

