Menggunakan Terraform untuk membuat bucket penyimpanan dan mengupload objek

Dalam panduan memulai ini, Anda akan membuat file konfigurasi Terraform yang menyediakan bucket penyimpanan dan mengupload objek sample_file.txt ke bucket tersebut. Untuk menyelesaikan panduan memulai ini, Anda akan menggunakan shell dan terminal lokal atau Cloud Shell Editor dan terminal Cloud Shell. Anda juga akan menggunakan Terraform CLI, yang sudah diinstal sebelumnya di Cloud Shell.

Sebelum memulai

Guna menyiapkan project untuk panduan memulai ini, selesaikan langkah-langkah berikut:

  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

Membuat struktur folder dan file konfigurasi Terraform

Untuk membuat file konfigurasi Terraform dan yang akan Anda upload sebagai objek ke Cloud Storage, lakukan langkah-langkah berikut:

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. Tetapkan project Google Cloud default tempat Anda ingin menerapkan konfigurasi Terraform:
    export GOOGLE_CLOUD_PROJECT=PROJECT_ID
  2. Di terminal Cloud Shell, tetapkan direktori beranda sebagai direktori aktif:
    cd
  3. Buat folder baru bernama terraform:
    mkdir terraform
  4. Luncurkan Cloud Shell Editor dengan mengklik Open Editor di toolbar jendela Cloud Shell.
  5. Di panel Explorer, klik kanan folder terraform, lalu klik New File.
  6. Masukkan main.tf sebagai nama file, lalu klik OK.
  7. Di panel Explorer, klik kanan folder terraform, lalu klik New File.
  8. Masukkan sample_file.txt sebagai nama file, lalu klik OK.

Shell lokal

  1. Jika Anda belum melakukannya, instal dan konfigurasikan Terraform. Pastikan Anda menginstal dan melakukan inisialisasi Google Cloud CLI.

    Secara default, Terraform membaca konfigurasi yang dibuat oleh Google Cloud CLI dan men-deploy resource yang nantinya Anda tentukan ke project Google Cloud CLI yang aktif.

  2. Di terminal Anda, tetapkan direktori beranda sebagai direktori aktif:
    cd
  3. Buat folder baru bernama terraform:
    mkdir terraform
  4. Di editor teks pilihan Anda, buat file baru bernama main.tf di folder terraform.
  5. Di editor teks pilihan Anda, buat file baru bernama sample_file.txt di folder terraform.

Menentukan infrastruktur di file konfigurasi Terraform

Untuk menentukan infrastruktur yang ingin Anda sediakan di file konfigurasi Terraform, selesaikan langkah-langkah berikut:

  1. Buka file main.tf.

  2. Salin contoh berikut ke file 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
    }

    Ganti:

    • BUCKET_NAME dengan nama bucket yang ingin Anda buat. Contoh, my-bucket.

    • OBJECT_NAME dengan nama objek yang ingin Anda upload. Untuk panduan memulai ini, masukkan nama sample_file.txt.

    • OBJECT_PATH dengan jalur ke objek yang ingin Anda upload. Untuk panduan memulai ini, masukkan jalur ~/terraform/sample_file.txt.

  3. Simpan file main.tf.

Melakukan inisialisasi direktori kerja yang berisi file konfigurasi Terraform

Untuk menginisialisasi Terraform dan direktori yang berisi file konfigurasi Terraform, lakukan langkah-langkah berikut:

  1. Di terminal, tetapkan folder terraform sebagai direktori kerja saat ini:

    cd ~/terraform
  2. Lakukan inisialisasi Terraform:

    terraform init
  3. Jika Anda menggunakan Cloud Shell dan diminta untuk memberikan otorisasi pada Cloud Shell, klik Authorize.

    Terraform menginisialisasi direktori kerja. Jika berhasil menginisialisasi direktori kerja, Terraform akan menampilkan output yang mirip dengan berikut ini:

    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.
    

Melihat pratinjau rencana eksekusi

Rencana eksekusi Terraform didasarkan pada konfigurasi Terraform dan menunjukkan perubahan yang direncanakan oleh Terraform pada infrastruktur dan layanan Cloud Storage.

Lihat rencana eksekusi Terraform:

terraform plan

Contoh output:

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.

Menerapkan perubahan yang diusulkan dalam rencana eksekusi

Untuk menerapkan perubahan di file konfigurasi Terraform, selesaikan langkah-langkah berikut:

  1. Terapkan perubahan dari rencana eksekusi ke infrastruktur Cloud Storage dengan perintah berikut. Saat Anda menerapkan perubahan, Terraform akan membuat bucket penyimpanan dan mengupload sample_file.txt ke bucket tersebut.

    terraform apply

    Contoh output:

    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. Ketik yes dan tekan Enter.

    Jika berhasil, Terraform akan menampilkan output yang mirip dengan berikut ini:

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

Melihat bucket penyimpanan dan objek yang diupload

Di Konsol Google Cloud, buka halaman Buckets Cloud Storage.

Buka Buckets

Bucket baru yang berisi objek sample_file.txt akan muncul. Perhatikan bahwa resource mungkin memerlukan waktu beberapa menit untuk disediakan setelah Anda menjalankan terraform apply.

Membersihkan project

Untuk menghindari timbulnya biaya yang tidak terduga dari resource Google Cloud yang Anda buat selama panduan memulai ini, selesaikan langkah-langkah berikut untuk membersihkan resource:

  1. Di terminal, tetapkan folder terraform sebagai direktori kerja saat ini:

    cd ~/terraform
  2. Hapus resource Cloud Storage yang Anda buat berdasarkan file konfigurasi Terraform:

    terraform destroy
  3. Jika berhasil, Terraform akan menampilkan output yang mirip dengan berikut ini:

    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. Ketik yes dan tekan Enter. Jika berhasil, Terraform akan menampilkan output yang mirip dengan berikut ini:

    Destroy complete! Resources: 2 destroyed.
    
  5. Di terminal, hapus folder terraform.

    rm -rf ~/terraform
  6. Untuk memverifikasi bahwa bucket dan objek telah dihapus, buka halaman Buckets di Konsol Google Cloud.

    Buka Buckets

Langkah berikutnya