代码之家  ›  专栏  ›  技术社区  ›  James Hiew

如何使用TerraForm在我的Google计算实例上公开额外的端口?

  •  2
  • James Hiew  · 技术社区  · 7 年前

    我有一个由一些地形代码定义的谷歌计算实例。

    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计算实例公开端口22和其他一些端口。我可以更新我的TerraForm代码以实现公开端口80和其他一些端口,而不必使用Web控制台吗?我需要添加或编辑什么地形资源?

    1 回复  |  直到 7 年前
        1
  •  6
  •   Brandon Miller    7 年前

    使用 google_compute_firewall . 你需要 tag 具有实例资源和集合的实例 target_tags 在防火墙资源上。您可以参考这些标签的工作原理。 here

    例子

    向实例添加标记

    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_tags source_ranges ,上面的示例使用的源范围为 0.0.0.0/0 什么都可以。这可能不适用于所有规则。