Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions docs/resources/pet.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,13 @@ resource "aws_instance" "server" {
### Read-Only

- `id` (String) The random pet name.

## Import

Import is supported using the following syntax:

```shell
# Random Pet can be imported with format: pet_name,separator,prefix

terraform import random_pet.example pet_name,separator,prefix
```
3 changes: 3 additions & 0 deletions examples/resources/random_pet/import.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Random Pet can be imported with format: pet_name,separator,prefix

terraform import random_pet.example pet_name,separator,prefix
42 changes: 41 additions & 1 deletion internal/provider/resource_pet.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@ import (
mapplanmodifiers "github.com/terraform-providers/terraform-provider-random/internal/planmodifiers/map"
)

var _ resource.Resource = (*petResource)(nil)
var (
_ resource.Resource = (*petResource)(nil)
_ resource.ResourceWithImportState = (*petResource)(nil)
)

func NewPetResource() resource.Resource {
return &petResource{}
Expand Down Expand Up @@ -151,6 +154,43 @@ func (r *petResource) Update(ctx context.Context, req resource.UpdateRequest, re
func (r *petResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
}

func (r *petResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
parts := strings.Split(req.ID, ",")
if len(parts) != 3 {
resp.Diagnostics.AddError(
"Unexpected Import Identifier",
fmt.Sprintf("Expected import identifier with format: pet_name,separator,prefix. Got: %q", req.ID),
)
return
}

id, separator, prefix := parts[0], parts[1], parts[2]
if separator == "" {
separator = "-"
}

nameLength := len(strings.Split(id, separator))

prefixVal := types.StringNull()
if prefix != "" {
prefixVal = types.StringValue(prefix)
}

state := petModelV0{
ID: types.StringValue(id),
Length: types.Int64Value(int64(nameLength)),
Prefix: prefixVal,
Separator: types.StringValue(separator),
Keepers: types.MapNull(types.StringType),
}

diags := resp.State.Set(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
}

type petModelV0 struct {
ID types.String `tfsdk:"id"`
Keepers types.Map `tfsdk:"keepers"`
Expand Down