将 Terraform 状态存储在 Cloud Storage 存储桶中

在本教程中,您将学习如何在 Cloud Storage 存储桶中存储 Terraform 状态。

默认情况下,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 存储桶名称,以确保 Cloud Storage 存储桶具有唯一的名称。
    • google_storage_bucket:用于存储状态文件的 Cloud Storage 存储桶。此存储桶配置为具有以下属性:
      • force_destroy 设置为 false,以确保在存储桶中存在对象时不会被删除。这样可以确保存储桶中的状态信息不会被意外删除。
      • public_access_prevention 设置为 enforced,以确保存储桶内容不会被意外公开。
      • uniform_bucket_level_access 设置为 true 以允许使用 IAM 权限而不是访问控制列表来控制对存储桶及其内容的访问。
      • 启用了 versioning,以确保将状态的早期版本保留在存储桶中。
    • local_file:本地文件。此文件的内容指示 Terraform 将 Cloud Storage 存储桶用作远程后端。

预配 Cloud Storage 存储桶

  1. 初始化 Terraform:

    terraform init
    

    首次运行 terraform init 时,您在 main.tf 文件中指定的 Cloud Storage 存储桶尚不存在,因此 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 存储桶。出现提示时,输入 yes

运行此命令后,您的 Terraform 状态将存储在 Cloud Storage 存储桶中。Terraform 在运行命令之前从此存储桶拉取最新状态,并在运行命令后将最新状态推送到存储桶。