Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Guida rapida: crea un'istanza VM utilizzando Terraform
In questa guida rapida, imparerai a utilizzare Terraform per creare un'istanza di macchina virtuale (VM) Compute Engine e a connetterti a questa istanza VM.
Hashicorp Terraform è uno strumento Infrastructure as Code (IaC) che consente
di eseguire il provisioning e di gestire l'infrastruttura cloud. Il provider Terraform per
Google Cloud (providerGoogle Cloud ) consente di eseguire il provisioning e
gestire l'infrastruttura Google Cloud .
Prima di iniziare
Per utilizzare un terminale online con gcloud CLI e Terraform già configurati, attiva Cloud Shell:
Nella parte inferiore di questa pagina viene avviata una sessione di Cloud Shell e viene visualizzato un prompt della riga di comando. L'inizializzazione della sessione può richiedere alcuni secondi.
Questo file descrive la
risorsa google_compute_instance, che è la risorsa Terraform per l'istanza VM di Compute Engine. google_compute_instance è configurato per avere le seguenti proprietà:
name è impostato su my-vm.
machine_type è impostato su n1-standard-1.
zone è impostato su us-central1-a.
boot_disk imposta il disco di avvio per l'istanza.
network_interface è impostato per utilizzare la rete predefinita nel tuo progettoGoogle Cloud .
Crea l'istanza VM di Compute Engine
In Cloud Shell, esegui questo comando per verificare che Terraform
sia disponibile:
Inizializza Terraform eseguendo questo comando. Questo comando prepara
il tuo spazio di lavoro in modo che Terraform possa applicare la configurazione.
Convalida la configurazione di Terraform eseguendo il comando seguente.
Questo comando esegue le seguenti azioni:
Verifica che la sintassi di main.tf sia corretta.
Mostra un'anteprima delle risorse che verranno create.
terraformplan
L'output dovrebbe essere simile al seguente:
Plan:1toadd,0tochange,0todestroy.
Note:Youdidn't use the -out option to save this plan, so Terraform can't
guaranteetotakeexactlytheseactionsifyourun"terraform apply"now.
Applica la configurazione per eseguire il provisioning delle risorse descritte nel file main.tf:
terraformapply
Quando richiesto, inserisci yes.
Terraform chiama le API Google Cloud per creare l'istanza VM definita nel file main.tf.
Connettiti all'istanza VM che hai appena creato eseguendo il seguente comando:
gcloudcomputessh--zone=us-central1-amy-vm
Esegui la pulizia
Per evitare che al tuo account Google Cloud vengano addebitati costi relativi alle risorse utilizzate in questa pagina, elimina il progetto Google Cloud
con le risorse.
In Cloud Shell, esegui questo comando per eliminare le risorse Terraform:
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Difficile da capire","hardToUnderstand","thumb-down"],["Informazioni o codice di esempio errati","incorrectInformationOrSampleCode","thumb-down"],["Mancano le informazioni o gli esempi di cui ho bisogno","missingTheInformationSamplesINeed","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 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)."]]