如何在 Google Compute VM 上使用 terraform 进行 ip 转发

问题描述

我正在尝试学习wireguard。我发现了这个关于如何在 GCP 上安装它的很棒的教程...... https://sreejithag.medium.com/set-up-wireguard-vpn-with-google-cloud-57bb3267a6ef

非常基本(对于不熟悉wireguard的人),但确实有效。本教程展示了使用 ip 转发配置的虚拟机。通过 GCP 网络界面

我想用 terraform 设置它。我搜索terraform 注册表并找到了这个...

https://registry.terraform.io/providers/hashicorp/google/latest/docs/data-sources/compute_forwarding_rule

这是我的带有虚拟机配置的 main.tf。我会把诸如 ip forwarding 之类的东西放在哪里?没有地形抱怨?

代码---

# This is the provider used to spin up the gcloud instance
provider "google" {
  project = var.project_name
  region  = var.region_name
  zone    = var.zone_name
  credentials = "mycredentials.json"
}

# Locks the version of terraform for this particular use case
terraform {
  required_version = "0.14.6"
}

# This creates the google instance
resource "google_compute_instance" "vm_instance" {
  name         = "development-vm"
  machine_type = var.machine_size
  
    
    tags = ["allow-http","allow-https","allow-dns","allow-tor","allow-ssh","allow-2277","allow-mosh","allow-whois","allow-openvpn","allow-wireguard"]  # FIREWALL

  boot_disk {
    initialize_params {
      image = var.image_name
      size  = var.disk_size_gb
    }
  }

  network_interface {
    network       = "default"
    # Associated our public IP address to this instance
    access_config {
      nat_ip = google_compute_address.static.address
    }
  }

   # We connect to our instance via terraform and remotely executes our script using SSH
  provisioner "remote-exec" {
    script = var.script_path

    connection {
      type        = "ssh"
      host        = google_compute_address.static.address
      user        = var.username
      private_key = file(var.private_key_path)
    }
  }
}


# We create a public IP address for our google compute instance to utilize
resource "google_compute_address" "static" {
  name = "vm-public-address"
}

解决方法

对于 WireGuard,您需要启用 IP 转发。您尝试使用的资源用于 HTTP(S) 负载平衡器。

改为启用 google_compute_instance 资源属性 can_ip_forward

can_ip_forward -(可选)是否允许发送和接收 具有不匹配源或目标 IP 的数据包。这默认为 假的。

can_ip_forward

resource "google_compute_instance" "vm_instance" {
  name           = "development-vm"
  machine_type   = var.machine_size
  can_ip_forward = true
  ....
}