random_id

Stores small snippets of code or other types of data that can be easily referenced in the future

random_id

This Terraform configuration code creates a random identifier using the “random_id” resource provided by the “random” Terraform provider. The randomly generated identifier can be used in other parts of the Terraform configuration by referencing it as “random_id.this.hex”. This would return the hexadecimal representation of the randomly generated identifier.

This functionality can be helpful in scenarios where a unique identifier is required for a resource.

resource "random_id" "this" {
  byte_length = 16
}

To use it in a resource.

name = "st${var.prefix}${var.environment}${lower(random_id.this.hex)}"

The byte_length parameter in the random_id resource specifies the length of the randomly generated identifier in bytes.

In the example Terraform code, byte_length is set to 4, which means that the generated identifier will have a length of 4 bytes or 32 bits. The actual value of the identifier will be a random string of 32 hexadecimal characters (0-9, A-F), which can be obtained by referencing the generated resource as random_id.this.hex.

The byte_length parameter can be set to any positive integer value to generate an identifier of the desired length in bytes. However, it’s important to note that increasing the length of the identifier will also increase the likelihood of collisions or duplicate values, so choosing a length appropriate for the specific use case is crucial.

For most purposes, a byte length of 8 (64 bits) or more is considered sufficiently unique for most use cases. It would result in a random identifier that is 16 characters long when represented in hexadecimal form.

Example byte length values

byte_length = 2 | random_id_value = 54d5

byte_length = 4 | random_id_value = 350557e4

byte_length = 8 | random_id_value = 93879a089729

Last modified July 21, 2024: update (e2ae86c)