写 TF Provider 时,我应该从 Importer return 做什么?

What should I return from Importer when writing TF Provider?

上下文:我正在开发一个 TF 提供程序。

假设我正在实施一个复杂的导入:

func fooResource() *schema.Resource {
    return &schema.Resource{
...
        Importer: &schema.ResourceImporter{
            StateContext: fooImport,
        },

...

func fooImport(ctx context.Context, d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
    ...
    return []*schema.ResourceData{d}, nil
}

因此,如果导入成功,我应该 return []*schema.ResourceData{d}, nil。如果导入失败,我应该将 return nil[]*schema.ResourceData{d} 作为第一个参数吗?显然,第二个参数将是 err.

注意:我从 HashiCorp 找到了这个 tutorial,但它没有说明任何相关内容(他们使用的是 ImportStatePassthrough)。

复杂资源导入的代码一般遵循以下结构:

Importer: &schema.ResourceImporter{
  State: func(d *schema.ResourceData, meta interface{}) (result []*schema.ResourceData, err error) {
    ...
    if err {
      return nil, fmt.Errorf("my error message about the ID (%q)", d.Id())
    }

    d.Set("<resource_type>", d.Id())

    return []*schema.ResourceData{d}, nil
  },
},

所以对于你的具体情况,它看起来像:

Importer: &schema.ResourceImporter{
  StateContext: fooImport(ctx context.Context, d *schema.ResourceData, meta interface{}) (result []*schema.ResourceData, error) {
    ...
    if err {
      return nil, fmt.Errorf("my error message about the ID (%q)", d.Id())
    }

    d.Set("foo_resource", d.Id())

    return []*schema.ResourceData{d}, nil,
  },
}

所以基本上第一个 return 类型是 nil

旁注:您提到 ImportStatePassthrough,在您使用 context 的情况下,相关帮助者可能是 ImportStatePassthroughContext