
The "random" Terraform provider generates random values inside your Terraform or OpenTofu configurations. It's handy when you need a unique or arbitrary value but don't want to hardcode it. A few things people use it for:
There are seven resources that the random provider supports in the Terraform configuration:
random_id: Generates a random identifierrandom_integer: Produces a random integer within a specified rangerandom_string: Creates a random string of charactersrandom_password: Generates a random passwordrandom_shuffle: Randomly shuffles a list of stringsrandom_pet: Randomly generate namesrandom_uuid: Randomly generates a UUIDThe random values are generated during the plan phase and stay the same across applies, unless you tell them to regenerate with the keepers argument, which we'll get to later.
Before anything else, you need to declare the provider so you can pull the random resources into the Terraform run:
Once the provider is set, you can start trying out the resources below:
The main use case for the random_id resource is to create random resource IDs, such as appending an ID to a name. This will allow you to keep a consistent naming convention:
The main use case for the random_integer resource is to create a random integer for testing scenarios and simulations.
The main use case for the random_string resource is to generate random strings for input. It's good for unique test values, as long as they're not sensitive. For sensitive values, use the random_password resource below.
The main use case for random_password is to generate random passwords or strings to improve security. Instead of relying on a human, this resource creates strong, unique passwords based on the rules you set:
The main use case for random_shuffle is to randomly shuffle a list of inputs. A use case for this is distributing resources across different AZs for high availability:
The main use case for this is to provide an easy way to generate unique, memorable names for resources without having to come up with them manually.
Nothing else is needed besides the resource when using random_UUID, as it calls go-uuid to generate the UUID:
By design, the values from the random provider stay the same on every new Terraform plan and apply, unless a "keeper" in the config file says otherwise. A keeper references an attribute in your Terraform code, and if that attribute changes, the random value changes with it. The point is to make the random resource behave predictably. For example, you might want an ec2 instance name to stay the same unless the AMI, instance type, or environment type changes:
The random Terraform provider is useful whenever you need generated values for testing and simulation, with the rules defined in code instead of left to a person. Once you've tried the basic resources, spend some time on the keepers argument. It's the piece that decides when a random value stays put and when it regenerates, and that behavior is easy to get wrong if you skip it.
