简体   繁体   中英

How to add a static IP to a GCE VM instance using Terraform

I would like to deploy a Google Cloud Compute Engine VM instance with Terraform 0.12. My problem is that 2 IP addresses are created. I have a static and an ephemeral IP address. The VM instance is using the ephemeral IP. The zone is correct.

This is the code that I'm using:

resource "google_compute_address" "static-ip" {
  name = "static-ip"
  address_type = "EXTERNAL"
  region = var.location
}

Inside the Compute Engine VM instance, in google_compute_instance_template , the network is configured this way:

  network_interface {
    network = "default-net"
    access_config {
      nat_ip = google_compute_address.static-ip.address
    }
   }

After that, I instantiate the VM instance with the resource google_compute_instance_from_template .

I was wondering, how can I attach the external IP to my VM instance and only have one IP address?

You will have 2 IP an internal IP and optional external IP (ephemeral or static) as described in GCP IP Addresses article

To create an instance with Static IP using Terraform take a look at their google_compute_address example

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
    }
  }
}

Read the Argument Reference section to know what is expected in each variable

thanks for the responds. I solved the problem by myself. I think the problem was that I created a VM with internal IP in the first place. Than I changed my terraform script to an extermal ephemeral IP. Afterwards I changed everything to static external.

Terraform didn't delete the ephemeral IP. So I deleted the ip manually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM