Google-Cloud-Platform

terraform apply error alreadyExists on untouched resources

  • December 3, 2021

我正在按照官方指南開始一個新的 terraform 項目:

https://learn.hashicorp.com/tutorials/terraform/gke?in=terraform/kubernetes&utm_source=WEBSITE&utm_medium=WEB_IO&utm_offer=ARTICLE_PAGE&utm_content=DOCS&_ga=2.91746777.2118895439.1637849824-960084622.1637849824

我設法讓它執行。(我將它作為送出時觸發的Google云建構任務的一部分執行)

但是,如果我更改資源中的某些內容(例如,我將“gke_num_nodes”預設值從 2 替換為 1),當我terraform apply再次執行時,這就是我得到的:


Plan: 4 to add, 0 to change, 0 to destroy.

Changes to Outputs:
 + kubernetes_cluster_host = (known after apply)
 + kubernetes_cluster_name = "workspace-auto-gke"
 + project_id              = "workspace-auto"
 + region                  = "europe-west4"
google_compute_network.vpc: Creating...
╷
│ Error: Error creating Network: googleapi: Error 409: The resource 'projects/workspace-auto/global/networks/workspace-auto-vpc' already exists, alreadyExists
│ 
│   with google_compute_network.vpc,
│   on vpc.tf line 15, in resource "google_compute_network" "vpc":
│   15: resource "google_compute_network" "vpc" {
│ 
╵

有沒有辦法讓它不嘗試重新創建現有的未觸及資源?

cloudbuild.json的如下:

{
 "steps": [
   {
     "name": "hashicorp/terraform",
     "entrypoint": "/bin/sh",
     "args": [
       "./cloudbuild/prepare-terraform.sh"
     ]
   }
 ],
 "logsBucket": "gs://my-bucket/logdir",
 "serviceAccount": "projects/my-proj/serviceAccounts/my-service-account@my-proj.iam.gserviceaccount.com"
}

prepare-terraform.sh簡單地

terraform init
terraform plan
terraform apply -auto-approve

terraform 狀態需要儲存在所有建構都可以訪問的位置。例如在Google云儲存桶中,如下所示:https ://www.terraform.io/docs/language/settings/backends/gcs.html

如果您使用 Terraform 創建資源,請不要在 Terraform 之外修改它們。

如果您手動更改某些內容,Terraform 將嘗試將其放回 HCL 聲明它的方式以及 Terraform 保存它的方式。

這稱為聲明性。您正在嘗試使 Terraform 動態化,這首先會擊敗使用 Terraform。

引用自:https://serverfault.com/questions/1084620