google-compute-engine - 如何使用 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_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_tags
or source_ranges
,上面的示例使用的源范围0.0.0.0/0
是“任何东西”。这可能不适用于所有规则。
推荐阅读
- json - 如何使用 jq 或任何工具合并目录中的多个 json 文件?
- plot - geopandas plotting - 识别地图之外的位置
- python - 在为 pip 安装安装不同的缓存后,Docker 实验构建仍然使用系统缓存
- angular - Angular 使用路径变量从 API 获取数据
- python - 为什么 mne resample 方法不会对数据进行点对点采样?
- python - 为 macOS 下的 ctypes.util.find_library() 指定路径
- typescript - Ionic 4:Ionic Lab 黑屏错误的解决方法
- python - Kivy 未正确显示(孟加拉语)Unicode 字符
- javascript - 无法解析 json 数据 jquery
- ios - 是否可以在 iOS 中实现对操作系统权限提示的分析?