From d1106e9e22f97c8bca3d454317491b8feecf0e1f Mon Sep 17 00:00:00 2001 From: Paul Hinze Date: Wed, 22 Apr 2015 12:53:05 -0500 Subject: [PATCH] helper/resource: add UniqueId() helper A generic function for provider resources to use to get a unique identifier. --- helper/resource/id.go | 25 +++++++++++++++++++++++++ helper/resource/id_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 helper/resource/id.go create mode 100644 helper/resource/id_test.go diff --git a/helper/resource/id.go b/helper/resource/id.go new file mode 100644 index 000000000..3bb68c51d --- /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 000000000..245155b7a --- /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{}{} + } +}