10 const UniqueIdPrefix = `terraform-`
12 // idCounter is a monotonic counter for generating ordered unique ids.
13 var idMutex sync.Mutex
16 // Helper for a resource to generate a unique identifier w/ default prefix
17 func UniqueId() string {
18 return PrefixedUniqueId(UniqueIdPrefix)
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
26 // Helper for a resource to generate a unique identifier w/ given prefix
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)
42 defer idMutex.Unlock()
44 return fmt.Sprintf("%s%s%08x", prefix, timestamp, idCounter)