Terraform – FotD – uuid()

This is part of an ongoing series of posts documenting the built-in interpolation functions in Terraform. For more information, check out the beginning post. In this post I am going to cover the uuid() function. The example file is on GitHub here.

What is it?

Function name: uuid()

Returns: Takes no arguments. Returns a string with a UUID conforming to RFC 4122 v4.

Example:

# Returns something like XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
output "uuid_output" {
  value = "${uuid()}"
}

Example file:

##############################################
# Function: uuid
##############################################
##############################################
# Variables
##############################################

##############################################
# Resources
##############################################


##############################################
# Outputs
##############################################
output "1_uuid_basic" {
  value = "${uuid()}"
}

Run the following from the uuid folder to get example output for a number of different cases:

#No arguments for function
terraform apply

Why use it?

Having a UUID is going to be pretty useful when generating new resources. Especially if the provider for those resources doesn’t have a UUID generation mechanism. AWS resources all have an identifier associated with them, but that might not be the case everywhere. The important thing to remember is that this function will generate a new, unique ID each time it is run. And that means that if you run it against the same resource it would change the ID each time. That’s why you’ll need to add the ignore_changes lifecycle attribute to prevent that behavior.

Lessons Learned

The official docs don’t actually explain what RFC 4122 is, or how the UUID is constructed. For that, you can turn to the RFC itself. The UUID is a 128-bit value generated by an algorithm in order to be unique across time and space. It also doesn’t need a central authority to register each ID with, which simplifies the creation of UUIDs by a lot. 2 ^ 128 potential values works out to about 3.4 X 10^38. That’s the same address space being used by IPv6. So like, that’s a lot of values. The output from Terraform formats the value as:

32 bits - 16 bits - 16 bits - 16 bits - 48 bits

I won’t go into too much more detail, but basically the fields correspond to the following:

time values - time values - time values - clock sequence - node value

The actual calculation of the values depends on the version in use. Version 4 is meant for creating unique values from psuedo-random numbers. The whole RFC was pretty fascinating, I recommend reading it!

Coming up next is the values() function.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.