TF: Generating Random Strings

less than 1 minute read

Description:

Follow these steps to use random string whatever reason. I usually use these for creating resources which won’t gaurantee uniqueness, but most likely will. It will fail on apply if the resource just happens to exist but I’ve never seen it yet.

To Resolve:

  1. First, make sure to include random in your providers:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
    terraform {
       required_providers {
          random = {
             source  = "hashicorp/random"
             version = "~>3.3.2"
          }
       }
       required_version = "~>1.1.0"
    }
    
    provider "random" {
    }
    
  2. Next, just create a random resource. Optionally, if using Azure, I like to add resource_group to the keepers ( which points to here ) which ensures the random resource will never regenerate unless that is changed:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    
    resource "random_string" "naming_convention" {
    keepers = {
       resource_group = var.resource_group_name
    }
    length  = 5
    upper   = false
    lower   = true
    number  = true
    special = false
    }
    
    resource "null_resource" "naming_standard_key_vault_example" {
       name  = "some-resource-${random_string.naming_convention.result}"
    }
    
  3. To create multiple random strings using count, see my other post here for an example.

Comments