使用 Terraform 创建存储桶并上传对象

在本快速入门指南中,您将创建一个 Terraform 配置文件,以预配一个存储桶并将 sample_file.txt 对象上传到该存储桶。如需完成本快速入门,您将使用本地 shell 和终端,或 Cloud Shell Editor 和 Cloud Shell 终端。您还将使用 Cloud Shell 中预安装的 Terraform CLI。

准备工作

如需为本快速入门设置项目,请完成以下步骤:

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the Cloud Storage API.

    Enable the API

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  6. Make sure that billing is enabled for your Google Cloud project.

  7. Enable the Cloud Storage API.

    Enable the API

创建文件夹结构和 Terraform 配置文件

如需创建 Terraform 配置文件以及要以对象形式上传到 Cloud Storage 的文件,请完成以下步骤:

Cloud Shell

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  1. 设置要在其中应用 Terraform 配置的默认 Google Cloud 项目:
    export GOOGLE_CLOUD_PROJECT=PROJECT_ID
  2. 在 Cloud Shell 终端中,将主目录设置为活跃目录:
    cd
  3. 创建一个名为 terraform 的新文件夹:
    mkdir terraform
  4. 通过点击 Cloud Shell 窗口工具栏上的打开编辑器,启动 Cloud Shell Editor。
  5. 浏览器窗格中,右键点击 terraform 文件夹,然后点击新建文件
  6. 输入 main.tf 作为文件名,然后点击确定
  7. 浏览器窗格中,右键点击 terraform 文件夹,然后点击新建文件
  8. 输入 sample_file.txt 作为文件名,然后点击确定

本地 shell

  1. 如果您尚未安装并配置 Terraform,请先执行此操作。 确保您已安装初始化 Google Cloud CLI。

    默认情况下,Terraform 会读取 Google Cloud CLI 创建的配置,并将您稍后指定的资源部署到您的有效 Google Cloud CLI 项目中。

  2. 在终端中,将主目录设置为活跃目录:
    cd
  3. 创建一个名为 terraform 的新文件夹:
    mkdir terraform
  4. 在您选择的文本编辑器中,在 terraform 文件夹中创建一个名为 main.tf 的新文件。
  5. 在您选择的文本编辑器中,在 terraform 文件夹中创建一个名为 sample_file.txt 的新文件。

在 Terraform 配置文件中定义基础架构

如需在 Terraform 配置文件定义您要预配的基础架构,请完成以下步骤:

  1. 打开 main.tf 文件。

  2. 将以下示例复制到 main.tf 文件中。

    # Create new storage bucket in the US
    # location with Standard Storage
    
    resource "google_storage_bucket" "static" {
     name          = "BUCKET_NAME"
     location      = "US"
     storage_class = "STANDARD"
    
     uniform_bucket_level_access = true
    }
    
    # Upload a text file as an object
    # to the storage bucket
    
    resource "google_storage_bucket_object" "default" {
     name         = "OBJECT_NAME"
     source       = "OBJECT_PATH"
     content_type = "text/plain"
     bucket       = google_storage_bucket.static.id
    }

    您需要进行如下替换:

    • BUCKET_NAME 替换为您要创建的存储桶的名称。例如 my-bucket

    • OBJECT_NAME 替换为您要上传的对象的名称。对于本快速入门,请输入名称 sample_file.txt

    • OBJECT_PATH 替换为您要上传的对象的路径。对于本快速入门,请输入路径 ~/terraform/sample_file.txt

  3. 保存 main.tf 文件。

初始化包含 Terraform 配置文件的工作目录

如需初始化 Terraform 和包含 Terraform 配置文件的目录,请完成以下步骤:

  1. 在终端中,将 terraform 文件夹设置为当前工作目录:

    cd ~/terraform
  2. 初始化 Terraform:

    terraform init
  3. 如果您使用的是 Cloud Shell,并且系统提示您为 Cloud Shell 授权,请点击授权

    Terraform 会初始化工作目录。如果它成功初始化工作目录,则 Terraform 将返回类似于以下内容的输出:

    Terraform has been successfully initialized!
    
    You may now begin working with Terraform. Try running "terraform plan" to see
    any changes that are required for your infrastructure. All Terraform commands
    should now work.
    
    If you ever set or change modules or backend configuration for Terraform,
    rerun this command to reinitialize your working directory. If you forget, other
    commands will detect it and remind you to do so if necessary.
    

预览执行计划

Terraform 执行计划基于 Terraform 配置,包含 Terraform 计划要对 Cloud Storage 基础架构和服务进行的更改。

查看 Terraform 执行计划:

terraform plan

输出示例:

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # google_storage_bucket.static will be created
  + resource "google_storage_bucket" "static" {
      + force_destroy               = false
      + id                          = (known after apply)
      + location                    = "US"
      + name                        = "my-bucket"
      + project                     = "my-project"
      + public_access_prevention    = (known after apply)
      + self_link                   = (known after apply)
      + storage_class               = "STANDARD"
      + uniform_bucket_level_access = true
      + url                         = (known after apply)

      + versioning {
          + enabled = (known after apply)
        }

      + website {
          + main_page_suffix = (known after apply)
          + not_found_page   = (known after apply)
        }
    }

  # google_storage_bucket_object.default will be created
  + resource "google_storage_bucket_object" "default" {
      + bucket         = (known after apply)
      + content_type   = "text/plain"
      + crc32c         = (known after apply)
      + detect_md5hash = "different hash"
      + id             = (known after apply)
      + kms_key_name   = (known after apply)
      + md5hash        = (known after apply)
      + media_link     = (known after apply)
      + name           = "sample_file.txt"
      + output_name    = (known after apply)
      + self_link      = (known after apply)
      + source         = "sample_file.txt"
      + storage_class  = (known after apply)
    }

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

