sequential
您提到,方式确实很重要...... 我认为,按顺序排列,比较简单,使用范围,使用数字trick滴(<条码>(i % 3)+1条码>,以便在你想要的[1-3]之间获得价值。
variable "objects" {
default = 12
}
locals {
distrib = [ for i in range(var.objects) : (i % 3) + 1 ]
}
output "test" {
value = local.distrib
}
a terraform plan on that:
Changes to Outputs:
+ test = [
+ 1,
+ 2,
+ 3,
+ 1,
+ 2,
+ 3,
+ 1,
+ 2,
+ 3,
+ 1,
+ 2,
+ 3,
]
sequential with random start
在<代码>random_integer资源的帮助下,我们可以任意开端,并在范围功能中使用开端和限参数。
variable "objects" {
default = 12
}
resource "random_integer" "extra" {
min = 0
max = 2
}
locals {
start = random_integer.extra.result
distrib = [for i in range(local.start, var.objects + local.start) : (i % 3) + 1]
}
output "test" {
value = local.distrib
}
random
Randomization is also possible using the random_shuffle
resource:
https://registry.terraform.io/providers/hashicorp/random/latest/docs/resources/shuffle
variable "objects" {
default = 12
}
locals {
distrib = [ for i in range(var.objects) : (i % 3) + 1 ]
}
resource "random_shuffle" "random" {
input = local.distrib
result_count = var.objects
}
output "test" {
value = random_shuffle.random.result
}
a) 适用于:
Apply complete! Resources: 1 added, 0 changed, 1 destroyed.
Outputs:
test = tolist([
"3",
"1",
"3",
"2",
"2",
"3",
"1",
"1",
"2",
"2",
"1",
"3",
])
more complex
我们还可以使用其他价值而不是<代码>。 [1-3],见以下图形:
variable "objects" {
default = 9
}
variable "items" {
default = ["red", "blue", "cyan"]
}
locals {
distrib = [for i in range(var.objects) : element(var.items, (i % length(var.items)))]
}
resource "random_shuffle" "random" {
input = local.distrib
result_count = var.objects
}
output "test" {
value = random_shuffle.random.result
}