BenVek
BenVek

Reputation: 45

Terraform and GCP - Create new Compute VM in existing Shared VPC and Subnet

How do I create a new Compute Instance and associate it with an existing shared VPC/Subnet? The shared VPC/Subnet already exists in another Project.

My TF block:

resource "google_compute_instance" "computevm1" {
  name                      = "test-compute-vm1"
  zone                      = "us-west1-a"
  machine_type              = "e2-standard-1"

  network_interface {
    network = "isolated-vpc"
  }
  boot_disk {
    initialize_params {
      image = "ubuntu-2004-focal-v20211212"
      size  = 20
    }
  }
}

Error I'm getting:

The referenced network resource cannot be found., invalid

Upvotes: 1

Views: 2702

Answers (2)

Senan T
Senan T

Reputation: 33

you can use data to import the nework and subnet in your tf file like

data "google_compute_network" "main-default-vpc" {
  name    = "default"
  project = "project-id"
}

data "google_compute_subnetwork" "subnet-for-vms" {
  name    = "name_of_subnet"
  project = "project-id"
  region  = "us-central1"

network_interface {
  subnetwork = data.google_compute_subnetwork.subnet-for-vms
  }

For more information; take a look at https://cloud.google.com/docs/terraform/get-started-with-terraform

@BenVek; let me know if it works or not. I have faced similar issues and that is how I solved it. Thanks!

Upvotes: 0

John Hanley
John Hanley

Reputation: 81336

For HCL attribute network specify the network name of the VPC in the project that the instance is being created in. The subnet will be selected from the region automatically. There is nothing special about Shared VPC when creating an instance.

Assuming your Shared VPC is enabled on the default network:

network_interface {
  network = "default"
}

Change the name if different.

Upvotes: 1

Related Questions