Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To create two GCP instances with static IPs using Terraform, follow these steps:

  1. Install and configure Terraform on your local machine.

  2. Create a new Terraform file, name it something like gcp-instances.tf, and include the following code:

provider "google" {
  credentials = file("account.json")
  project     = "<YOUR_GCP_PROJECT>"
  region      = "<YOUR_GCP_REGION>"
}

resource "google_compute_address" "instance1_ip" {
  name = "instance1-static-ip"
}

resource "google_compute_instance" "instance1" {
  name_prefix  = "instance1-"
  machine_type = "n1-standard-1"
  zone         = "<YOUR_GCP_ZONE>"
  boot_disk {
    initialize_params {
      image = "<YOUR_GCP_IMAGE>"
    }
  }

  network_interface {
    network = "default"
    access_config {
      nat_ip = google_compute_address.instance1_ip.address
    }
  }
}

resource "google_compute_address" "instance2_ip" {
  name = "instance2-static-ip"
}

resource "google_compute_instance" "instance2" {
  name_prefix  = "instance2-"
  machine_type = "n1-standard-1"
  zone         = "<YOUR_GCP_ZONE>"
  boot_disk {
    initialize_params {
      image = "<YOUR_GCP_IMAGE>"
    }
  }

  network_interface {
    network = "default"
    access_config {
      nat_ip = google_compute_address.instance2_ip.address
    }
  }
}
  1. Fill in the necessary values in the code, such as your GCP project, region, zone, and image.

  2. Run terraform init and terraform apply to create the instances and static IPs.

  3. Once the Terraform process is complete, you can verify that the instances were created and have static IPs assigned by navigating to the Google Cloud Console and looking for the instances under the Compute Engine section.