首页 > 文章列表 > 构建自定义 terraform 数据源提供程序架构来为地图值的地图创建?

构建自定义 terraform 数据源提供程序架构来为地图值的地图创建?

279 2024-04-28
问题内容

我有一个 golang 函数,它返回 map[string]map[string]string 类型的角色

例如:

map[foo:map[name:abc env:dev id:465 project:e-1] boo:map[name:def env:prd id:82 project:e-1] :doo[name:ght env:stg id:353 project:e-3]]

我为它创建了一个架构,如下所示...

func datasourceaccounthelper() *schema.resource {
    return &schema.resource{
        read: accounthelperread,

        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,
            },
        },
    }
}

以及将角色值传递给架构的创建方法

func rolesread(d *schema.resourcedata, m interface{}) error {
    filteredroles := filteraccounts("john") // returns `map[string]map[string]string`



    if err := d.set("account_map", filteredroles); err != nil {
        return err
    }

    //accountmaps := make(map[string]interface{})

    d.setid("-")

    return nil
}

但是 terraform 输出是一个空地图,我该如何修复它,请帮忙:)

outputs:

output = {
  "roles" = tomap(null) /* of map of string */
  "id" = tostring(null)
}

期望输出如下

Outputs:

output = {
  "roles" = { foo    = {name = "abc" env = "dev" id= 465 project = "e-1"}
              boo    = {name = "efg" env = "prd" id= 82 project = "e-2"}       
            },
  "id" = "-"
}


正确答案


您正在使用的旧版 terraform sdk 无法实现您在此处尝试执行的操作。映射只能是基本类型:typestringtypeinttypebool

要创建此结构,您需要迁移到新框架,它是为现代 terraform 的类型系统构建的,而不是(如 sdkv2 的情况)经典 terraform v0.11 及更早版本的类型系统。

在 terraform 插件框架中,与您尝试在此处描述的结构等效的结构是 mapnestedattribute,以下内容描述了您在问题中显示的架构结构:

schema.mapnestedattribute{
    nestedobject: schema.nestedattributeobject{
        attributes: map[string]schema.attribute{
            "name": schema.stringattribute{
                // ...
            },
            "env": schema.stringattribute{
                // ...
            },
            "id": schema.numberattribute{
                // ...
            },
            "project": schema.stringattribute{
                // ...
            },
        },
    },
}

这表示具有给定属性的对象的映射,因此上述模式类型相当于以下类型约束,可以使用 terraform 语言的类型约束语法

map(
  object({
    name    = string
    env     = string
    id      = number
    project = string
  })
)