I’ve been working with Terraform recently for deploying the required architecture for a data pipeline in Google Cloud Platform (GCP). It’s my first project with Terraform and I decided to dive into its random_something resources, because I couldn’t have duplicate resource names. Here are some findings.
Randomize a resource name with Terraform random_string
Randomizing a resource’s name or ID is super easy with Terraform. You can use the random_string resource, and use it as a suffix or a prefix. In the following example, I’ve created a random string of three digits, and used it as the suffic of a GCP Cloud SQL database.
resource "random_string" "random_suffix" { length = 3 special = false upper = false } resource "google_sql_database_instance" "my_database" { name = "my-database-${random_string.random_suffix.result}" database_version = "POSTGRES_13" ...
However, this could lead to issues along the way. Whenever you’re rerunning the apply command, a new suffix will be generated, and your new resource name won’t match the one from the previous state. Consequently, Terraform will try to apply the new name to the resource — which isn’t even always possible.
That’s why you should set the keeper argument in your Terraform schema. The keeper argument behaves like a random seed. You could set it to a specific value, so that it only changes once that specific value changes. Another approach is to link the existence of your random_string to the ID of another resource. When the other resource is created again, so will the random_string. Even more interesting: you can use multiple values in the keeper argument!
In this example, I set the IP address of a GCP compute instance as the random seed.
resource "random_string" "random_suffix" { length = 3 special = false upper = false keepers = { instance_ip = "${google_compute_address.my_instance.address}" } } resource "google_sql_database_instance" "my_database" { name = "my-database-${random_string.random_suffix.result}" database_version = "POSTGRES_13" ...
The resulting name of my_database? my-database-ht5. Exciting, right? 🤷♀️
Randomize a resource name with Terraform random_pet
Terraform has quite a lot of random providers to create random strings. The random_id resource has quite a lot in common with random_string, but is focussed on minimizing collision (receiving the same ID twice or more).
Without doubt, the most interesting random provider is random_pet, which can be used to generate a random pet, with some adjectives — how many depends on the length argument.
resource "random_pet" "pet" { keepers = { some_id = "100" } length = 10 }
For demonstration purpose only, I set the length argument to 10, which gave me the following random pet name: “tightly-generally-moderately-mostly-usually-arguably-ultimately-badly-willing-lizard”. Extremely useful!