github.com/turtlemonvh/terraform@v0.6.9-0.20151204001754-8e40b6b855e8/helper/resource/id.go (about)

     1  package resource
     2  
     3  import (
     4  	"crypto/rand"
     5  	"encoding/base32"
     6  	"fmt"
     7  	"strings"
     8  )
     9  
    10  const UniqueIdPrefix = `terraform-`
    11  
    12  // Helper for a resource to generate a unique identifier w/ default prefix
    13  func UniqueId() string {
    14  	return PrefixedUniqueId(UniqueIdPrefix)
    15  }
    16  
    17  // Helper for a resource to generate a unique identifier w/ given prefix
    18  //
    19  // This uses a simple RFC 4122 v4 UUID with some basic cosmetic filters
    20  // applied (base32, remove padding, downcase) to make visually distinguishing
    21  // identifiers easier.
    22  func PrefixedUniqueId(prefix string) string {
    23  	return fmt.Sprintf("%s%s", prefix,
    24  		strings.ToLower(
    25  			strings.Replace(
    26  				base32.StdEncoding.EncodeToString(uuidV4()),
    27  				"=", "", -1)))
    28  }
    29  
    30  func uuidV4() []byte {
    31  	var uuid [16]byte
    32  
    33  	// Set all the other bits to randomly (or pseudo-randomly) chosen
    34  	// values.
    35  	rand.Read(uuid[:])
    36  
    37  	// Set the two most significant bits (bits 6 and 7) of the
    38  	// clock_seq_hi_and_reserved to zero and one, respectively.
    39  	uuid[8] = (uuid[8] | 0x80) & 0x8f
    40  
    41  	// Set the four most significant bits (bits 12 through 15) of the
    42  	// time_hi_and_version field to the 4-bit version number from Section 4.1.3.
    43  	uuid[6] = (uuid[6] | 0x40) & 0x4f
    44  
    45  	return uuid[:]
    46  }