【问题标题】:How to create GCP instance with public IP with terraform如何使用 terraform 创建具有公共 IP 的 GCP 实例
【发布时间】:2021-05-12 10:59:33
【问题描述】:

我需要在gcp 中创建一个具有公共 IP 的 VM 实例(实例可以为自己随机选择一个),而无需明确定义一个。

那么我该怎么做呢?

这是我可以用来实现此目的的gcloud 命令(创建一个自动分配公共 ip 的 vm 实例)

gcloud compute instances create controller-1 \
    --async \
    --boot-disk-size 200GB \
    --can-ip-forward \
    --image-family ubuntu-2004-lts \
    --image-project ubuntu-os-cloud \
    --machine-type e2-standard-2 \
    --private-network-ip 10.240.0.10 \
    --scopes compute-rw,storage-ro,service-management,service-control,logging-write,monitoring \
    --subnet kubernetes \
    --tags kubernetes-the-hard-way,controller

上面的命令将创建一个具有内部 IP 10.240.0.10 的 vm 和一个带有一些随机选择的 ip 地址的公共 ip。

所以我想和terraform达到同样的目标

这是我的terraform 代码。但是我该怎么做呢?

resource "google_compute_instance" "controllers" {
  name         = "controller-0"
  machine_type = "e2-standard-2"
  zone         = var.zone

  can_ip_forward = true



  tags = ["kubernetes-the-hard-way", "controller"]
  

  boot_disk {
    initialize_params {
      image = "ubuntu-2004-focal-v20200720"
    }
  }

  network_interface {
    subnetwork = google_compute_subnetwork.kubernetes.name
    network_ip = "10.240.0.10"  // private ip but how to assign a public ip (randomly)  
  }

  service_account {
    scopes = ["compute-rw", "storage-ro", "service-management", "service-control", "logging-write", "monitoring"]
  }
}

【问题讨论】:

    标签: google-cloud-platform terraform


    【解决方案1】:

    一个空的 access_config 块会为您的实例分配一个外部临时 IP。

    network_interface {
        network = "default"
        access_config {}
    }
    

    【讨论】:

      【解决方案2】:

      看起来您需要在“network_interface”下指定“access_config”以根据来自terraform的this example为GCE实例分配外部(公共)IP。

      resource "google_compute_address" "static" {
        name = "ipv4-address"
      }
      
      data "google_compute_image" "debian_image" {
        family  = "debian-9"
        project = "debian-cloud"
      }
      
      resource "google_compute_instance" "instance_with_ip" {
        name         = "vm-instance"
        machine_type = "f1-micro"
        zone         = "us-central1-a"
      
        boot_disk {
          initialize_params {
            image = data.google_compute_image.debian_image.self_link
          }
        }
      
        network_interface {
          network = "default"
          access_config {
            nat_ip = google_compute_address.static.address
          }
        }
      }
      

      Google Cloud Platform 的计算引擎支持两种external IP addresses

      Static external IP addresses

      Ephemeral external IP addresses

      【讨论】:

      • ...截图?
      • 值得注意的是,您确实为静态 IP 地址付费,我上次检查时每月大约 7.20 美元。临时选项是免费的。
      • 如何在GCP中通过该地址资源的名称分配nat_ip已经保留的IP?
      猜你喜欢
      • 2020-09-05
      • 2018-07-30
      • 2020-07-15
      • 2020-05-03
      • 2019-08-12
      • 2021-02-20
      • 2020-06-16
      • 2023-02-02
      • 2021-06-21
      相关资源
      最近更新 更多