登录
首页 >  Golang >  Go问答

使用 Terraform 中的 MapNestedAttribute 进行迭代操作

来源:stackoverflow

时间:2024-02-16 11:27:22 155浏览 收藏

从现在开始,我们要努力学习啦!今天我给大家带来《使用 Terraform 中的 MapNestedAttribute 进行迭代操作》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!

问题内容

我在 main.tf 中定义了列表嵌套属性规范,它看起来像这样:

di_name = [
    {
      source_name = "test1"
      new_d_name  = "test2"
      new_di_name = "test3"
      di_type     = "test4"
    },
    {
      source_name = "test1"
      new_d_name  = "test2"
      new_di_name = "test3"
      di_type     = "test4"
    },
  ]

对应如下。

"di_name" : schema.listnestedattribute{
                optional: true,
                nestedobject: schema.nestedattributeobject{
                    attributes: map[string]schema.attribute{
                        "source_name": schema.stringattribute{
                            required: true,
                        },
                        "new_d_name" : schema.stringattribute{
                            required: true,
                        },
                        "new_di_name" : schema.stringattribute{
                            required: true,
                        },
                        "di_type" : schema.stringattribute{
                            required: true,
                        },
                    },
                },







  type modelstruct struct {

dname              []vmdi `tfsdk:"di_name"`
}

type vmdi struct {
    source name    types.string `tfsdk:"source_name"`
    newdname       types.string `tfsdk:"new_d_name"`
    newdiname      types.string `tfsdk:"new_di_name"`
    ditype         types.string `tfsdk:"di_type"`
}

在新的类/包中,希望这在 go 中是正确的,我有相应的结构,我想用数据初始化。

type vmbi struct {

  getdata [] vmdi
}


 type   vmdi struct {
        source name    string
        newdname       string
        newdiname      string
        ditype         string
    }

现在我想使用这个创建方法从 di_name 列表中获取 main.tf 中的所有值:

func (r *vmResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {

   Initialize struct with di_name values.
newData := newGoPackage.VmDi {


 Put data here from di_name

     }
    
  }

我如何初始化该结构,因为我无法在这里访问 len(di_name) 。

任何帮助都可以,提前致谢。


正确答案


我假设这是 terraform-framework-plugin,因为尽管未指定,但用法似乎是一致的。要从资源模型初始化结构,必须声明该结构,然后使用请求中的 state.get 来修改该结构作为方法内的引用。然后,该引用将包含 terraform 配置中的 hcl2 反序列化/解组值。通常还将返回结果附加到响应诊断中。该模式通常如下所示:

func (r *vmResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
  var state ModelStruct
  resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
  if resp.Diagnostics.HasError() {
      return
  }
  // state.DName now resolves as expected as type []vmDi and is iterable
}

到这里,我们也就讲完了《使用 Terraform 中的 MapNestedAttribute 进行迭代操作》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>