Skip to content

Commit 87de13d

Browse files
committed
Add guidance for Importer
Signed-off-by: Timo Sand <timo.sand@f-secure.com>
1 parent cc5b69e commit 87de13d

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

ARCHITECTURE.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ This document serves as a guide for contributors implementing new features and r
1717
- [CRUD Function Signatures](#crud-function-signatures)
1818
- [Accessing the API Client](#accessing-the-api-client)
1919
- [Error Handling](#error-handling)
20+
- [Import](#import)
2021
- [State Migrations](#state-migrations)
2122
- [Logging](#logging)
2223
- [Testing](#testing)
@@ -342,6 +343,42 @@ if err := deleteResourceOn404AndSwallow304OtherwiseReturnError(err, d, "resource
342343
}
343344
```
344345

346+
### Import
347+
348+
Import is registered via the `Importer` field with a `StateContext` function. After import runs, Terraform **automatically calls `Read`** — so the import function's only job is to set enough state for `Read` to succeed. Do not duplicate `Read` logic in the import function.
349+
350+
For resources with a single-part ID, the default passthrough importer is often sufficient:
351+
352+
```go
353+
Importer: &schema.ResourceImporter{
354+
StateContext: schema.ImportStatePassthroughContext,
355+
},
356+
```
357+
358+
For resources with composite IDs, the import function must parse the user-provided ID and populate any schema attributes that `Read` depends on:
359+
360+
```go
361+
func resourceGithubExampleImport(ctx context.Context, d *schema.ResourceData, meta any) ([]*schema.ResourceData, error) {
362+
owner, name, err := parseID2(d.Id())
363+
if err != nil {
364+
return nil, err
365+
}
366+
367+
// Set attributes that Read needs to make API calls
368+
d.Set("owner", owner)
369+
// Re-build a normalized ID if needed
370+
id, err := buildID(owner, name)
371+
if err != nil {
372+
return nil, err
373+
}
374+
d.SetId(id)
375+
376+
return []*schema.ResourceData{d}, nil
377+
}
378+
```
379+
380+
**Key principle:** Import sets the minimum state required for `Read` to fetch the full resource. `Read` then populates all remaining attributes.
381+
345382
### State Migrations
346383

347384
When adding new fields or changing schema, use `StateUpgraders` (not the deprecated `MigrateState`):

0 commit comments

Comments
 (0)