Sling Academy
Home/DevOps/How to generate random values in Terraform

How to generate random values in Terraform

Last updated: February 03, 2024

Introduction

Generating random values in Terraform can be a critical aspect when provisioning infrastructure, ensuring that names, passwords, or any other sensitive information remain unpredictable and secure. Terraform, developed by HashiCorp, uses a powerful and flexible syntax known as HashiCorp Configuration Language (HCL), allowing you to define your infrastructure as code (IaC). In this tutorial, we will delve into the various methods of generating random values within your Terraform configurations, ranging from basic examples to more complex scenarios.

Understanding Randomness in Terraform

Before diving into the code examples, it’s crucial to understand how randomness works in Terraform. Terraform uses a provider model to interact with APIs, services, and custom code. The random provider is what we’ll focus on for generating random values. To use it, you must first declare it in your configuration.

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

After declaring the provider, you can then use various resources within the random provider to generate values. Let’s start with the basics.

Generating a Random Integer

The simplest way to generate a random value is by creating a random integer. This can be useful for generating unique identifiers, passwords, or selecting a random resource.

resource "random_integer" "example" {
  min = 1
  max = 100
}

You can then reference this value using ${random_integer.example.result} in your Terraform configurations.

Generating a Random Password

Generating a secure, random password is another common use case. The random_password resource enables you to specify the length and complexity of your password.

resource "random_password" "password" {
  length  = 16
  special = true
}

Reference it in your configurations as ${random_password.password.result}.

Generating a Random String

Similarly, you can generate random strings for use in names, tags, or other identifiers.

resource "random_string" "name" {
  length  = 10
  upper = true
  lower = true
  number = true
  special = false
}

Use the generated string with ${random_string.name.result}.

Advanced Scenarios

Moving to more advanced uses of randomness, consider a scenario where you need multiple, unique, random values. Terraform’s random provider offers the random_id resource, which generates a unique identifier based on a specified number of bytes.

resource "random_id" "server" {
  byte_length = 8
}

This unique ID can be valuable for creating unduplicated identifiers for resources across your cloud infrastructure. Output is accessed through ${random_id.server.hex} or ${random_id.server.b64}, depending on the required format.

Conditional Random Values

You might not always want to generate a new random value on each plan or apply. To conditionally generate random values, you can combine the random resources with Terraform’s conditional logic.

resource "random_string" "conditional_name" {
  count  = var.condition ? 1 : 0
  length  = 10
  upper = true
  special = false
}

This approach ensures that the random value is only generated when a certain condition, defined by var.condition, is true.

Securing Random Values

When generating sensitive information, like passwords or encryption keys, it’s crucial to ensure these values are treated securely. Use the sensitive = true attribute in outputs to prevent Terraform from printing the value to the console.

output "sensitive_password" {
  value     = random_password.password.result
  sensitive = true
}

Conclusion

Generating random values in Terraform enables dynamic and secure infrastructure configurations. From creating basic integers and strings to managing complex, conditional logic for random generation, understanding how to leverage the random provider expands the flexibility and security of your configurations. Embrace randomness in your Terraform projects to ensure uniqueness and security across your infrastructure.

Next Article: Terraform: How to generate passwords

Previous Article: How to write conditional logic in Terraform

Series: Terraform Tutorials

DevOps

You May Also Like

  • How to reset Ubuntu to factory settings (4 approaches)
  • Making GET requests with cURL: A practical guide (with examples)
  • Git: What is .DS_Store and should you ignore it?
  • NGINX underscores_in_headers: Explained with examples
  • How to use Jenkins CI with private GitHub repositories
  • Terraform: Understanding State and State Files (with Examples)
  • SHA1, SHA256, and SHA512 in Terraform: A Practical Guide
  • CSRF Protection in Jenkins: An In-depth Guide (with examples)
  • Terraform: How to Merge 2 Maps
  • Terraform: How to extract filename/extension from a path
  • JSON encoding/decoding in Terraform: Explained with examples
  • Sorting Lists in Terraform: A Practical Guide
  • Terraform: How to trigger a Lambda function on resource creation
  • How to use Terraform templates
  • Understanding terraform_remote_state data source: Explained with examples
  • Jenkins Authorization: A Practical Guide (with examples)
  • Solving Jenkins Pipeline NotSerializableException: groovy.json.internal.LazyMap
  • Understanding Artifacts in Jenkins: A Practical Guide (with examples)
  • Using Jenkins with AWS EC2 and S3: A Practical Guide