Bootstrap FreeKB - Terraform - Random Shuffle a list
Terraform - Random Shuffle a list

Updated:   |  Terraform articles

random_shuffle can be used to shuffle a list. Let's say you have the following files on your Terraform server.

├── main.tf (root module)
├── data.tf
├── locals.tf
├── outputs.tf
├── providers.tf
├── terraform.tfstate
├── variables.tf
├── child (directory)
│   ├── main.tf (child module)
│   ├── data.tf
│   ├── outputs.tf
│   ├── resources.tf

 

Let's say variables.tf has the following list.

variable "environments" {
  type = list(string)
  sensitive = false
  default = ["dev", "stage", "prod"]
}

 

And perhaps outputs.tf in the same directory as your main root module (main.tf) outputs the list.

output "my-environments" {
  value = var.environments
}

 

The terraform output command should return the following. Notice the list is in the same order as defined in the variable.

my-environments = tolist([
  "dev",
  "stage",
  "prod",
])

 

random_shuffle can be used to shuffle the list.

resource "random_shuffle" "random_environment" {
  input = [
    var.environments[0],
    var.environments[1],
    var.environments[2]
  ]
}

 

Now the list should be shuffled, which you can see using output.

output "random-environments" {
  value = random_shuffle.random_environment
}

 

Which should return the following.

random-environments = {
  "id" = "-"
  "input" = tolist([
    "dev",
    "stage",
    "prod",
  ])
  "keepers" = tomap(null) /* of string */
  "result" = tolist([
    "stage",
    "dev",
    "prod",
  ])
  "result_count" = tonumber(null)
  "seed" = tostring(null)
}

 

You probably just want the result list.

output "random-environments-result" {
  value = random_shuffle.random_environment.result
}

 

Which should return the following.

random-environments-result = tolist([
  "stage",
  "dev",
  "prod",
])

 

And then output one of the values from the shuffled list.

output "random-environment" {
  value = random_shuffle.random_environment.result[0]
}

 

Or like this.

output "random-environment" {
  value = element(random_shuffle.random_environment.result, 0)
}

 

Which should return the following.

random-environment = "stage"

 

Or like this.

output "random-environment-0" {
  value = random_shuffle.random_environment.result[0]
}

output "random-environment-1" {
  value = random_shuffle.random_environment.result[1]
}

output "random-environment-2" {
  value = random_shuffle.random_environment.result[2]
}

 

Which should return output like this.

random-environment-0 = "stage"
random-environment-1 = "dev"
random-environment-2 = "prod"

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 59cb63 in the box below so that we can be sure you are a human.