Utilizzare Terraform per creare bucket di archiviazione e caricare oggetti

In questa guida rapida, creerai un file di configurazione Terraform che esegue il provisioning di un bucket di archiviazione e carica un oggetto sample_file.txt nel bucket. Per completare questa guida rapida, utilizzerai la shell e il terminale locali o l'editor di Cloud Shell e il terminale Cloud Shell. Utilizzerai anche Terraform CLI, preinstallata in Cloud Shell.

Prima di iniziare

Per configurare un progetto per questa guida rapida, completa i seguenti passaggi:

  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

  8. Crea la struttura delle cartelle e il file di configurazione Terraform

    Per creare il file di configurazione Terraform e il file che caricherai come oggetto in Cloud Storage, completa i seguenti passaggi:

    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. Imposta il progetto Google Cloud predefinito in cui vuoi applicare la tua configurazione Terraform:
      export GOOGLE_CLOUD_PROJECT=PROJECT_ID
    2. Nel terminale Cloud Shell, imposta la home directory come directory attiva:
      cd
    3. Crea una nuova cartella denominata terraform:
      mkdir terraform
    4. Avvia l'editor di Cloud Shell facendo clic su Apri editor sulla barra degli strumenti della finestra di Cloud Shell.
    5. Nel riquadro Explorer, fai clic con il tasto destro del mouse sulla cartella terraform e poi fai clic su Nuovo file.
    6. Inserisci main.tf come nome del file e fai clic su Ok.
    7. Nel riquadro Explorer, fai clic con il tasto destro del mouse sulla cartella terraform e poi fai clic su Nuovo file.
    8. Inserisci sample_file.txt come nome del file e fai clic su Ok.

    Shell locale

    1. Se non lo hai ancora fatto, installa e configura Terraform. Assicurati di installare e inizializzare Google Cloud CLI.

      Per impostazione predefinita, Terraform legge la configurazione creata da Google Cloud CLI e distribuisce le risorse che specifichi in un secondo momento nel tuo progetto Google Cloud CLI attivo.

    2. Nel terminale, imposta la home directory come directory attiva:
      cd
    3. Crea una nuova cartella denominata terraform:
      mkdir terraform
    4. Nell'editor di testo che preferisci, crea un nuovo file denominato main.tf nella cartella terraform.
    5. Nell'editor di testo che preferisci, crea un nuovo file denominato sample_file.txt nella cartella terraform.

    Definisci l'infrastruttura nel file di configurazione Terraform

    Per definire l'infrastruttura di cui vuoi eseguire il provisioning nel file di configurazione Terraform, completa i seguenti passaggi:

    1. Apri il file main.tf.

    2. Copia il seguente esempio nel 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
      }

      Sostituisci:

      • BUCKET_NAME con il nome del bucket che vuoi creare. Ad esempio, my-bucket.

      • OBJECT_NAME con il nome dell'oggetto che vuoi caricare. Per questa guida rapida, inserisci il nome sample_file.txt.

      • OBJECT_PATH con il percorso dell'oggetto che vuoi caricare. Per questa guida rapida, inserisci il percorso ~/terraform/sample_file.txt.

    3. Salva il file main.tf.

    Inizializza la directory di lavoro contenente il file di configurazione Terraform

    Per inizializzare Terraform e la directory contenente il file di configurazione di Terraform, completa i seguenti passaggi:

    1. Nel terminale, imposta la cartella terraform come directory di lavoro corrente:

      cd ~/terraform
    2. Inizializza Terraform:

      terraform init
    3. Se utilizzi Cloud Shell e ti viene chiesto di autorizzare Cloud Shell, fai clic su Autorizza.

      Terraform inizializza la directory di lavoro. Se inizializza correttamente la directory di lavoro, Terraform restituisce un output simile al seguente:

      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.
      

    Visualizzare l'anteprima del piano di esecuzione

    Il piano di esecuzione di Terraform si basa sulla configurazione di Terraform e indica le modifiche che Terraform prevede di apportare all'infrastruttura e ai servizi Cloud Storage.

    Visualizza il piano di esecuzione di Terraform:

    terraform plan

    Output di esempio:

    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.
    

    Applica le modifiche proposte nel piano di esecuzione

    Per applicare le modifiche nel file di configurazione Terraform, completa i seguenti passaggi:

    1. Applica le modifiche del piano di esecuzione all'infrastruttura Cloud Storage con il comando seguente. Quando applichi le modifiche, Terraform crea un bucket di archiviazione e carica sample_file.txt nel bucket.

      terraform apply

      Output di esempio:

      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. Digita yes e premi Invio.

      Se l'operazione ha esito positivo, Terraform restituisce un output simile al seguente:

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

    Visualizzare il bucket di archiviazione e l'oggetto caricato

    Nella console Google Cloud , vai alla pagina Bucket in Cloud Storage.

    Vai a Bucket

    Viene visualizzato il nuovo bucket, contenente l'oggetto sample_file.txt. Tieni presente che il provisioning delle risorse potrebbe richiedere alcuni minuti dopo l'esecuzione di terraform apply.

    Pulizia del progetto

    Per evitare addebiti imprevisti dalle risorse Google Cloud che hai creato durante questa guida rapida, completa i seguenti passaggi per pulire le risorse:

    1. Nel terminale, imposta la cartella terraform come directory di lavoro corrente:

      cd ~/terraform
    2. Elimina le risorse Cloud Storage che hai creato in base al file di configurazione Terraform:

      terraform destroy
    3. Se l'operazione ha esito positivo, Terraform restituisce un output simile al seguente:

      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. Digita yes e premi Invio. Se l'operazione ha esito positivo, Terraform restituisce un output simile al seguente:

      Destroy complete! Resources: 2 destroyed.
      
    5. Nel terminale, elimina la cartella terraform.

      rm -rf ~/terraform
    6. Per verificare che il bucket e l'oggetto siano stati eliminati, vai alla pagina Bucket nella console Google Cloud .

      Vai a Bucket

    Passaggi successivi