Use o Terraform para criar contentores de armazenamento e carregar objetos

Neste guia de início rápido, vai criar um ficheiro de configuração do Terraform que aprovisiona um contentor de armazenamento e carrega um objeto sample_file.txt para o contentor. Para concluir este início rápido, vai usar o terminal e a shell locais, ou o editor e o terminal do Cloud Shell. Também vai usar a CLI do Terraform, que está pré-instalada no Cloud Shell.

Antes de começar

Para configurar um projeto para este início rápido, conclua os seguintes passos:

  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.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Cloud Storage API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the API

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

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Cloud Storage API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the API

  8. Crie a estrutura de pastas e o ficheiro de configuração do Terraform

    Para criar o ficheiro de configuração do Terraform e o ficheiro que vai carregar como um objeto para o Cloud Storage, conclua os seguintes passos:

    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. Defina o Google Cloud projeto predefinido
      onde quer aplicar a sua configuração do Terraform:
      export GOOGLE_CLOUD_PROJECT=PROJECT_ID
    2. No terminal do Cloud Shell, defina o diretório inicial como o diretório ativo:
      cd
    3. Crie uma nova pasta com o nome terraform:
      mkdir terraform
    4. Inicie o Cloud Shell Editor clicando em Abrir editor na barra de ferramentas da janela do Cloud Shell.
    5. No painel Explorador, clique com o botão direito do rato na pasta terraform e, de seguida, clique em Novo ficheiro.
    6. Introduza main.tf como nome do ficheiro e, de seguida, clique em OK.
    7. No painel Explorador, clique com o botão direito do rato na pasta terraform e, de seguida, clique em Novo ficheiro.
    8. Introduza sample_file.txt como nome do ficheiro e, de seguida, clique em OK.

    Shell local

    1. Se ainda não o fez, instale e configure o Terraform. Certifique-se de que instala e inicializa a CLI Google Cloud.

      Por predefinição, o Terraform lê a configuração criada pela CLI do Google Cloud e implementa os recursos que especificar posteriormente no seu projeto ativo da CLI do Google Cloud.

    2. No terminal, defina o diretório inicial como o diretório ativo:
      cd
    3. Crie uma nova pasta com o nome terraform:
      mkdir terraform
    4. No editor de texto à sua escolha, crie um novo ficheiro com o nome main.tf na pasta terraform.
    5. No editor de texto à sua escolha, crie um novo ficheiro com o nome sample_file.txt na pasta terraform.

    Defina a infraestrutura no ficheiro de configuração do Terraform

    Para definir a infraestrutura que quer aprovisionar no ficheiro de configuração do Terraform, conclua os seguintes passos:

    1. Abra o ficheiro main.tf.

    2. Copie o seguinte exemplo para o ficheiro 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
      }

      Substituição:

      • BUCKET_NAME com o nome do contentor que quer criar. Por exemplo, my-bucket.

      • OBJECT_NAME com o nome do objeto que quer carregar. Para este início rápido, introduza o nome sample_file.txt.

      • OBJECT_PATH com o caminho para o objeto que quer carregar. Para este início rápido, introduza o caminho ~/terraform/sample_file.txt.

    3. Guarde o ficheiro main.tf.

    Inicialize o diretório de trabalho que contém o ficheiro de configuração do Terraform

    Para inicializar o Terraform e o diretório que contém o ficheiro de configuração do Terraform, conclua os passos seguintes:

    1. No terminal, defina a pasta terraform como o diretório de trabalho atual:

      cd ~/terraform
    2. Inicialize o Terraform:

      terraform init
    3. Se estiver a usar a Cloud Shell e lhe for pedido que autorize a Cloud Shell, clique em Autorizar.

      O Terraform inicializa o diretório de trabalho. Se inicializar com êxito o diretório de trabalho, o Terraform devolve uma saída semelhante à seguinte:

      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.
      

    Pré-visualize o plano de execução

    O plano de execução do Terraform baseia-se na configuração do Terraform e indica as alterações que o Terraform planeia fazer à infraestrutura e aos serviços do Cloud Storage.

    Veja o plano de execução do Terraform:

    terraform plan

    Exemplo de saída:

    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.
    

    Aplique as alterações propostas no plano de execução

    Para aplicar as alterações no ficheiro de configuração do Terraform, conclua os seguintes passos:

    1. Aplique as alterações do plano de execução à infraestrutura do Cloud Storage com o seguinte comando. Quando aplica as alterações, o Terraform cria um contentor de armazenamento e carrega sample_file.txt para o contentor.

      terraform apply

      Exemplo de saída:

      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. Escreva yes e prima Enter.

      Se for bem-sucedido, o Terraform devolve um resultado semelhante ao seguinte:

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

    Veja o seu segmento de armazenamento e objeto carregado

    Na Google Cloud consola, aceda à página Recipientes do Cloud Storage.

    Aceda a Recipientes

    É apresentado o novo contentor, que contém o objeto sample_file.txt. Tenha em atenção que o aprovisionamento dos recursos pode demorar alguns minutos após a execução do comando terraform apply.

    Limpe o projeto

    Para evitar incorrer em custos inesperados com os Google Cloud recursos que criou durante este início rápido, conclua os seguintes passos para limpar os recursos:

    1. No terminal, defina a pasta terraform como o diretório de trabalho atual:

      cd ~/terraform
    2. Elimine os recursos do Cloud Storage que criou com base no seu ficheiro de configuração do Terraform:

      terraform destroy
    3. Se for bem-sucedido, o Terraform devolve um resultado semelhante ao seguinte:

      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. Escreva yes e prima Enter. Se for bem-sucedido, o Terraform devolve um resultado semelhante ao seguinte:

      Destroy complete! Resources: 2 destroyed.
      
    5. No terminal, elimine a pasta terraform.

      rm -rf ~/terraform
    6. Para verificar se o contentor e o objeto foram eliminados, aceda à página Contentores na Google Cloud consola.

      Aceda a Recipientes

    O que se segue?