github.com/gavriloga/terraform@v0.11.12-beta1/helper/resource/id.go (about)

     1  package resource
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  	"sync"
     7  	"time"
     8  )
     9  
    10  const UniqueIdPrefix = `terraform-`
    11  
    12  // idCounter is a monotonic counter for generating ordered unique ids.
    13  var idMutex sync.Mutex
    14  var idCounter uint32
    15  
    16  // Helper for a resource to generate a unique identifier w/ default prefix
    17  func UniqueId() string {
    18  	return PrefixedUniqueId(UniqueIdPrefix)
    19  }
    20  
    21  // UniqueIDSuffixLength is the string length of the suffix generated by
    22  // PrefixedUniqueId. This can be used by length validation functions to
    23  // ensure prefixes are the correct length for the target field.
    24  const UniqueIDSuffixLength = 26
    25  
    26  // Helper for a resource to generate a unique identifier w/ given prefix
    27  //
    28  // After the prefix, the ID consists of an incrementing 26 digit value (to match
    29  // previous timestamp output).  After the prefix, the ID consists of a timestamp
    30  // and an incrementing 8 hex digit value The timestamp means that multiple IDs
    31  // created with the same prefix will sort in the order of their creation, even
    32  // across multiple terraform executions, as long as the clock is not turned back
    33  // between calls, and as long as any given terraform execution generates fewer
    34  // than 4 billion IDs.
    35  func PrefixedUniqueId(prefix string) string {
    36  	// Be precise to 4 digits of fractional seconds, but remove the dot before the
    37  	// fractional seconds.
    38  	timestamp := strings.Replace(
    39  		time.Now().UTC().Format("20060102150405.0000"), ".", "", 1)
    40  
    41  	idMutex.Lock()
    42  	defer idMutex.Unlock()
    43  	idCounter++
    44  	return fmt.Sprintf("%s%s%08x", prefix, timestamp, idCounter)
    45  }