diff --git a/helper/resource/id.go b/helper/resource/id.go new file mode 100644 index 0000000000..3bb68c51d6 --- /dev/null +++ b/helper/resource/id.go @@ -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))) +} diff --git a/helper/resource/id_test.go b/helper/resource/id_test.go new file mode 100644 index 0000000000..245155b7ae --- /dev/null +++ b/helper/resource/id_test.go @@ -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{}{} + } +}