允许SSH访问通过Terraform设置的GCP VM实例

时间:2020-06-06 11:59:21

标签: google-cloud-platform terraform terraform-provider-gcp

我正在尝试使用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>返回

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

似乎防火墙规则阻止了nc -zv <vm-external-ip> 22失败,从而阻止了通过端口22的TCP连接。

1 个答案:

答案 0 :(得分:3)

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

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"]
}