0

我已经gcp vm使用terraform modules. 我的模块文件夹中的内容如下

  #main.tf

 # google_compute_instance.default:
  resource "google_compute_instance" "default" {
     machine_type         = "${var.machinetype}"
     name                 = "${var.name}"
     project              = "demo"
     tags                 = []
     zone                 = "${var.zone}"

      boot_disk {

         initialize_params {
         image  = "https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-7-v20210701"
         size   = 20
         type   = "pd-balanced"
        }
      }


network_interface {
    network            = "default"
    subnetwork         = "default"
    subnetwork_project = "gcp-infrastructure-319318"
}


service_account {
    email  = "971558418058-compute@developer.gserviceaccount.com"
    scopes = [
        "https://www.googleapis.com/auth/devstorage.read_only",
        "https://www.googleapis.com/auth/logging.write",
        "https://www.googleapis.com/auth/logging.write",
        "https://www.googleapis.com/auth/monitoring.write",
        "https://www.googleapis.com/auth/service.management.readonly",
        "https://www.googleapis.com/auth/servicecontrol",
        "https://www.googleapis.com/auth/trace.append",
       ]
      }
    }

   -----------

  #variables.tf

  variable "zone" {
        default="us-east1-b"
     }

 variable "machinetype" {
       default="f1-micro"
    }

   ------------------
   #terraform.tfvars

   machinetype="g1-small"
   zone="europe-west1-b"
      

我的主要代码块如下

    $ cat providers.tf
       provider "google" {
           }

    $ cat main.tf
       module "gce" {
          source = "../../../modules/services/gce"
          name = "new-vm-tf"
        }

使用此代码,我可以成功创建一个新的 vm 实例

    $ gcloud compute instances list
     NAME       ZONE        MACHINE_TYPE  PREEMPTIBLE  INTERNAL_IP  EXTERNAL_IP  STATUS
     new-vm-tf  us-east1-b  f1-micro                   10.142.0.3                RUNNING

现在我需要创建一个新VM instance的机器类型e2-standard。我该如何处理这种情况?

如果我如下所示编辑我现有main.tf的,它将破坏现有的vm instance to create the new vm instance.

         $ cat main.tf
         module "gce" {
             source = "../../../modules/services/gce"
             name = "new-vm-tf1"
        }

terraform plan确认如下

   ~ name                 = "new-vm-tf" -> "new-vm-tf1" # forces replacement
   Plan: 1 to add, 0 to change, 1 to destroy.

我需要指针来重用相同的代码来创建一个现有的新 vm 而对现有的没有任何更改。请建议

4

1 回答 1

2

我建议您深入研究 terraform 机制和最佳实践。我有 2 个关键字要开始:tfstatevariables

tfstate 是部署上下文。如果您更改部署并且上下文不一致,Terraform 会删除不一致的部分并创建缺失的部分。

通过自定义条目中的值,这些变量对于重用一段通用代码很有用。

于 2021-07-11T11:47:00.243 回答