应用执行计划中建议的更改

如需在 Terraform 配置文件中应用更改,请完成以下步骤:

  1. 使用以下命令将执行计划中的更改应用于 Cloud Storage 基础架构。应用更改后,Terraform 会创建一个存储桶,并将 sample_file.txt 上传到该存储桶。

    terraform apply

    输出示例:

    Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
      + create
    
    Terraform will perform the following actions:
    
      # google_storage_bucket.static will be created
      + resource "google_storage_bucket" "static" {
          + force_destroy               = false
          + id                          = (known after apply)
          + location                    = "US"
          + name                        = "my-bucket"
          + project                     = "my-project"
          + public_access_prevention    = (known after apply)
          + self_link                   = (known after apply)
          + storage_class               = "STANDARD"
          + uniform_bucket_level_access = true
          + url                         = (known after apply)
    
          + versioning {
              + enabled = (known after apply)
            }
    
          + website {
              + main_page_suffix = (known after apply)
              + not_found_page   = (known after apply)
            }
        }
    
      # google_storage_bucket_object.default will be created
      + resource "google_storage_bucket_object" "default" {
          + bucket         = (known after apply)
          + content_type   = "text/plain"
          + crc32c         = (known after apply)
          + detect_md5hash = "different hash"
          + id             = (known after apply)
          + kms_key_name   = (known after apply)
          + md5hash        = (known after apply)
          + media_link     = (known after apply)
          + name           = "sample_file.txt"
          + output_name    = (known after apply)
          + self_link      = (known after apply)
          + source         = "sample_file.txt"
          + storage_class  = (known after apply)
        }
    
    Plan: 2 to add, 0 to change, 0 to destroy.
    
    Do you want to perform these actions?
      Terraform will perform the actions described above.
      Only 'yes' will be accepted to approve.
    
      Enter a value:
    
  2. 输入 yes 并按 Enter 键。

    如果成功,Terraform 将返回类似于以下内容的输出:

    Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
    

查看存储桶和上传的对象

在 Google Cloud 控制台中,进入 Cloud Storage 存储桶页面。

进入“存储桶”

系统随即会显示包含 sample_file.txt 对象的新存储桶。请注意,运行 terraform apply 后,资源可能需要几分钟时间才能完成预配。

清理您的项目

为避免您在本快速入门中创建的 Google Cloud 资源产生意外费用,请完成以下步骤来清理资源:

  1. 在终端中,将 terraform 文件夹设置为当前工作目录:

    cd ~/terraform
  2. 删除您基于 Terraform 配置文件创建的 Cloud Storage 资源:

    terraform destroy
  3. 如果成功,Terraform 将返回类似于以下内容的输出:

    Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
      - destroy
    
    Terraform will perform the following actions:
    
      # google_storage_bucket.static will be destroyed
      - resource "google_storage_bucket" "static" {
          - default_event_based_hold    = false -> null
          - force_destroy               = false -> null
          - id                          = "my-bucket" -> null
          - labels                      = {} -> null
          - location                    = "US" -> null
          - name                        = "" -> null
          - project                     = "example-project" -> null
          - public_access_prevention    = "inherited" -> null
          - requester_pays              = false -> null
          - self_link                   = "https://www.googleapis.com/storage/v1/b/cbonnie-bucket-9" -> null
          - storage_class               = "STANDARD" -> null
          - uniform_bucket_level_access = true -> null
          - url                         = "gs://BUCKET_NAME" -> null
        }
    
      # google_storage_bucket_object.default will be destroyed
      - resource "google_storage_bucket_object" "default" {
          - bucket           = "my-bucket" -> null
          - content_type     = "text/plain" -> null
          - crc32c           = "yZRlqg==" -> null
          - detect_md5hash   = "XrY7u+Ae7tCTyyK7j1rNww==" -> null
          - event_based_hold = false -> null
          - id               = "my-bucket-sample_file.txt" -> null
          - md5hash          = "XrY7u+Ae7tCTyyK7j1rNww==" -> null
          - media_link       = "https://storage.googleapis.com/download/storage/v1/b/BUCKET_NAME/o/sample_file.txt?generation=1675800386233102&alt=media" -> null
          - metadata         = {} -> null
          - name             = "sample_file.txt" -> null
          - output_name      = "sample_file.txt" -> null
          - self_link        = "https://www.googleapis.com/storage/v1/b/BUCKET_NAME/o/sample_file.txt" -> null
          - source           = "sample_file.txt" -> null
          - storage_class    = "STANDARD" -> null
          - temporary_hold   = false -> null
        }
    
    Plan: 0 to add, 0 to change, 2 to destroy.
    
    Do you really want to destroy all resources?
      Terraform will destroy all your managed infrastructure, as shown above.
      There is no undo. Only 'yes' will be accepted to confirm.
    
      Enter a value:
    
  4. 输入 yes 并按 Enter 键。如果成功,Terraform 将返回类似于以下内容的输出:

    Destroy complete! Resources: 2 destroyed.
    
  5. 在终端中,删除 terraform 文件夹。

    rm -rf ~/terraform
  6. 如需验证存储桶和对象是否已删除,请前往 Google Cloud 控制台中的存储桶页面。

    进入“存储桶”

后续步骤