允许 SSH 访问使用 Terraform 预配的 GCP VM 实例

Allow SSH access to GCP VM instances provisioned with Terraform

我正在尝试使用 Terraform 在 GCP 上创建 VM 实例。确实创建了实例,但我似乎无法通过 SSH 访问这些实例。我的 tf 文件:

# Cloud Provider
provider "google" {
  version = "3.5.0"
  credentials = file("./terraform-service-account.json")
  project = "terraform-279210"
  region  = "us-central1"
  zone    = "us-central1-c"
}
# Virtual Private Network
resource "google_compute_network" "vpc_network" {
  name = "terraform-network"
}
# VM Instance
resource "google_compute_instance" "demo-vm-instance" {
  name         = "demo-vm-instance"
  machine_type = "f1-micro"
  tags         = ["demo-vm-instance"]
  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-9"
    }
  }
  metadata = {
    ssh-keys = "demouser:${file("./demouser.pub")}"
  }
  network_interface {
    network = google_compute_network.vpc_network.name
    access_config {
    }
  }
}


ssh -i demouser demouser@<vm-external-ip> returns

ssh: connect to host <vm-external-ip> port 22: Operation timed out

看起来防火墙规则阻止了通过端口 22 的 TCP 连接,因为 nc -zv <vm-external-ip> 22 没有成功。

使用以下内容创建防火墙规则

resource "google_compute_firewall" "ssh-rule" {
  name = "demo-ssh"
  network = google_compute_network.vpc_network.name
  allow {
    protocol = "tcp"
    ports = ["22"]
  }
  target_tags = ["demo-vm-instance"]
  source_ranges = ["0.0.0.0/0"]
}