How to Generate a Random Number/String in Terraform
If you need to generate a random number or string in Terraform, then you can use the following:
This is useful when you need unique names for resources like S3 buckets or database instances that require globally unique identifiers. I use this pattern to append a random suffix to resource names so they don’t collide across environments.
The keepers block controls when a new random value gets generated — using timestamp() means it regenerates on every apply, which you probably don’t want in production. For stable random values that only change when a specific input changes, use a meaningful keeper like a project name or environment variable instead.
resource "random_id" "myrandom" {
keepers = {
first = "${timestamp()}"
}
byte_length = 8
}
Then refer to it as:
random_id.myrandom.hex