Terraform GCP add VM to existing VPC

google-cloud-platformterraform

I'm starting to learn Terraform (I want to manage my growing GCP infrastructure). I'm trying to do an apparently simple thing — create a VM in the different Project — but:

  • I already have a VPC configured, let's called it pre-terra-vpc in Project proj1
  • this VPC is already in use, so I would like not to destroy it in process

I have a different Project setup, proj2 for learning purposes and I would like to create a simple GCP VM in proj2, but connected to the VPC from proj1, pre-terra-vpc.

Is this possible without Terraform destroying and recreating the pre-terra-vpc? Is this safe? When run terraform plan I have 2 things to add…

provider "google" {
  ...
  project = "proj2"
}

resource "google_compute_network" "pre-terra-vpc" {                        
  name          = "pre-terra-vpc"                                          
  project       = "proj1"                                       
}

resource "google_compute_instance" "default" {
  ...
  ...
  network_interface {                                                        
  network     = "${google_compute_network.pre-terra-vpc.self_link}"      
  network_ip  = ""                                                         

  access_config {                                                          
    // Ephemeral IP Address                                                
  }                                                                        
}

Best Regards

Kamil

Best Answer

You can also use a data source lookup to find things created outside your current run and they act just like terraform created them

data "google_compute_network" "pre-terra-vpc" {
  name          = "pre-terra-vpc"                                          
  project       = "proj1"
}

Then you can use it like. (notice the data in front and not the resource name)

${data.google_compute_network.pre-terra-vpc.self_link}

See the following

https://www.terraform.io/docs/providers/google/d/datasource_compute_network.html

Related Topic