將 Terraform 狀態儲存在 Cloud Storage 值區中

在本教學課程中,您將瞭解如何將 Terraform 狀態儲存在 Cloud Storage bucket 中。

根據預設,Terraform 會將狀態儲存在名為 terraform.tfstate 的本機檔案中。如果多位使用者同時執行 Terraform,且每部機器對目前的基礎架構都有自己的理解,這個預設設定會使得團隊難以使用 Terraform。

為協助您避免這類問題,本頁說明如何設定指向 Cloud Storage 值區的遠端狀態。遠端狀態是 Terraform 後端的一項功能。

準備環境

  1. 複製包含 Terraform 範例的 GitHub 存放區:

    git clone https://github.com/terraform-google-modules/terraform-docs-samples.git --single-branch
    
  2. 變更為工作目錄:

    cd terraform-docs-samples/storage/remote_terraform_backend_template
    

查看 Terraform 檔案

  1. 查看 main.tf 檔案:

    cat main.tf
    

    輸出內容類似如下

    resource "random_id" "default" {
      byte_length = 8
    }
    
    resource "google_storage_bucket" "default" {
      name     = "${random_id.default.hex}-terraform-remote-backend"
      location = "US"
    
      force_destroy               = false
      public_access_prevention    = "enforced"
      uniform_bucket_level_access = true
    
      versioning {
        enabled = true
      }
    }
    
    resource "local_file" "default" {
      file_permission = "0644"
      filename        = "${path.module}/backend.tf"
    
      # You can store the template in a file and use the templatefile function for
      # more modularity, if you prefer, instead of storing the template inline as
      # we do here.
      content = <<-EOT
      terraform {
        backend "gcs" {
          bucket = "${google_storage_bucket.default.name}"
        }
      }
      EOT
    }

    這個檔案說明下列資源:

    • random_id:附加至 Cloud Storage bucket 名稱,確保 Cloud Storage bucket 名稱不重複。
    • google_storage_bucket:用於儲存狀態檔案的 Cloud Storage 值區。這個 bucket 已設定下列屬性:
      • force_destroy 設為 false,確保值區中如有物件,就不會遭到刪除。這樣才能確保儲存空間中的狀態資訊不會遭到誤刪。
      • public_access_prevention 設為 enforced,確保儲存空間內容不會意外公開。
      • uniform_bucket_level_access 設為 true,即可使用 IAM 權限 (而非存取控制清單) 控管值區和內容的存取權
      • versioning,確保值區中保留較舊版本的狀態。
    • local_file:本機檔案。這個檔案的內容會指示 Terraform 在建立值區後,使用 Cloud Storage 值區做為遠端後端。

佈建 Cloud Storage bucket

  1. 初始化 Terraform:

    terraform init
    

    首次執行 terraform init 時,您在 main.tf 檔案中指定的 Cloud Storage bucket 尚不存在,因此 Terraform 會初始化本機後端,將狀態儲存在本機檔案系統中。

  2. 套用設定,佈建 main.tf 檔案中說明的資源:

    terraform apply
    

    系統顯示提示訊息時,請輸入 yes

    首次執行 terraform apply 時,Terraform 會佈建 Cloud Storage 值區,用於儲存狀態。此外,這個指令也會建立本機檔案;這個檔案的內容會指示 Terraform 使用 Cloud Storage 值區做為遠端後端,以儲存狀態。

將狀態遷移至 Cloud Storage 值區

  1. 將 Terraform 狀態遷移至遠端 Cloud Storage 後端:

    terraform init -migrate-state
    

    Terraform 會偵測到您在本機已有狀態檔案,並提示您將狀態遷移至新的 Cloud Storage bucket。系統顯示提示訊息時,請輸入 yes

執行這項指令後,Terraform 狀態會儲存在 Cloud Storage bucket 中。Terraform 會先從這個 bucket 提取最新狀態,再執行指令,並在執行指令後將最新狀態推送至 bucket。