The Terraform random provider is used to generate random values such as strings, integers, and passwords, typically for unique resource names or secrets during infrastructure deployment. It is a local-only provider that does not interact with any cloud platform like AWS, Azure, or GCP. Instead, it operates purely locally within Terraform, producing random data that can be reused and stored in the Terraform state file. This means that once a random value is generated, Terraform remembers it across runs, ensuring consistency between terraform plan and terraform apply operations.
Terraform preserves the generated value across runs unless you manually replace or destroy the resource. This ensures that names remain consistent across plan and apply cycles, even if the infrastructure changes around them. The random values are generated only once when you first apply your configuration, and they remain stable and consistent unless the resource is explicitly replaced or destroyed. Terraform stores the generated random value in its state file, so the same random value will persist across future applies, ensuring reproducibility.
It is commonly used to add randomness or uniqueness to your infrastructure while still keeping that randomness deterministic within the context of Terraform’s state. Destroying or replacing the random resource or losing its state will generate a new value. Use the keepers map to control when a value rotates. To rotate on demand, you can apply with -replace=RESOURCE_ADDRESS.
What the Random Provider Does
The Random provider supports the use of randomness within Terraform configurations. The provider resources can be used to generate a random id, integer, password, pet, shuffle, string or uuid. Official documentation on how to use this provider can be found on the Terraform Registry.
The provider does not create remote resources. It is a pure data generation layer. This makes it ideal for naming, entropy, and secret generation where stability across applies is required but true randomness at creation time is desired.
Key points
- The provider operates locally and does not call cloud APIs.
- Generated values are written to Terraform state and reused on subsequent runs.
- Consistency is maintained between plan and apply.
- Rotation is explicit via resource replacement, state loss, or keepers.
Core Resources Overview
Each resource serves a specific purpose, from generating secure credentials to creating fun but unique names.
| Resource | Output Type | Typical Use |
|---|---|---|
| random_string | Alphanumeric string | Resource naming suffixes, bucket names |
| random_integer | Integer within range | Unique numeric identifiers, allocation |
| random_password | Complex password | Database credentials, secrets |
| random_id | Opaque hex or base64 | Tokens, entropy |
| random_pet | Readable pet names | Human friendly names like bright-otter |
| random_shuffle | Random permutation of list | Picking choices from known list |
The randomstring resource generates random alphanumeric strings for resource naming. The randominteger resource picks a random integer within a specified range. The randompassword resource creates secure, complex passwords for databases or systems. The randomid resource provides opaque IDs as hex or base64 for tokens or entropy. The randompet resource creates readable pet names like bright-otter. The randomshuffle resource returns a random reordering so you can pick one or more valid choices from a known list.
State Persistence and Determinism
Terraform’s Random provider doesn’t interact with any cloud platform. It operates purely locally within Terraform, producing random data that can be reused and stored in the Terraform state file. This means that once a random value is generated, Terraform remembers it across runs, ensuring consistency between terraform plan and terraform apply operations.
This deterministic behavior is critical for infrastructure. A name generated on first apply will not change on the next plan unless the resource is intentionally replaced. That prevents cascading updates to dependent resources.
Destroying or replacing the random resource or losing its state will generate a new value. If the state file is lost, the next apply will treat the resource as new and generate a fresh random value. This can cause drift or breakage for resources that depend on the value.
Provider Declaration and Usage Patterns
Once the provider is declared, you can use resources like randomstring, randominteger, randompassword, randomid, randompet, and randomshuffle.
A minimal provider declaration is shown below.
terraform {
required_providers {
random = {
source = "hashicorp/random"
version = "~> 3.0"
}
}
}
After declaration, resources are referenced in configuration and their outputs can be interpolated into other resources.
Resource-Specific Behaviors
random_string for unique naming
One of the most common use cases for the Terraform random provider is to generate unique strings for naming resources. This ensures that resource names don’t conflict, especially in shared environments or across multiple deployments.
In this example, we’ll use the random_string resource to generate a random suffix for an S3 bucket name in AWS. S3 bucket names must be globally unique, so appending a random string ensures uniqueness without manual naming.
In this configuration, the random_string resource generates a six-character lowercase string. The result is then interpolated into the S3 bucket name, producing something like app-data-xt9hqp. Each terraform apply run will reuse the same string unless the resource is explicitly replaced.
```
resource "random_string" "suffix" {
length = 6
lower = true
upper = false
special = false
numeric = false
}
resource "awss3bucket" "example" {
bucket = "app-data-${random_string.suffix.result}"
}
```
random_password for secrets
Security-sensitive resources like databases often require passwords that are not hardcoded. The random_password resource allows you to create a strong, secure password dynamically and store it safely within Terraform’s state.
The following example generates a random password for an RDS instance. It ensures that the password contains a mix of uppercase, lowercase, and special characters for compliance with AWS security recommendations.
```
resource "randompassword" "db" {
length = 16
special = true
overridespecial = "!@#%^&*"
}
resource "awsdbinstance" "example" {
password = random_password.db.result
}
```
The random_password resource allows you to create a strong, secure password dynamically and store it safely within Terraform’s state.
random_integer for allocation
Example 3: Using random integer for unique resource allocation
Sometimes, it’s helpful to allocate unique numeric identifiers to resources. For example, when provisioning multiple compute instances or network subnets. The random_integer resource provides a simple way to generate integer values within a defined range.
Picking subnet octets at random can collide with existing networks or fall outside your plan. The integer is stable once generated, so dependent resources remain consistent.
resource "random_integer" "instance_index" {
min = 100
max = 200
}
Keepers and Rotation Control
Use the keepers map to control when a value rotates. The keepers argument allows a random resource to be regenerated when a set of input values change. This gives explicit control over rotation without destroying state.
A typical pattern is to tie rotation to a version label or configuration change.
resource "random_password" "rotating" {
length = 20
keepers = {
rotation = var.password_version
}
}
To rotate on demand, you can apply with -replace=RESOURCE_ADDRESS. This forces Terraform to recreate the resource and generate a new random value.
Security and Practical Use Cases
The provider is suitable for generating names, suffixes, and initial secrets. It is not a secret management system. Values are stored in plaintext in Terraform state, so state file security and access controls are essential.
Practical uses include:
- Unique bucket names and DNS labels
- Random suffixes for resource names in shared accounts
- Initial database passwords
- Pet names for load balancers and instances
- Random IDs for token entropy
- Shuffling a list to select a random valid choice
Limitations and Operational Considerations
The random provider generates values only once. If state is lost, new values will be generated on next apply, which can break references.
Randomness is not cryptographically guaranteed for all use cases. For highly sensitive secrets, combine with a dedicated secrets manager.
Picking subnet octets at random can collide with existing networks or fall outside your plan. Validate ranges and avoid relying on randomness for critical networking decisions without additional checks.
The provider is local only. It does not provide cloud integration, and it does not rotate values automatically.
Conclusion
The Terraform random provider delivers deterministic randomness for infrastructure. It generates random values such as strings, integers, and passwords during deployment and then preserves them in state for consistency across plan and apply cycles. It operates purely locally and does not interact with cloud platforms, producing random data that remains stable unless the resource is explicitly replaced or destroyed.
Resources like randomstring, randominteger, randompassword, randomid, randompet, and randomshuffle each address a distinct need, from unique naming to secure credentials and readable identifiers. Keepers and targeted replacement provide controlled rotation, while state persistence ensures reproducibility. Used with awareness of state security and operational constraints, the provider adds uniqueness without sacrificing the stability required for reliable infrastructure.