如何使用Terraform在我的Google Compute Instance上公开额外的端口?

时间:2018-05-28 20:38:50

标签: google-compute-engine terraform

我有一些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资源?

1 个答案:

答案 0 :(得分:6)

使用google_compute_firewall。您需要使用实例资源tag实例,并在防火墙资源上设置target_tags。您可以参考这些代码的工作方式here

实施例

将标签添加到实例

import numpy as np
a = np.array([[1,2,3],[4,5,6]])
a
>> array([[1, 2, 3],
       [4, 5, 6]])
a.shape
>> (2, 3)

添加防火墙资源

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

您还要定义source_tagssource_ranges,上面的示例使用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"] } 的来源范围,这是“任何事情”。这可能不适合所有规则。