Terraform forcing new resources on every apply

google-cloud-platformterraform

I'm making a small VM in Google Cloud, with one disk base image, and wish to manage my GCP infra with HashiCorp's Terraform Here's the basic TF code I'm running:

resource "google_compute_disk" "blog" {
    image = "ubuntu-1604-lts"
}
resource "google_compute_instance" "blog-vm" {
    disk {
        disk = "${google_compute_disk.blog.id}"
        auto_delete = false
    }
}

When I tf apply, it works fine the first time. But subsequent plans want to rebuild the disk, and thus the VM itself.

-/+ google_compute_disk.blog
    image:                      "ubuntu-1604-xenial-v20170619a" =>
                                "ubuntu-1604-lts" (forces new resource)

My goal here is to pick the latest ubuntu-lts template on image creation, but to leave the disk alone if created. Is this possible in Terraform?

Best Answer

The general solution to this class of problem is the ignore_changes lifecycle setting, which causes Terraform to ignore changes to specific attributes when creating a plan.

resource "google_compute_disk" "blog" {
  image = "ubuntu-1604-lts"

  lifecycle {
    ignore_changes = ["image"]
  }
}

With this in place, Terraform will not automatically plan to replace the disk when image changes. If you do want to replace the disk for a new image, it'd be necessary to manually taint it:

$ terraform taint google_compute_disk.blog

This marks the instance as "tainted" in the state, which means the next plan will include a step to destroy the disk and create a new one in its place. Since the instance then uses that disk, the plan will also update or replace that as necessary.

Related Topic