Skip to content

Instantly share code, notes, and snippets.

@x-yuri
Last active April 1, 2024 13:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save x-yuri/da2b63a8456fe63790761510cdd8170d to your computer and use it in GitHub Desktop.
Save x-yuri/da2b63a8456fe63790761510cdd8170d to your computer and use it in GitHub Desktop.
terraform creates VMs without an account

terraform creates VMs without an account

main.tf:

provider "google" {
  project = "PROJECT_ID"
}

resource "google_compute_instance" "test-ce" {
  name = "test-ce"
  machine_type = "e2-micro"
  zone = "europe-central2-a"
  boot_disk {
    initialize_params {
      image = "debian-12"
    }
  }
  network_interface {
    subnetwork = google_compute_subnetwork.test-ce.self_link
    access_config {
    }
  }
  metadata = {
    block-project-ssh-keys = true
  }
}

resource "google_compute_network" "test-ce" {
  name = "test-ce"
  auto_create_subnetworks = false
}

resource "google_compute_subnetwork" "test-ce" {
  name = "test-ce"
  ip_cidr_range = "10.0.0.0/20"
  region = "europe-central2"
  network = google_compute_network.test-ce.self_link
}

resource "google_compute_firewall" "test-ce-ssh" {
  name = "test-ce-ssh"
  network = google_compute_network.test-ce.self_link
  source_ranges = ["SOURCE_IP"]
  allow {
    protocol = "tcp"
    ports = [22]
  }
}
// replace PROJECT_ID, SOURCE_IP
$ docker run --rm -itv "$PWD:/app" -w /app google/cloud-sdk:457.0.0-alpine
/app # gcloud auth login --update-adc
/app # apk add terraform
/app # terraform init
/app # terraform apply
/app # terraform apply
/app # gcloud compute instances create test-ce2 \
  --machine-type e2-micro --subnet test-ce \
  --image-project debian-cloud --image-family debian-12 \
  --zone europe-central2-a --project PROJECT_ID

/ app # gcloud compute ssh me@test-ce \
  --command '
    curl -sS -H "Metadata-Flavor: Google"
      http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/' \
  --zone europe-central2-a --project PROJECT_ID

/ app # gcloud compute ssh me@test-ce2
  --command '
      curl -sS -H "Metadata-Flavor: Google"
        http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/email' \
  --zone europe-central2-a --project PROJECT_ID
196948812904-compute@developer.gserviceaccount.com

/ app # gcloud compute instances delete test-ce2 \
  --zone europe-central2-a --project PROJECT_ID
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment