Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace usage of deprecated fields in schema.Resource #231

Merged
merged 23 commits into from
Apr 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
44d7e05
Running gofmt (#230)
bendbennett Apr 12, 2022
26911a7
Replace usage of Create field with CreateContext in resource_id (#230)
bendbennett Apr 12, 2022
5720b72
Replace usgae of Read field with ReadContext in resource_id (#230)
bendbennett Apr 12, 2022
d262d66
Using blank identifier for unused context passed to RepopulateEncodin…
bendbennett Apr 12, 2022
c63329b
Replace usage of Delete field with DeleteContext in resource_id (#230)
bendbennett Apr 12, 2022
3bb503a
Replace usage of State field with StateContext in resource_id (#230)
bendbennett Apr 12, 2022
ebf4911
Replace usage of Create field with CreateContext in resource_integer …
bendbennett Apr 12, 2022
d63ba15
Replace usage of Read field with ReadContext in resource_integer
bendbennett Apr 12, 2022
2fce511
Replace usage of Delete field with DeleteContext in resource_integer
bendbennett Apr 12, 2022
79d154b
Replace usage of State field with StateContext in resource_integer
bendbennett Apr 12, 2022
9f8012a
Replace usage of Create field with CreateContext in resource_password…
bendbennett Apr 12, 2022
2ea5683
Replace usage of Read field with ReadContext in resource_password and…
bendbennett Apr 12, 2022
9d51c60
Replace usage of Delete field with DeleteContext in resource_password…
bendbennett Apr 12, 2022
708d4ef
Replace usage of Create field with CreateContext in resource_pet (#230)
bendbennett Apr 12, 2022
726acdc
Replace usage of Create field with CreateContext in resource_pet (#230)
bendbennett Apr 12, 2022
b47c746
Replace usage of Delete field with DeleteContext in resource_pet (#230)
bendbennett Apr 12, 2022
1d6b7b1
Replace usage of Create, Read and Delete fields with CreateContext, R…
bendbennett Apr 12, 2022
d47e381
Add comment to justify not replacing deprecated MigrateState field in…
bendbennett Apr 12, 2022
082dce6
Replace usage of Create, Read, Delete and State fields with CreateCon…
bendbennett Apr 12, 2022
1ec934b
Sorting imports (#230)
bendbennett Apr 12, 2022
445ab1d
Consolidating DeleteContext to a shared func (#230)
bendbennett Apr 13, 2022
c83c891
Moving DeleteContext func to provider (#230)
bendbennett Apr 13, 2022
5ed4718
Renaming DeleteContext func to RemoveResourceFromState (#230)
bendbennett Apr 13, 2022
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
7 changes: 7 additions & 0 deletions internal/provider/provider.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package provider

import (
"context"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

Expand All @@ -24,3 +26,8 @@ func New() *schema.Provider {
},
}
}

func RemoveResourceFromState(_ context.Context, d *schema.ResourceData, _ interface{}) diag.Diagnostics {
d.SetId("")
return nil
}
36 changes: 22 additions & 14 deletions internal/provider/resource_id.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
package provider

import (
"context"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"math/big"
"strings"

"github.com/hashicorp/errwrap"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

Expand All @@ -28,11 +29,11 @@ the ` + "`create_before_destroy`" + ` lifecycle flag set to avoid conflicts with
unique names during the brief period where both the old and new resources
exist concurrently.
`,
Create: CreateID,
Read: RepopulateEncodings,
Delete: schema.RemoveFromState,
CreateContext: CreateID,
ReadContext: RepopulateEncodings,
DeleteContext: RemoveResourceFromState,
Importer: &schema.ResourceImporter{
State: ImportID,
StateContext: ImportID,
},

Schema: map[string]*schema.Schema{
Expand Down Expand Up @@ -95,31 +96,38 @@ exist concurrently.
}
}

func CreateID(d *schema.ResourceData, meta interface{}) error {
func CreateID(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
var diags diag.Diagnostics
byteLength := d.Get("byte_length").(int)
bytes := make([]byte, byteLength)

n, err := rand.Reader.Read(bytes)
if n != byteLength {
return errors.New("generated insufficient random bytes")
return append(diags, diag.Errorf("generated insufficient random bytes: %s", err)...)
}
if err != nil {
return errwrap.Wrapf("error generating random bytes: {{err}}", err)
return append(diags, diag.Errorf("error generating random bytes: %s", err)...)
}

b64Str := base64.RawURLEncoding.EncodeToString(bytes)
d.SetId(b64Str)

return RepopulateEncodings(d, meta)
repopEncsDiags := RepopulateEncodings(ctx, d, meta)
if repopEncsDiags != nil {
return append(diags, repopEncsDiags...)
}

return diags
}

func RepopulateEncodings(d *schema.ResourceData, _ interface{}) error {
func RepopulateEncodings(_ context.Context, d *schema.ResourceData, _ interface{}) diag.Diagnostics {
var diags diag.Diagnostics
prefix := d.Get("prefix").(string)
base64Str := d.Id()

bytes, err := base64.RawURLEncoding.DecodeString(base64Str)
if err != nil {
return errwrap.Wrapf("Error decoding ID: {{err}}", err)
return append(diags, diag.Errorf("error decoding ID: %s", err)...)
}

b64StdStr := base64.StdEncoding.EncodeToString(bytes)
Expand All @@ -138,7 +146,7 @@ func RepopulateEncodings(d *schema.ResourceData, _ interface{}) error {
return nil
}

func ImportID(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
func ImportID(_ context.Context, d *schema.ResourceData, _ interface{}) ([]*schema.ResourceData, error) {
id := d.Id()

sep := strings.LastIndex(id, ",")
Expand All @@ -149,7 +157,7 @@ func ImportID(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData,

bytes, err := base64.RawURLEncoding.DecodeString(id)
if err != nil {
return nil, errwrap.Wrapf("Error decoding ID: {{err}}", err)
return nil, fmt.Errorf("error decoding ID: %w", err)
}

d.Set("byte_length", len(bytes))
Expand Down
20 changes: 13 additions & 7 deletions internal/provider/resource_integer.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package provider

import (
"context"
"fmt"
"strconv"
"strings"

"github.com/hashicorp/errwrap"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

Expand All @@ -17,11 +19,11 @@ func resourceInteger() *schema.Resource {
"This resource can be used in conjunction with resources that have the `create_before_destroy` " +
"lifecycle flag set, to avoid conflicts with unique names during the brief period where both the " +
"old and new resources exist concurrently.",
Create: CreateInteger,
Read: schema.Noop,
Delete: schema.RemoveFromState,
CreateContext: CreateInteger,
ReadContext: schema.NoopContext,
DeleteContext: RemoveResourceFromState,
Importer: &schema.ResourceImporter{
State: ImportInteger,
StateContext: ImportInteger,
},

Schema: map[string]*schema.Schema{
Expand Down Expand Up @@ -70,13 +72,17 @@ func resourceInteger() *schema.Resource {
}
}

func CreateInteger(d *schema.ResourceData, meta interface{}) error {
func CreateInteger(_ context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
var diags diag.Diagnostics
min := d.Get("min").(int)
max := d.Get("max").(int)
seed := d.Get("seed").(string)

if max <= min {
return fmt.Errorf("Minimum value needs to be smaller than maximum value")
return append(diags, diag.Diagnostic{
Severity: diag.Error,
Summary: "minimum value needs to be smaller than maximum value",
})
}
rand := NewRand(seed)
number := rand.Intn((max+1)-min) + min
Expand All @@ -87,7 +93,7 @@ func CreateInteger(d *schema.ResourceData, meta interface{}) error {
return nil
}

func ImportInteger(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
func ImportInteger(_ context.Context, d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
parts := strings.Split(d.Id(), ",")
if len(parts) != 3 && len(parts) != 4 {
return nil, fmt.Errorf("Invalid import usage: expecting {result},{min},{max} or {result},{min},{max},{seed}")
Expand Down
8 changes: 4 additions & 4 deletions internal/provider/resource_password.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ func resourcePassword() *schema.Resource {
"data handling in the [Terraform documentation](https://www.terraform.io/docs/language/state/sensitive-data.html).\n" +
"\n" +
"This resource *does* use a cryptographic random number generator.",
Create: createStringFunc(true),
Read: readNil,
Delete: schema.RemoveFromState,
Schema: stringSchemaV1(true),
CreateContext: createStringFunc(true),
ReadContext: readNil,
DeleteContext: RemoveResourceFromState,
Schema: stringSchemaV1(true),
Importer: &schema.ResourceImporter{
StateContext: importStringFunc(true),
},
Expand Down
11 changes: 6 additions & 5 deletions internal/provider/resource_pet.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
package provider

import (
"context"
"fmt"
"strings"

petname "github.com/dustinkirkland/golang-petname"

"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

Expand All @@ -22,9 +23,9 @@ func resourcePet() *schema.Resource {
"This resource can be used in conjunction with resources that have the `create_before_destroy` " +
"lifecycle flag set, to avoid conflicts with unique names during the brief period where both the old " +
"and new resources exist concurrently.",
Create: CreatePet,
Read: schema.Noop,
Delete: schema.RemoveFromState,
CreateContext: CreatePet,
ReadContext: schema.NoopContext,
DeleteContext: RemoveResourceFromState,

Schema: map[string]*schema.Schema{
"keepers": {
Expand Down Expand Up @@ -67,7 +68,7 @@ func resourcePet() *schema.Resource {
}
}

func CreatePet(d *schema.ResourceData, meta interface{}) error {
func CreatePet(_ context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
length := d.Get("length").(int)
separator := d.Get("separator").(string)
prefix := d.Get("prefix").(string)
Expand Down
11 changes: 7 additions & 4 deletions internal/provider/resource_shuffle.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
package provider

import (
"context"

"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

func resourceShuffle() *schema.Resource {
return &schema.Resource{
Description: "The resource `random_shuffle` generates a random permutation of a list of strings " +
"given as an argument.",
Create: CreateShuffle,
Read: schema.Noop,
Delete: schema.RemoveFromState,
CreateContext: CreateShuffle,
ReadContext: schema.NoopContext,
DeleteContext: RemoveResourceFromState,

Schema: map[string]*schema.Schema{
"keepers": {
Expand Down Expand Up @@ -71,7 +74,7 @@ func resourceShuffle() *schema.Resource {
}
}

func CreateShuffle(d *schema.ResourceData, _ interface{}) error {
func CreateShuffle(_ context.Context, d *schema.ResourceData, _ interface{}) diag.Diagnostics {
input := d.Get("input").([]interface{})
seed := d.Get("seed").(string)

Expand Down
8 changes: 5 additions & 3 deletions internal/provider/resource_string.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@ func resourceString() *schema.Resource {
"Historically this resource's intended usage has been ambiguous as the original example used " +
"it in a password. For backwards compatibility it will continue to exist. For unique ids please " +
"use [random_id](id.html), for sensitive random values please use [random_password](password.html).",
Create: createStringFunc(false),
Read: readNil,
Delete: schema.RemoveFromState,
CreateContext: createStringFunc(false),
ReadContext: readNil,
DeleteContext: RemoveResourceFromState,
// MigrateState is deprecated but the implementation is being left in place as per the
// [SDK documentation](https://github.com/hashicorp/terraform-plugin-sdk/blob/main/helper/schema/resource.go#L91).
MigrateState: resourceRandomStringMigrateState,
SchemaVersion: 1,
Schema: stringSchemaV1(false),
Expand Down
18 changes: 11 additions & 7 deletions internal/provider/resource_uuid.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package provider

import (
"context"

"github.com/hashicorp/errwrap"
"github.com/hashicorp/go-uuid"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

Expand All @@ -13,11 +16,11 @@ func resourceUuid() *schema.Resource {
"\n" +
"This resource uses [hashicorp/go-uuid](https://github.com/hashicorp/go-uuid) to generate a " +
"UUID-formatted string for use with services needed a unique string identifier.",
Create: CreateUuid,
Read: schema.Noop,
Delete: schema.RemoveFromState,
CreateContext: CreateUuid,
ReadContext: schema.NoopContext,
DeleteContext: RemoveResourceFromState,
Importer: &schema.ResourceImporter{
State: ImportUuid,
StateContext: ImportUuid,
},

Schema: map[string]*schema.Schema{
Expand All @@ -44,17 +47,18 @@ func resourceUuid() *schema.Resource {
}
}

func CreateUuid(d *schema.ResourceData, meta interface{}) error {
func CreateUuid(_ context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
var diags diag.Diagnostics
result, err := uuid.GenerateUUID()
if err != nil {
return errwrap.Wrapf("error generating uuid: {{err}}", err)
return append(diags, diag.Errorf("error generating uuid: %s", err)...)
}
d.Set("result", result)
d.SetId(result)
return nil
}

func ImportUuid(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
func ImportUuid(_ context.Context, d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
id := d.Id()
bytes, err := uuid.ParseUUID(id)
if err != nil {
Expand Down
19 changes: 11 additions & 8 deletions internal/provider/string.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
"math/big"
"sort"

"github.com/hashicorp/errwrap"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

Expand Down Expand Up @@ -123,12 +123,15 @@ func stringSchemaV1(sensitive bool) map[string]*schema.Schema {
}
}

func createStringFunc(sensitive bool) func(d *schema.ResourceData, meta interface{}) error {
return func(d *schema.ResourceData, meta interface{}) error {
func createStringFunc(sensitive bool) func(_ context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
return func(_ context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
const numChars = "0123456789"
const lowerChars = "abcdefghijklmnopqrstuvwxyz"
const upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var specialChars = "!@#$%&*()-_=+[]{}<>:?"
var (
specialChars = "!@#$%&*()-_=+[]{}<>:?"
diags diag.Diagnostics
)

length := d.Get("length").(int)
upper := d.Get("upper").(bool)
Expand Down Expand Up @@ -169,18 +172,18 @@ func createStringFunc(sensitive bool) func(d *schema.ResourceData, meta interfac
for k, v := range minMapping {
s, err := generateRandomBytes(&k, v)
if err != nil {
return errwrap.Wrapf("error generating random bytes: {{err}}", err)
return append(diags, diag.Errorf("error generating random bytes: %s", err)...)
}
result = append(result, s...)
}
s, err := generateRandomBytes(&chars, length-len(result))
if err != nil {
return errwrap.Wrapf("error generating random bytes: {{err}}", err)
return append(diags, diag.Errorf("error generating random bytes: %s", err)...)
}
result = append(result, s...)
order := make([]byte, len(result))
if _, err := rand.Read(order); err != nil {
return errwrap.Wrapf("error generating random bytes: {{err}}", err)
return append(diags, diag.Errorf("error generating random bytes: %s", err)...)
}
sort.Slice(result, func(i, j int) bool {
return order[i] < order[j]
Expand Down Expand Up @@ -209,7 +212,7 @@ func generateRandomBytes(charSet *string, length int) ([]byte, error) {
return bytes, nil
}

func readNil(d *schema.ResourceData, meta interface{}) error {
func readNil(_ context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
return nil
}

Expand Down
1 change: 1 addition & 0 deletions tools/tools.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//go:build tools
// +build tools

package tools
Expand Down