Search code examples
google-cloud-platformcompiler-errorsterraformgoogle-vpc

Getting an error creating a GCP resource using terraform


I am trying to create a resource by using the terraform.

Here is the code

provider "google" {
  project     = "evident-plane-403213"
  credentials = file("evident-plane-403213-1b4230892244.json")
  region      = "us-central1"
  zone        = "us-central1-c"
}

resource "google_compute_instance" "my-instance" {
  name                      = "terraform-instance"
  machine_type              = "f1-micro"
  zone                      = "us-central1"
  allow_stopping_for_update = true

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

  network_interface {
    network    = google_compute_network.terraform_network.self_link
    subnetwork = google_compute_subnetwork.terraform_subnet.self_link
    access_config {
      // Keeping it empty. It will access over the internet.
    }
  }
}

resource "google_compute_network" "terrform_network" {
  name                    = "terraform-network"
  auto_create_subnetworks = false
}

resource "google_compute_subnetwork" "terraform_subnet" {
  name          = "terraform-subnetwork"
  ip_cidr_range = "10.20.0.0/15"
  region        = "us-central1"
  network       = google_compute_network.terraform_network.id
}

My resource is not getting created and I am getting some error

│ Error: Reference to undeclared resource │ │ on main.tf line 33, in resource "google_compute_subnetwork" "terraform_subnet": │ 33: network = google_compute_network.terraform_network.id │ │ A managed resource "google_compute_network" "terraform_network" has not been
│ declared in the root module.

Where is the error? please help and explain.


Solution

  • In your resource:

    resource "google_compute_network" "terrform_network" {
    

    You have a typo in the resource name. It is named terrform_network. It is missing the a in terraform.

    Later, when you try to reference it, you include the a:

    network       = google_compute_network.terraform_network.id
    

    So the name of the resource doesn't match the name you try to reference later.