terraformvsphere

Terraform retrieve list value using count


I am trying to retrieve the list values using count

variables.tf
-------------
variable vmi {
  type = list(string)
  default =[]
}

variable server_num {
  default = "1"
}

cluster.tf
----------
module "provision" {
 source = "git:://https://example.com/repo.git"
 server_num = "3"
 vmi = ["abc", "cde", "def"]
}

main.tf
-------
resource vpshere_virtual_machine vm {
  count = var.server_num
  name = var.vmi[count.index]
}

But it is printing abc every time. Can someone point me the mistake that I am making


Solution

  • In the Terraform setup you shared, the main issue that stands out to me is that you're attempting to assign values to a non-existent vmi attribute in the vsphere_virtual_machine resource as specified here. Instead, you should use each element from the vmi list to set a valid property of the virtual machine, likely the name if that's what you intend.

    If you haven’t, you also need to define a variable server_num which specifies how many VMs you want to create.

    So I’ll modify your configuration to look like this:

    variable "vmi" {
      type = list(string)
      default = ["abc", "cde", "def"]
    }
    
    variable "server_num" {
      type = number
      default = 3
    }
    
    resource "vsphere_virtual_machine" "vm" {
      count = var.server_num
      name = var.vmi[count.index]  // Assign each VM a name from the 'vmi' list
    }
    

    This way, each virtual machine instance gets a unique name from your vmi list, based on its position. Lastly, make sure that server_num does not exceed the number of elements in your vmi list to prevent indexing errors.