Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Guia de início rápido: criar uma instância de VM usando o Terraform
Neste guia de início rápido, você vai aprender a usar o Terraform para criar uma
instância de máquina virtual (VM) e conectar-se a ela.
Hashicorp Terraform é uma ferramenta de infraestrutura como código (IaC, na sigla em inglês) que permite provisionar e gerenciar infraestrutura em nuvem. O provedor do Terraform para
Google Cloud (provedor doGoogle Cloud ) permite provisionar e
gerenciar a infraestrutura do Google Cloud .
Antes de começar
Para usar um terminal on-line com a gcloud CLI e o Terraform já configurados, ative o Cloud Shell:
Na parte de baixo desta página, uma sessão do Cloud Shell é iniciada e exibe um
prompt de linha de comando. A inicialização da sessão pode levar alguns segundos.
Esse arquivo descreve o
recurso google_compute_instance, que é o recurso do Terraform para
instâncias de VM do Compute Engine. google_compute_instance está configurado para
ter as seguintes propriedades:
name, definida como my-vm.
machine_type, definida como n1-standard-1.
zone, definida como us-central1-a.
boot_disk define o disco de inicialização da instância.
network_interface está configurado para usar a rede padrão no seu
projetoGoogle Cloud .
Criar a instância de VM do Compute Engine
No Cloud Shell, execute o seguinte comando para verificar se o Terraform
está disponível:
Valide a configuração do Terraform executando o comando a seguir.
Esse comando realiza as seguintes ações:
verifica se a sintaxe de main.tf está correta;
mostra uma prévia dos recursos que serão criados.
terraformplan
A saída será semelhante a esta:
Plan:1toadd,0tochange,0todestroy.
Note:Youdidn't use the -out option to save this plan, so Terraform can't
guaranteetotakeexactlytheseactionsifyourun"terraform apply"now.
Aplique a configuração para provisionar os recursos descritos no arquivo
main.tf:
terraformapply
Quando solicitado, digite yes.
O Terraform chama as APIs Google Cloud para criar a instância de VM definida no
arquivo main.tf.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-09-04 UTC."],[[["\u003cp\u003eThis quickstart guide demonstrates how to use Hashicorp Terraform, an Infrastructure as Code (IaC) tool, to create and manage a Compute Engine Virtual Machine (VM) instance on Google Cloud.\u003c/p\u003e\n"],["\u003cp\u003eThe process involves setting up a Google Cloud project, enabling the Compute Engine API, granting necessary IAM roles, and preparing a local environment with Terraform installed.\u003c/p\u003e\n"],["\u003cp\u003eA \u003ccode\u003emain.tf\u003c/code\u003e file is used to define the desired VM instance properties, including name, machine type, zone, boot disk, and network interface.\u003c/p\u003e\n"],["\u003cp\u003eTerraform commands, including \u003ccode\u003eterraform init\u003c/code\u003e, \u003ccode\u003eterraform plan\u003c/code\u003e, and \u003ccode\u003eterraform apply\u003c/code\u003e, are utilized to initialize the environment, preview the changes, and provision the VM instance.\u003c/p\u003e\n"],["\u003cp\u003eFinally, the guide shows how to connect to the created VM using \u003ccode\u003egcloud compute ssh\u003c/code\u003e and how to clean up resources using \u003ccode\u003eterraform destroy\u003c/code\u003e.\u003c/p\u003e\n"]]],[],null,["# Quickstart: Create a Compute Engine VM instance using Terraform\n\nQuickstart: Create a VM instance using Terraform\n================================================\n\nIn this quickstart, you learn how to use Terraform to create a Compute Engine\nVirtual Machine (VM) instance and connect to that VM instance.\n\nHashicorp Terraform is an Infrastructure as code (IaC) tool that lets you\nprovision and manage cloud infrastructure. *Terraform provider for\nGoogle Cloud* (*Google Cloud provider*) lets you provision and\nmanage Google Cloud infrastructure.\n\nBefore you begin\n----------------\n\n1. To use an online terminal with the gcloud CLI and Terraform\n already set up, activate Cloud Shell:\n\n At the bottom of this page, a Cloud Shell session starts and\n displays a command-line prompt. It can take a few seconds for the session to\n initialize.\n2. [Create or select a Google Cloud project](https://cloud.google.com/resource-manager/docs/creating-managing-projects).\n\n | **Note**: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.\n - Create a Google Cloud project:\n\n ```\n gcloud projects create PROJECT_ID\n ```\n\n Replace \u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e with a name for the Google Cloud project you are creating.\n - Select the Google Cloud project that you created:\n\n ```\n gcloud config set project PROJECT_ID\n ```\n\n Replace \u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e with your Google Cloud project name.\n3.\n [Verify that billing is enabled for your Google Cloud project](/billing/docs/how-to/verify-billing-enabled#confirm_billing_is_enabled_on_a_project).\n\n4.\n\n\n Enable the Compute Engine API:\n\n\n ```bash\n gcloud services enable compute.googleapis.com\n ```\n5.\n Grant roles to your user account. Run the following command once for each of the following\n IAM roles:\n `roles/compute.instanceAdmin.v1`\n\n ```bash\n gcloud projects add-iam-policy-binding PROJECT_ID --member=\"user:\u003cvar translate=\"no\"\u003eUSER_IDENTIFIER\u003c/var\u003e\" --role=ROLE\n ```\n\n Replace the following:\n - \u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e: your project ID.\n - \u003cvar translate=\"no\"\u003eUSER_IDENTIFIER\u003c/var\u003e: the identifier for your user account. For examples, see [Represent workforce pool users in IAM policies](/iam/docs/workforce-identity-federation#representing-workforce-users).\n - \u003cvar translate=\"no\"\u003eROLE\u003c/var\u003e: the IAM role that you grant to your user account.\n\nPrepare the environment\n-----------------------\n\n1. Clone the GitHub repository containing Terraform samples:\n\n git clone https://github.com/terraform-google-modules/terraform-docs-samples.git --single-branch\n\n2. Go to the directory that contains the quickstart sample:\n\n cd terraform-docs-samples/compute/quickstart/create_vm\n\nReview the Terraform files\n--------------------------\n\nReview the `main.tf` file. This file defines the Google Cloud\nresources that you want to create. \n\n cat main.tf\n\nThe output is similar to the following \n\n resource \"google_compute_instance\" \"default\" {\n name = \"my-vm\"\n machine_type = \"n1-standard-1\"\n zone = \"us-central1-a\"\n\n boot_disk {\n initialize_params {\n image = \"ubuntu-minimal-2210-kinetic-amd64-v20230126\"\n }\n }\n\n network_interface {\n network = \"default\"\n access_config {}\n }\n }\n\nThis file describes the\n[`google_compute_instance` resource](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/compute_instance), which is the Terraform resource for the\nCompute Engine VM instance. `google_compute_instance` is configured to\nhave the following properties:\n\n- `name` is set to `my-vm`.\n- `machine_type` is set to `n1-standard-1`.\n- `zone` is set to `us-central1-a`.\n- `boot_disk` sets the boot disk for the instance.\n- `network_interface` is set to use the default network in your Google Cloud project.\n\nCreate the Compute Engine VM instance\n-------------------------------------\n\n1. In Cloud Shell, run the following command to verify that Terraform\n is available:\n\n terraform\n\n The output should be similar to the following: \n\n\n Usage: terraform [global options] \u003csubcommand\u003e [args]\n\n The available commands for execution are listed below.\n The primary workflow commands are given first, followed by\n less common or more advanced commands.\n\n Main commands:\n init Prepare your working directory for other commands\n validate Check whether the configuration is valid\n plan Show changes required by the current configuration\n apply Create or update infrastructure\n destroy Destroy previously-created infrastructure\n\n2. Initialize Terraform by running the following command. This command prepares\n your workspace so Terraform can apply your configuration.\n\n terraform init\n\n The output should be similar to the following: \n\n\n Initializing the backend...\n\n Initializing provider plugins...\n - Finding latest version of hashicorp/google...\n - Installing hashicorp/google v5.35.0...\n - Installed hashicorp/google v5.35.0 (signed by HashiCorp)\n\n Terraform has created a lock file .terraform.lock.hcl to record the provider\n selections it made above. Include this file in your version control repository\n so that Terraform can guarantee to make the same selections by default when\n you run \"terraform init\" in the future.\n\n Terraform has been successfully initialized!\n\n3. Validate the Terraform configuration by running the following command.\n This command takes the following actions:\n\n - Verifies that the syntax of `main.tf` is correct.\n - Shows a preview of the resources that will be created.\n\n terraform plan\n\n The output should be similar to the following: \n\n Plan: 1 to add, 0 to change, 0 to destroy.\n\n Note: You didn't use the -out option to save this plan, so Terraform can't\n guarantee to take exactly these actions if you run \"terraform apply\" now.\n\n4. Apply the configuration to provision resources described in the `main.tf`\n file:\n\n terraform apply\n\n When prompted, enter `yes`.\n\n Terraform calls Google Cloud APIs to create the VM instance defined in\n the `main.tf` file.\n\n The output should be similar to the following: \n\n Apply complete! Resources: 1 added, 0 changed, 0 destroyed\n\nConnect to the VM instance\n--------------------------\n\nConnect to the VM instance you just created by running the following command: \n\n gcloud compute ssh --zone=us-central1-a my-vm\n\nClean up\n--------\n\n\nTo avoid incurring charges to your Google Cloud account for\nthe resources used on this page, delete the Google Cloud project with the\nresources.\n\nIn Cloud Shell, run the following command to delete the Terraform\nresources: \n\n terraform destroy\n\nWhen prompted, enter `yes`.\n\nThe output should be similar to the following: \n\n Destroy complete! Resources: 1 destroyed.\n\nWhat's next\n-----------\n\n- Learn how to [deploy a basic Flask web server using Terraform](/docs/terraform/deploy-flask-web-server).\n- Learn how to [store Terraform state in a Cloud Storage bucket](/docs/terraform/resource-management/store-state)."]]