Skip to content

Commit

Permalink
add import to random_pet resource hashicorp#184
Browse files Browse the repository at this point in the history
  • Loading branch information
wakeful committed Sep 27, 2024
1 parent 090d013 commit 5549716
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 1 deletion.
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

0 comments on commit 5549716

Please sign in to comment.