Christoph's 2 Cents

A Backup for My Brain!

CloudDevOpsOracle Cloud InfrastructrureTerraform

Terraform: Fun with Random Resources

Yes! You can actually have some fun with Terraform!
I saw this in Kristin Laemmert’s video A Tour of Terraform 0.12 (transcript). She used the random_pet resource to generate random pet names.

The code is very simple and fun to play with. Here is my own version of her example:

variable "pet_count" { default = 5 }
variable "default_prefix" { default = "Whiskers" }
variable "zoo_enabled" { default = false }
variable "prefix_list" { default = ["Whiskers", "Spot", "Fluffy", "Rex", "Pistol", "Pookie"] }

resource "random_pet" "my_pet" {
  count  = var.pet_count
  separator = " "
  length = "3"
  prefix = var.zoo_enabled ? element(var.prefix_list, count.index) : var.default_prefix
}

output "pet_out" {
  value = random_pet.my_pet[*].id
}
The result looks something like this:
Outputs:

pet_out = [
  "Whiskers partially charming horse",
  "Whiskers wholly enough sculpin",
  "Whiskers remotely vast boxer",
  "Whiskers cheaply choice octopus",
  "Whiskers mistakenly immortal griffon",
]
There are a number of options to play with. For example if you set zoo_enabled to true. The prefix_list will be used:
pet_out = [
  "Whiskers partially charming horse",
  "Spot generally certain toad",
  "Fluffy normally discrete sturgeon",
  "Rex yearly grand mallard",
  "Pistol totally legible bird",
]
There are various other random resources provided. They can generate IDs, integers, passwords, strings, and UUIDs.
resource "random_id" "my_id" {
    count = 3
    byte_length = 5
    prefix = "Yowsa_"
}

output "id_out" {
    value = random_id.my_id[*].b64
}
id_out = [
  "Yowsa_sjJKWqI",
  "Yowsa_wW24YDs",
  "Yowsa_Bd_pWlk",
]
Another fun random resource is shuffle. It shuffles a given list of items:
variable "strings" { default = ["a","b","c","d"]}

resource "random_shuffle" "my_shuffle" {
  input = var.strings
  result_count = length(var.strings)
}

output "shuffle_out" {
  value = random_shuffle.my_shuffle.result
}
shuffle_out = [
  "c",
  "a",
  "b",
  "d",
]

Read more about these resources in the official Terraform documentation.