如何为Map of Maps创建Terraform自定义数据源Schema并修复输出为空问题
问题修复方案
核心错误点
- Read方法绑定不匹配:Schema中指定的Read函数是
accountHelperRead,但实际定义的函数是rolesRead,导致Terraform调用数据源时根本没执行数据读取逻辑。 - 字段名不匹配:调用
d.Set时用了"account_map",但Schema中定义的字段是"roles",导致数据没写入正确的字段。
修正后的代码
1. 修正Read方法绑定与函数名
func dataSourceAccountHelper() *schema.Resource { return &schema.Resource{ Read: rolesRead, // 绑定正确的Read函数 Schema: map[string]*schema.Schema{ "roles": { Type: schema.TypeMap, Elem: &schema.Schema{ Type: schema.TypeMap, Computed: true, Elem: &schema.Schema{ Type: schema.TypeString, }, }, Computed: true, }, "id": &schema.Schema{ Computed: true, Type: schema.TypeString, }, }, } }
2. 修正Read方法中的字段名并适配类型
func rolesRead(d *schema.ResourceData, m interface{}) error { filteredRoles := filterAccounts("john") // 返回map[string]map[string]string类型数据 // 将嵌套map转换为map[string]interface{},适配Terraform SDK的类型要求 rolesInterface := make(map[string]interface{}, len(filteredRoles)) for k, v := range filteredRoles { rolesInterface[k] = v } // 写入正确的字段名"roles" if err := d.Set("roles", rolesInterface); err != nil { return err } d.SetId("-") return nil }
补充说明
- 显式转换为
map[string]interface{}是为了更好适配Terraform SDK对复杂嵌套类型的处理逻辑,避免潜在的类型断言问题。 - 修正后,Terraform会正确读取roles数据,id也会被设置为
"-",与预期输出一致。
内容的提问来源于stack exchange,提问作者alexx087
相关产品推荐
相关产品推荐

