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

Breaking change: SDK v2 #118

Merged
merged 9 commits into from
Oct 2, 2020
Merged
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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
2 changes: 1 addition & 1 deletion .go-version
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1.14.0
1.15.0
11 changes: 2 additions & 9 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ services:
- docker
language: go
go:
- "1.14.x"
- stable
- tip
env:
- GO111MODULE=on GOFLAGS=-mod=vendor TF_VERSION=0.12.20
- GO111MODULE=on GOFLAGS=-mod=vendor

install:
# This script is used by the Travis build to install a cookie for
Expand All @@ -16,17 +16,10 @@ install:
# See: https://github.com/golang/go/issues/12933
- bash scripts/gogetcookie.sh

before_script:
- curl -fSL "https://releases.hashicorp.com/terraform/${TF_VERSION}/terraform_${TF_VERSION}_linux_amd64.zip" -o terraform.zip
- sudo unzip terraform.zip -d /opt/terraform
- sudo ln -s /opt/terraform/terraform /usr/bin/terraform
- rm -f terraform.zip

script:
- make test
- make testacc
- make vet
- make website-test

branches:
only:
Expand Down
19 changes: 2 additions & 17 deletions GNUmakefile
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
TEST?=$$(go list ./... |grep -v 'vendor')
GOFMT_FILES?=$$(find . -name '*.go' |grep -v vendor)
WEBSITE_REPO=github.com/hashicorp/terraform-website
PKG_NAME=random

default: build
Expand All @@ -11,7 +10,7 @@ build: fmtcheck
test: fmtcheck
go test -i $(TEST) || exit 1
echo $(TEST) | \
xargs -t -n4 go test $(TESTARGS) -timeout=30s -parallel=4
xargs -t -n4 go test $(TESTARGS) -timeout=120s -parallel=4

testacc: fmtcheck
TF_ACC=1 go test $(TEST) -v $(TESTARGS) -timeout 120m
Expand Down Expand Up @@ -43,19 +42,5 @@ test-compile:
fi
go test -c $(TEST) $(TESTARGS)

website:
ifeq (,$(wildcard $(GOPATH)/src/$(WEBSITE_REPO)))
echo "$(WEBSITE_REPO) not found in your GOPATH (necessary for layouts and assets), get-ting..."
git clone https://$(WEBSITE_REPO) $(GOPATH)/src/$(WEBSITE_REPO)
endif
@$(MAKE) -C $(GOPATH)/src/$(WEBSITE_REPO) website-provider PROVIDER_PATH=$(shell pwd) PROVIDER_NAME=$(PKG_NAME)

website-test:
ifeq (,$(wildcard $(GOPATH)/src/$(WEBSITE_REPO)))
echo "$(WEBSITE_REPO) not found in your GOPATH (necessary for layouts and assets), get-ting..."
git clone https://$(WEBSITE_REPO) $(GOPATH)/src/$(WEBSITE_REPO)
endif
@$(MAKE) -C $(GOPATH)/src/$(WEBSITE_REPO) website-provider-test PROVIDER_PATH=$(shell pwd) PROVIDER_NAME=$(PKG_NAME)

.PHONY: build test testacc vet fmt fmtcheck errcheck test-compile website website-test
.PHONY: build test testacc vet fmt fmtcheck errcheck test-compile

5 changes: 2 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
module github.com/terraform-providers/terraform-provider-random

go 1.14
go 1.15

require (
github.com/dustinkirkland/golang-petname v0.0.0-20170105215008-242afa0b4f8a
github.com/hashicorp/errwrap v1.0.0
github.com/hashicorp/go-uuid v1.0.1
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/hashicorp/terraform-plugin-sdk v1.11.0
github.com/hashicorp/terraform-plugin-sdk/v2 v2.0.3
)
410 changes: 322 additions & 88 deletions go.sum

Large diffs are not rendered by default.

26 changes: 26 additions & 0 deletions internal/provider/provider.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package provider

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

func init() {
schema.DescriptionKind = schema.StringMarkdown
}

// New returns a *schema.Provider.
func New() *schema.Provider {
return &schema.Provider{
Schema: map[string]*schema.Schema{},

ResourcesMap: map[string]*schema.Resource{
"random_id": resourceId(),
"random_shuffle": resourceShuffle(),
"random_pet": resourcePet(),
"random_string": resourceString(),
"random_password": resourcePassword(),
"random_integer": resourceInteger(),
"random_uuid": resourceUuid(),
},
}
}
30 changes: 30 additions & 0 deletions internal/provider/provider_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package provider

import (
"testing"

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

var testAccProviders map[string]*schema.Provider
var testAccProvider *schema.Provider

func init() {
testAccProvider = New()
testAccProviders = map[string]*schema.Provider{
"random": testAccProvider,
}
}

func TestProvider(t *testing.T) {
if err := New().InternalValidate(); err != nil {
t.Fatalf("err: %s", err)
}
}

func TestProvider_impl(t *testing.T) {
var _ *schema.Provider = New()
}

func testAccPreCheck(t *testing.T) {
}
153 changes: 153 additions & 0 deletions internal/provider/resource_id.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
package provider

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

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

func resourceId() *schema.Resource {
return &schema.Resource{
Description: `
The resource ` + "`random_id`" + ` generates random numbers that are intended to be
used as unique identifiers for other resources.

This resource *does* use a cryptographic random number generator in order
to minimize the chance of collisions, making the results of this resource
when a 16-byte identifier is requested of equivalent uniqueness to a
type-4 UUID.

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: CreateID,
Read: RepopulateEncodings,
Delete: schema.RemoveFromState,
Importer: &schema.ResourceImporter{
State: ImportID,
},

Schema: map[string]*schema.Schema{
"keepers": {
Description: "Arbitrary map of values that, when changed, will trigger recreation of " +
"resource. See [the main provider documentation](../index.html) for more information.",
Type: schema.TypeMap,
Optional: true,
ForceNew: true,
},

"byte_length": {
Description: "The number of random bytes to produce. The minimum value is 1, which produces " +
"eight bits of randomness.",
Type: schema.TypeInt,
Required: true,
ForceNew: true,
},

"prefix": {
Description: "Arbitrary string to prefix the output value with. This string is supplied as-is, " +
"meaning it is not guaranteed to be URL-safe or base64 encoded.",
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},

"b64_url": {
Description: "The generated id presented in base64, using the URL-friendly character set: " +
"case-sensitive letters, digits and the characters `_` and `-`.",
Type: schema.TypeString,
Computed: true,
},

"b64_std": {
Description: "The generated id presented in base64 without additional transformations.",
Type: schema.TypeString,
Computed: true,
},

"hex": {
Description: "The generated id presented in padded hexadecimal digits. This result will " +
"always be twice as long as the requested byte length.",
Type: schema.TypeString,
Computed: true,
},

"dec": {
Description: "The generated id presented in non-padded decimal digits.",
Type: schema.TypeString,
Computed: true,
},
},
}
}

func CreateID(d *schema.ResourceData, meta interface{}) error {
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")
}
if err != nil {
return errwrap.Wrapf("error generating random bytes: {{err}}", err)
}

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

return RepopulateEncodings(d, meta)
}

func RepopulateEncodings(d *schema.ResourceData, _ interface{}) error {
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)
}

b64StdStr := base64.StdEncoding.EncodeToString(bytes)
hexStr := hex.EncodeToString(bytes)

bigInt := big.Int{}
bigInt.SetBytes(bytes)
decStr := bigInt.String()

d.Set("b64_url", prefix+base64Str)
d.Set("b64_std", prefix+b64StdStr)

d.Set("hex", prefix+hexStr)
d.Set("dec", prefix+decStr)

return nil
}

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

sep := strings.LastIndex(id, ",")
if sep != -1 {
d.Set("prefix", id[:sep])
id = id[sep+1:]
}

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

d.Set("byte_length", len(bytes))
d.SetId(id)

return []*schema.ResourceData{d}, nil
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
package random
package provider

import (
"fmt"
"testing"

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

type idLens struct {
Expand Down Expand Up @@ -62,15 +62,11 @@ func testAccResourceIDCheck(id string, want *idLens) resource.TestCheckFunc {
return fmt.Errorf("No ID is set")
}

b64Str := rs.Primary.Attributes["b64"]
b64UrlStr := rs.Primary.Attributes["b64_url"]
b64StdStr := rs.Primary.Attributes["b64_std"]
hexStr := rs.Primary.Attributes["hex"]
decStr := rs.Primary.Attributes["dec"]

if got, want := len(b64Str), want.b64Len; got != want {
return fmt.Errorf("base64 string length is %d; want %d", got, want)
}
if got, want := len(b64UrlStr), want.b64UrlLen; got != want {
return fmt.Errorf("base64 URL string length is %d; want %d", got, want)
}
Expand Down
Loading