0

How to provision multiple instances in GCP Compute Engine using Terraform. I've tried using 'count' parameter in the resource block. But terraform is not provisioning more than one instance because the VM with a particular name is created once when first count is executed.

provider "google" {
version = "3.5.0"
credentials = file("battleground01-5c86f5873d44.json")
project = "battleground01"
region  = "us-east1"
zone    = "us-east1-b"
}

variable "node_count" {
default = "3"
}


resource "google_compute_instance" "appserver" {
count = "${var.node_count}"
name = "battleground"
machine_type = "f1-micro"


boot_disk {
initialize_params {
image = "debian-cloud/debian-9"
}
}

network_interface {
network = "default"
}

}
2
  • Please add some terraform code to the question or your question will probably be closed. Commented Jul 13, 2022 at 8:18
  • You aren't using your count variable in the machine name, please reread the terraform documentation on terraform.io/language/meta-arguments/count#basic-syntax the aws example is extremely similar to what you are doing. Commented Jul 13, 2022 at 10:03

1 Answer 1

1

In order for this to work, you would have to make a slight change in the way you are naming your compute instances:

provider "google" {
  version     = "3.5.0"
  credentials = file("battleground01-5c86f5873d44.json")
  project     = "battleground01"
  region      = "us-east1"
  zone        = "us-east1-b"
}

variable "node_count" {
  type    = number
  default = 3
}


resource "google_compute_instance" "appserver" {
  count        = var.node_count
  name         = "battleground-${count.index}"
  machine_type = "f1-micro"


  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-9"
    }
  }

  network_interface {
    network = "default"
  }

}

As you are using the count meta-argument, the way to access the array index is by using the count.index attribute [1]. You have also set the node_count variable default value to be a string and even though it would probably get converted to a number by Terraform, make sure to use the right variable types.


[1] https://www.terraform.io/language/meta-arguments/count#the-count-object

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.