Is id attribute required for resource import?

Hi, I’m trying to create a resource that has the following fields:

  {
    "uuid": "7561c39d-f4df-4c46-b3f1-2ac981271e29",
    "name": "string",
    "publicKey": "string",
    "createdAt": 0
  }

and I’m at the step where I want to implement the import resource functionality using terraform import command.

My resource ImportState looks like this:

func (r *sshKeyResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
	// Retrieve import ID and save to uuid attribute
	resource.ImportStatePassthroughID(ctx, path.Root("uuid"), req, resp)
}

and my acceptance test case looks like:

			{
				ResourceName:      "provider_ssh_key.test",
				ImportState:       true,
				ImportStateVerify: true,
			},

but my tests fail with Could not read ssh key id id-attribute-not-set.

The tests seem to work fine once I add an id field on my model:

type SshKeyModel struct {
	CreatedAt types.Int64  `tfsdk:"created_at"`
	Name      types.String `tfsdk:"name"`
	PublicKey types.String `tfsdk:"public_key"`
	Uuid      types.String `tfsdk:"uuid"`
	ID        types.String `tfsdk:"id"`
}

and on the schema:

			"id": schema.StringAttribute{
				Computed: true,
			},

My question: is this the correct fix? Does the id has to be specified on the state of a resource for import to work? Or is there some other way to specify that uuid is the right id?

Thank you in advance!

1 Like