How to create Virtual servers in IBM cloud Terraform with for loop?

352 Views Asked by At

I have a Virtual server in IBM cloud created using Terraform

resource "ibm_is_instance" "vsi1" {
  name    = "${local.BASENAME}-vsi1"
  vpc     = ibm_is_vpc.vpc.id
  zone    = local.ZONE
  keys    = [data.ibm_is_ssh_key.ssh_key_id.id]
  image   = data.ibm_is_image.ubuntu.id
  profile = "cc1-2x4"

  primary_network_interface {
    subnet          = ibm_is_subnet.subnet1.id
    security_groups = [ibm_is_security_group.sg1.id]
  }
}

How to create Virtual Servers with Terraform For loops

vsi1 , vsi2, vsi3, vsi4, vsi5

for full code Please refer IBM Cloud Terraform getting started tutorial

1

There are 1 best solutions below

0
On BEST ANSWER

You may not require a for or for-each loop for achieving what you need. A simple count will do the required. Once you add count(number of instances), all you need to do is pass count.index in the VSI name.

resource "ibm_is_instance" "vsi" {
  count   = 4
  name    = "${local.BASENAME}-vsi-${count.index}"
  vpc     = ibm_is_vpc.vpc.id
  zone    = local.ZONE
  keys    = [data.ibm_is_ssh_key.ssh_key_id.id]
  image   = data.ibm_is_image.ubuntu.id
  profile = "cc1-2x4"

  primary_network_interface {
    subnet          = ibm_is_subnet.subnet1.id
    security_groups = [ibm_is_security_group.sg1.id]
  }
}

This will create instances with names vsi-0,vsi-1...