Terraform でストレージ バケットを作成してオブジェクトをアップロードする

このクイックスタート ガイドでは、ストレージ バケットをプロビジョニングし、sample_file.txt オブジェクトをバケットにアップロードする Terraform 構成ファイルを作成します。このクイックスタートを完了するには、Cloud Shell エディタ、Cloud Shell ターミナル、Terraform CLI(Cloud Shell にプリインストールされています)を使用します。

始める前に

このクイックスタートのプロジェクトを設定するには、次の手順を完了します。

  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. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  3. Google Cloud プロジェクトで課金が有効になっていることを確認します

  4. Cloud Storage API を有効にします。

    API を有効にする

  5. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  6. Google Cloud プロジェクトで課金が有効になっていることを確認します

  7. Cloud Storage API を有効にします。

    API を有効にする

フォルダ構造と Terraform 構成ファイルを作成する

Terraform 構成ファイルと、Cloud Storage にオブジェクトとしてアップロードするファイルを作成するには、次の手順を完了します。

  1. Google Cloud コンソールで、「Cloud Shell をアクティブにする」をクリックします。

    Cloud Shell をアクティブにする

    Google Cloud コンソールの下部で Cloud Shell セッションが開始し、コマンドライン プロンプトが表示されます。Cloud Shell はシェル環境です。Google Cloud CLI がすでにインストールされており、現在のプロジェクトの値もすでに設定されています。セッションが初期化されるまで数秒かかることがあります。

  1. Terraform 構成を適用するデフォルトの Google Cloud プロジェクトを設定します。
    export GOOGLE_CLOUD_PROJECT=PROJECT_ID
  2. Cloud Shell ターミナルで、ホーム ディレクトリをアクティブ ディレクトリとして設定します。
    cd
  3. terraform という名前の新しいフォルダを作成します。
    mkdir terraform
  4. Cloud Shell エディタを起動するには、Cloud Shell ウィンドウのツールバー上にある [エディタを開く] をクリックします。
  5. [Explorer] ペインで、terraform フォルダを右クリックし、[New File] をクリックします。
  6. ファイル名として「main.tf」と入力し、[OK] をクリックします。
  7. [Explorer] ペインで、terraform フォルダを右クリックし、[New File] をクリックします。
  8. ファイル名として「sample_file.txt」と入力し、[OK] をクリックします。

Terraform 構成ファイルでインフラストラクチャを定義する

Terraform 構成ファイルでプロビジョニングするインフラストラクチャを定義するには、次の手順を完了します。

  1. Cloud Shell エディタで 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. Cloud Shell エディタを開くには、Cloud Shell エディタのツールバーで [ターミナルを開く] をクリックします。

  2. Cloud Shell ターミナルで、terraform フォルダを現在の作業ディレクトリとして設定します。

    cd ~/terraform
    
  3. Terraform を初期化します。

    terraform init
    
  4. Cloud Shell を承認するよう求められたら、[承認] をクリックします。

    作業ディレクトリが初期化されます。作業ディレクトリが正常に初期化されると、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 の構成に基づいており、Cloud Storage のインフラストラクチャとサービスに対して Terraform が行う変更を示します。

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. Cloud Shell ターミナルで、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. Cloud Shell エディタで、[Explorer] ペインの terraform フォルダを右クリックして、[Delete] をクリックします。

  6. 確認画面が表示されたら、[OK] をクリックします。

  7. バケットとオブジェクトが削除されたことを確認するため、Google Cloud コンソールの [バケット] ページに移動します。

    [バケット] に移動

次のステップ