Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Guía de inicio rápido: Crea una instancia de VM con Terraform
En esta guía de inicio rápido, aprenderás a usar Terraform para crear una instancia de máquina virtual (VM)
de Compute Engine y conectarte a esa instancia de VM.
Hashicorp Terraform es una herramienta de infraestructura como código (IaC) que te permite aprovisionar y administrar la infraestructura de nube. El proveedor de Terraform paraGoogle Cloud (proveedor deGoogle Cloud ) te permite aprovisionar y administrar la infraestructura de Google Cloud .
Antes de comenzar
Para usar una terminal en línea con gcloud CLI y Terraform
ya configurados, activa Cloud Shell.
En la parte inferior de esta página, se inicia una sesión de Cloud Shell y
se muestra una instrucción de línea de comandos. La sesión puede tardar unos segundos en inicializarse.
En este archivo, se describe el
recurso google_compute_instance, que es el recurso de Terraform para la
instancia de VM de Compute Engine. google_compute_instance está configurado para
tener las siguientes propiedades:
name se configura como my-vm.
machine_type se configura como n1-standard-1.
zone se configura como us-central1-a.
boot_disk configura el disco de arranque de la instancia.
network_interface está configurado para usar la red predeterminada en tu proyecto deGoogle Cloud .
Crea la instancia de VM de Compute Engine
En Cloud Shell, ejecuta el siguiente comando para verificar que Terraform
esté disponible:
terraform
El resultado debería ser similar al siguiente ejemplo:
Para validar la configuración de Terraform, ejecuta el siguiente comando.
Este comando realiza las siguientes acciones:
Verifica que la sintaxis de main.tf sea correcta.
Muestra una vista previa de los recursos que se crearán.
terraformplan
El resultado debería ser similar al siguiente ejemplo:
Plan:1toadd,0tochange,0todestroy.
Note:Youdidn't use the -out option to save this plan, so Terraform can't
guaranteetotakeexactlytheseactionsifyourun"terraform apply"now.
Aplica la configuración para aprovisionar los recursos descritos en el archivo
main.tf:
terraformapply
Cuando se te solicite, ingresa yes.
Terraform llama a las APIs de Google Cloud para crear la instancia de VM definida en el archivomain.tf.
El resultado debería ser similar al siguiente ejemplo:
Conéctate a la instancia de VM que acabas de crear ejecutando el siguiente comando:
gcloudcomputessh--zone=us-central1-amy-vm
Limpia
Para evitar que se apliquen cargos a tu cuenta de Google Cloud por
los recursos que se usaron en esta página, borra el proyecto de Google Cloud que tiene los
recursos.
En Cloud Shell, ejecuta el siguiente comando para borrar los recursos de
Terraform:
terraformdestroy
Cuando se te solicite, ingresa yes.
El resultado debería ser similar al siguiente ejemplo:
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 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)."]]