Skip to content

Instantly share code, notes, and snippets.

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/9ab3699768f689dcf3d26f6808edb80a to your computer and use it in GitHub Desktop.
Save x-yuri/9ab3699768f689dcf3d26f6808edb80a to your computer and use it in GitHub Desktop.
GCE: make `gcloud compute ssh` use instance metadata

GCE: make gcloud compute ssh use instance metadata

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

$ gcloud compute project-info describe --format 'yaml(commonInstanceMetadata)' \
--project PROJECT_ID
commonInstanceMetadata:
  fingerprint: ...
  kind: compute#metadata
$ gcloud compute instances describe test-ce --format 'yaml(metadata)' \
--zone europe-central2-a --project PROJECT_ID
metadata:
  fingerprint: ...
  items:
  - key: block-project-ssh-keys
    value: 'true'
  kind: compute#metadata

$ gcloud compute ssh me@test-ce --zone europe-central2-a --project PROJECT_ID
Updating instance ssh metadata...⠧Updated [https://www.googleapis.com/compute/v1/projects/PROJECT_ID/zones/europe-central2-a/instances/test-ce].
Updating instance ssh metadata...done.
...

$ gcloud compute project-info describe --format 'yaml(commonInstanceMetadata)' \
--project PROJECT_ID
commonInstanceMetadata:
  fingerprint: ...
  kind: compute#metadata
$ gcloud compute instances describe test-ce --format 'yaml(metadata)' \
--zone europe-central2-a --project PROJECT_ID
metadata:
  fingerprint: ...
  items:
  - key: block-project-ssh-keys
    value: 'true'
  - key: ssh-keys
    value: me:ssh-rsa AAAA...zqjE= root@...
  kind: compute#metadata
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment