helper/resource: add UniqueId() helper

A generic function for provider resources to use to get a unique
identifier.
This commit is contained in:
Paul Hinze 2015-04-22 12:53:05 -05:00
parent f0c8ae7d3f
commit d1106e9e22
2 changed files with 50 additions and 0 deletions

25
helper/resource/id.go Normal file
View File

@ -0,0 +1,25 @@
package resource
import (
"crypto/rand"
"encoding/base32"
"fmt"
"strings"
)
const UniqueIdPrefix = `terraform-`
// Helper for a resource to generate a unique identifier
//
// This uses a simple RFC 4122 v4 UUID with some basic cosmetic filters
// applied (remove padding, downcase) to help distinguishing visually between
// identifiers.
func UniqueId() string {
var uuid [16]byte
rand.Read(uuid[:])
return fmt.Sprintf("%s%s", UniqueIdPrefix,
strings.ToLower(
strings.Replace(
base32.StdEncoding.EncodeToString(uuid[:]),
"=", "", -1)))
}

View File

@ -0,0 +1,25 @@
package resource
import (
"strings"
"testing"
)
func TestUniqueId(t *testing.T) {
iterations := 10000
ids := make(map[string]struct{})
var id string
for i := 0; i < iterations; i++ {
id = UniqueId()
if _, ok := ids[id]; ok {
t.Fatalf("Got duplicated id! %s", id)
}
if !strings.HasPrefix(id, "terraform-") {
t.Fatalf("Unique ID didn't have terraform- prefix! %s", id)
}
ids[id] = struct{}{}
}
}