Skip to content

Instantly share code, notes, and snippets.

@x-yuri
Created October 9, 2023 21:57
Show Gist options
  • Save x-yuri/75e50491a1f3823e350022717c2b4237 to your computer and use it in GitHub Desktop.
Save x-yuri/75e50491a1f3823e350022717c2b4237 to your computer and use it in GitHub Desktop.
GCP CE: multiple IPs

GCP CE: multiple IPs

resource "google_compute_instance" "test-many-ips" {
  name = "test-many-ips"
  machine_type = "e2-micro"
  zone = "europe-central2-a"
  boot_disk {
    initialize_params {
      image = "debian-12"
    }
  }
  network_interface {
    network = "default"
    access_config {
      nat_ip = google_compute_address.test-many-ips-1.address
    }
  }
  network_interface {
    subnetwork = google_compute_subnetwork.test-many-ips.name
    access_config {
      nat_ip = google_compute_address.test-many-ips-2.address
    }
  }
  metadata = {
    ssh-keys = "me:${file("id_rsa.pub")}"
    startup-script = <<-EOF
      instance=http://metadata.google.internal/computeMetadata/v1/instance
      get() { curl -sS "$instance/network-interfaces/1/$1" \
                   -H 'Metadata-Flavor: Google'; }
      ip=`get ip`
      gw=`get gateway`
      ip route add default via "$gw" table 1
      ip rule add from "$ip" table 1
    EOF
  }
}

resource "google_compute_address" "test-many-ips-1" {
  name = "test-many-ips-1"
  region = "europe-central2"
}

resource "google_compute_address" "test-many-ips-2" {
  name = "test-many-ips-2"
  region = "europe-central2"
}

resource "google_compute_network" "test-many-ips" {
  name = "test-many-ips"
  auto_create_subnetworks = false
}

resource "google_compute_firewall" "test-many-ips-icmp" {
  name = "allow-icmp-2"
  network = google_compute_network.test-many-ips.name
  source_ranges = ["0.0.0.0/0"]
  allow {
    protocol = "icmp"
  }
}

resource "google_compute_firewall" "test-many-ips-ssh" {
  name = "allow-ssh-2"
  network = google_compute_network.test-many-ips.name
  source_ranges = ["0.0.0.0/0"]
  allow {
    protocol = "tcp"
    ports = [22]
  }
}

resource "google_compute_subnetwork" "test-many-ips" {
  name          = "test-many-ips"
  ip_cidr_range = "10.0.0.0/29"
  region        = "europe-central2"
  network       = google_compute_network.test-many-ips.id
}
$ cp path/to/id_rsa.pub .
$ gcloud auth application-default login
$ terraform init
$ terraform apply

Multiple network interfaces
Create VMs with multiple network interfaces

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment