Skip to content

Commit 31922e3

Browse files
committed
add import to random_pet resource #184
1 parent 1936b5c commit 31922e3

File tree

3 files changed

+37
-0
lines changed

3 files changed

+37
-0
lines changed

docs/resources/pet.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,4 +54,12 @@ resource "aws_instance" "server" {
5454

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

57+
## Import
5758

59+
Import is supported using the following syntax:
60+
61+
```shell
62+
# Random Pet can be imported with format: pet_name,separator,prefix
63+
64+
terraform import random_pet.example pet_name,separator,prefix
65+
```
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Random Pet can be imported with format: pet_name,separator,prefix
2+
3+
terraform import random_pet.example pet_name,separator,prefix

internal/provider/resource_pet.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77

88
petname "github.com/dustinkirkland/golang-petname"
99
"github.com/hashicorp/terraform-plugin-framework/diag"
10+
"github.com/hashicorp/terraform-plugin-framework/path"
1011
"github.com/hashicorp/terraform-plugin-framework/resource"
1112
"github.com/hashicorp/terraform-plugin-framework/tfsdk"
1213
"github.com/hashicorp/terraform-plugin-framework/types"
@@ -148,6 +149,31 @@ func (r *petResource) Update(ctx context.Context, req resource.UpdateRequest, re
148149
func (r *petResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
149150
}
150151

152+
func (r *petResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
153+
idParts := strings.Split(req.ID, ",")
154+
if len(idParts) != 3 {
155+
resp.Diagnostics.AddError(
156+
"Unexpected Import Identifier",
157+
fmt.Sprintf("Expected import identifier with format: pet_name,separator,prefix. Got: %q", req.ID),
158+
)
159+
return
160+
}
161+
162+
id, separator, prefix := idParts[0], idParts[1], idParts[2]
163+
164+
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), id)...)
165+
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("length"), int64(len(id)))...)
166+
167+
if separator == "" {
168+
separator = "-"
169+
}
170+
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("separator"), separator)...)
171+
172+
if prefix != "" {
173+
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("prefix"), prefix)...)
174+
}
175+
}
176+
151177
type petModelV0 struct {
152178
ID types.String `tfsdk:"id"`
153179
Keepers types.Map `tfsdk:"keepers"`

0 commit comments

Comments
 (0)