Home > other >  What should I return from Importer when writing TF Provider?
What should I return from Importer when writing TF Provider?

Time:01-22

Context: I'm developing a TF provider.

Let's say I'm implementing a complex import:

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
}

So if the import was successful I should return []*schema.ResourceData{d}, nil. What if my import failed, shall I return nil or []*schema.ResourceData{d} as the first argument? Obviously, the second argument is going to be err.

Note: I found this tutorial from HashiCorp but it doesn't say anything about it (they're using ImportStatePassthrough).

CodePudding user response:

The code for a complex resource import generally follows the structure below:

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

so for your specific situation it would appear like:

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

So basically the first return type would be nil.

Side note: you mention ImportStatePassthrough, and in your situation with context the relevant helper may be ImportStatePassthroughContext instead.

  •  Tags:  
  • Related