Terraform的random_shuffle不会按预期进行洗牌

时间:2018-12-13 11:42:12

标签: terraform

我有此配置:

variable "sub_list" {
  type = "map"
  default = {
    "data.dev"= ["data1", "data2", "data3", "data4"]
    "data.dev2"= ["data1", "data2", "data3", "data4"]
 }
}

resource "random_shuffle" "az" {
   input =               "${var.sub_list[local.data]}"
   result_count =        "${length(var.VM_count)}"
   }

data "vsphere_sub" "sub" {
  count         =       "${length(var.VM_count)}"
  name          =       "${random_shuffle.az.result[count.index]}"
}

resource "vsphere_virtual_machine" "VM" {
  name      = "${var.VM_name}
  folder    = "${var.folder}"
  count     = "${length(var.VM_count)}"
  sub_id    = "${element(data.vsphere_sub.sub.*.id, (count.index)%length(data.vsphere_sub.sub.id))}"
  num_cpus  = "${var.VM_vcpu}"
  memory    = "${var.VM_memory}"
}

例如,当我以VM_count = 2启动时,我希望每个VM都有一个子网,但是它将在同一子网中创建2个VM,并且仅随机播放一次,而不是2个。我们如何随机选择一个项目从基于要创建的VM数量的映射中?

谢谢您的帮助

1 个答案:

答案 0 :(得分:0)

几个问题。您无法获得数字的长度,因此

count = length(var.VM_count)

应该是

count = var.VM_count

不确定这行的意图是什么

sub_id = element(data.vsphere_sub.sub.*.id, (count.index)%length(data.vsphere_sub.sub.id))

如果我们想要一个不同的子网应该是这样

sub_id = element(data.vsphere_sub.sub.*.id, count.index)

所以最终结果将是

resource "random_shuffle" "az" {
  input        = "${var.sub_list[local.data]}"
  result_count = "${var.VM_count}"
}

data "vsphere_sub" "sub" {
  count = "${var.VM_count}"
  name  = "${random_shuffle.az.result[count.index]}"
}

resource "vsphere_virtual_machine" "VM" {
  name     = "${var.VM_name}
  folder   = "${var.folder}"
  count    = "${var.VM_count}"
  sub_id   = "${element(data.vsphere_sub.sub.*.id, count.index)}"
  num_cpus = "${var.VM_vcpu}"
  memory   = "${var.VM_memory}"
}

现在,当您使用VM_count=2进行申请时,它应该从sub_list获取2个随机子网,并创建2个VM,每个VM具有不同的子网。