github.com/posener/terraform@v0.11.0-beta1.0.20171103235147-645df36af025/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  // Helper for a resource to generate a unique identifier w/ given prefix
    22  //
    23  // After the prefix, the ID consists of an incrementing 26 digit value (to match
    24  // previous timestamp output).  After the prefix, the ID consists of a timestamp
    25  // and an incrementing 8 hex digit value The timestamp means that multiple IDs
    26  // created with the same prefix will sort in the order of their creation, even
    27  // across multiple terraform executions, as long as the clock is not turned back
    28  // between calls, and as long as any given terraform execution generates fewer
    29  // than 4 billion IDs.
    30  func PrefixedUniqueId(prefix string) string {
    31  	// Be precise to 4 digits of fractional seconds, but remove the dot before the
    32  	// fractional seconds.
    33  	timestamp := strings.Replace(
    34  		time.Now().UTC().Format("20060102150405.0000"), ".", "", 1)
    35  
    36  	idMutex.Lock()
    37  	defer idMutex.Unlock()
    38  	idCounter++
    39  	return fmt.Sprintf("%s%s%08x", prefix, timestamp, idCounter)
    40  }