如何通过Terraform为Google Compute Instance开放额外端口?
问题描述
我已经通过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仅为GCE实例开放端口22等少数端口。我想无需借助Web控制台,通过更新Terraform代码来开放端口80及其他端口,请问需要添加或编辑哪些Terraform资源?
解决方案
当然可以完全通过Terraform搞定端口开放,不用碰Web控制台。你需要添加防火墙规则资源google_compute_firewall,同时最好给实例打标签,让规则精准作用在目标实例上。
具体操作步骤:
- 添加
google_compute_firewall资源,定义允许的端口、来源IP范围和目标实例标识 - 给你的GCE实例添加标签,和防火墙规则的目标标签匹配(可选但推荐,避免规则影响其他实例)
修改后的完整代码示例:
provider "google" { credentials = "${file("auth.json")}" project = "aqueous-depth-189023" region = "europe-west2" } resource "google_project" "website" { name = "Website" project_id = "aqueous-depth-189023" } // 新增:防火墙规则,开放80(HTTP)、443(HTTPS)等端口 resource "google_compute_firewall" "website_firewall" { name = "website-allow-http-and-more" network = "default" // 和实例使用的网络保持一致 allow { protocol = "tcp" ports = ["80", "443", "8080"] // 按需添加你需要开放的端口,多个用逗号分隔 } // 允许所有IP访问(如果要限制特定IP,改成比如["192.168.1.0/24"]) source_ranges = ["0.0.0.0/0"] // 仅作用于带有该标签的实例 target_tags = ["website-server"] } resource "google_compute_instance" "default" { name = "website" machine_type = "n1-standard-1" zone = "europe-west1-b" // 新增:给实例添加标签,匹配防火墙规则的target_tags tags = ["website-server"] 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_compute_firewall的network必须和实例network_interface.network一致,否则规则不会生效allow块里可以定义多种协议(比如tcp/udp/icmp),每个协议对应一组端口source_ranges控制访问来源,0.0.0.0/0是允许所有外部IP,生产环境建议改成业务需要的特定IP段- 用
target_tags和实例tags关联,能确保规则只作用在你的网站实例上,不会影响项目里其他GCE实例,安全性更高
配置完成后,运行terraform apply,Terraform就会自动创建并应用这个防火墙规则,全程不用手动操作控制台。
内容的提问来源于stack exchange,提问作者James Hiew
相关产品推荐
相关产品推荐

