首页 > 解决方案 > 如何使用 Terraform 在我的 Google 计算实例上公开额外的端口?

问题描述

我有一个由一些 Terraform 代码定义的 Google Compute Instance。

provider "google" {
  credentials = "${file("auth.json")}"
  project     = "aqueous-depth-189023"
  region      = "europe-west2"
}

resource "google_project" "website" {
  name = "Website"
  project_id = "aqueous-depth-189023"
}

resource "google_compute_instance" "default" {
  name         = "website"
  machine_type = "n1-standard-1"
  zone         = "europe-west1-b"

  network_interface {
    network = "default"

    access_config {
      // Ephemeral IP
    }
  }

  metadata {
    sshKeys = "james:${file("website.pem.pub")}"
  }

  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-8"
    }
  }
}

默认情况下,Google 只为 Google Compute Instances 公开端口 22 和其他一些端口。我可以更新我的 Terraform 代码以实现暴露端口 80 和其他一些端口,而无需使用 Web 控制台吗?我需要添加或编辑什么 Terraform 资源?

标签: google-compute-engineterraform

解决方案


使用google_compute_firewall. 您需要为tag您的实例提供实例资源并target_tags在防火墙资源上进行设置。您可以在此处参考这些标签的工作原理。

例子

为实例添加标签

resource "google_compute_instance" "default" {
  name         = "website"
  machine_type = "n1-standard-1"
  zone         = "europe-west1-b"

  tags = ["web"]

  network_interface {
    network = "default"

    access_config {
      // Ephemeral IP
    }
  }

  metadata {
    sshKeys = "james:${file("website.pem.pub")}"
  }

  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-8"
    }
  }
}

添加防火墙资源

resource "google_compute_firewall" "default" {
 name    = "web-firewall"
 network = "default"

 allow {
   protocol = "icmp"
 }

 allow {
   protocol = "tcp"
   ports    = ["80"]
 }

 source_ranges = ["0.0.0.0/0"]
 target_tags = ["web"]
}

您还需要定义source_tagsor source_ranges,上面的示例使用的源范围0.0.0.0/0是“任何东西”。这可能不适用于所有规则。


推荐阅读