Infra chaos crushing your controls?

Meet Spacelift at AWS re:Invent

How to Use Terraform Random Provider [Examples]

terraform

🚀 Level Up Your Infrastructure Skills

You focus on building. We’ll keep you updated. Get curated infrastructure insights that help you make smarter decisions.

Terraform’s random provider gives you stable random values that are written to state and reused on every apply. Use it when you need uniqueness without hand-crafting names or secrets. Rotate values only when you explicitly replace the resource.

What is the Terraform random provider?

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’s commonly used to add randomness or uniqueness to your infrastructure while still keeping that randomness deterministic within the context of Terraform’s state.

This means that 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.

The basic example of a provider declaration can look like this:

terraform {
  required_providers {
    random = {
      source  = "hashicorp/random"
      version = "**~> 3.6**"
    }
  }
}

Once the provider is declared, you can use resources like:

  • random_string – generates random alphanumeric strings for resource naming.
  • random_integer – picks a random integer within a specified range.
  • random_password – creates secure, complex passwords for databases or systems.
  • random_id – opaque IDs as hex or base64 for tokens or entropy.
  • random_pet – creates readable “pet names” like bright-otter.
  • random_shuffle – returns a random reordering so you can pick one or more valid choices from a known list.

Each serves a specific purpose, from generating secure credentials to creating fun but unique names.

Example 1: Generating a random string for resource 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.

provider "random" {}

resource "random_string" "bucket_suffix" {
  length  = 6
  upper   = false
  special = false
}

resource "aws_s3_bucket" "unique_bucket" {
  bucket = "app-data-${random_string.bucket_suffix.result}"
}

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.

Read more: Terraform Strings: Interpolation, Multiline & Built-in Functions

Example 2: Creating a random password for a database

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.

provider "random" {}

resource "random_password" "db_password" {
  length           = 16
  special          = true
  override_special = "!@#$%&*"
  keepers = { engine_version = "16" }
}

resource "aws_db_instance" "app_db" {
  identifier        = "app-database"
  engine            = "postgres"
  instance_class    = "db.t3.micro"
  username          = "admin"
  password          = random_password.db_password.result
  allocated_storage = 20
}

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. A safer pattern is to pick from a prevalidated list and use random_integer to select one entry by index.

locals {
  candidate_subnets = [
    "10.0.10.0/24",
    "10.0.11.0/24",
    "10.0.12.0/24",
  ]
}

resource "random_integer" "subnet_index" {
  min = 0
  max = length(local.candidate_subnets) - 1
}

resource "aws_subnet" "random_subnet" {
  vpc_id            = "vpc-123456"
  cidr_block        = local.candidate_subnets[random_integer.subnet_index.result]
  availability_zone = "us-east-1a"
}

If you want deterministic subnet math, prefer cidrsubnet() with inputs that you control rather than randomness.

Example 4: Generating human-readable resource names with random_pet

The random_pet resource is part of the Terraform random provider and is designed to create easy-to-read, friendly, and semi-random identifiers. Instead of generating hard-to-remember strings like a9f2kj, it produces names such as curious-otter or gentle-bear. 

These names are memorable, concise, and perfect for tagging, labeling, or naming ephemeral infrastructure resources — especially in development, testing, or CI/CD pipelines.

In this example, we’ll use random_pet to generate a human-readable name for a Kubernetes namespace. Each deployment will create a unique but readable namespace identifier, making it easier for developers to identify test environments visually.

provider "random" {}

resource "random_pet" "namespace_name" {
  length    = 2
  separator = "-"
}

resource "kubernetes_namespace" "test_environment" {
  metadata {
    name = "test-${random_pet.namespace_name.id}"
  }
}

Here’s what’s happening in this configuration: the random_pet resource generates two words separated by a hyphen (for example, test-bright-lynx). The length parameter controls how many words are included, and the separator defines what character joins them.

This approach is particularly useful when automating temporary or disposable environments, where having a readable and unique name simplifies debugging and cleanup. 

For example, when running multiple parallel integration tests in Kubernetes, each run might create a unique namespace like test-calm-lion or test-sunny-otter, preventing naming collisions without sacrificing clarity.

In addition to readability, random_pet offers stability. 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.

Key points

Terraform’s Random provider doesn’t 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.

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.

Terraform is really powerful, but to achieve an end-to-end secure GitOps approach, you need to use a product that can run your Terraform workflows. Spacelift takes managing Terraform to the next level by giving you access to a powerful CI/CD workflow and unlocking features such as:

  • Policies (based on Open Policy Agent)
  • Multi-IaC workflows
  • Self-service infrastructure
  • Integrations with any third-party tools

If you want to learn more about Spacelift, create a free account today or book a demo with one of our engineers.

Note: New versions of Terraform are placed under the BUSL license, but everything created before version 1.5.x stays open-source. OpenTofu is an open-source version of Terraform that expands on Terraform’s existing concepts and offerings. It is a viable alternative to HashiCorp’s Terraform, being forked from Terraform version 1.5.6.

Manage Terraform better with Spacelift

Build more complex workflows based on Terraform using policy as code, programmatic configuration, context sharing, drift detection, resource visualization and many more.

Learn more

Terraform Commands Cheat Sheet

Grab our ultimate cheat sheet PDF
for all the Terraform commands
and concepts you need.

Share your data and download the cheat sheet