Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Guide de démarrage rapide : créer une instance de VM à l'aide de Terraform
Dans ce guide de démarrage rapide, vous allez apprendre à utiliser Terraform pour créer une instance de machine virtuelle (VM) Compute Engine et à vous y connecter.
HashiCorp Terraform est un outil IaC (Infrastructure as Code) qui vous permet de provisionner et de gérer l'infrastructure cloud. Le fournisseur Terraform pourGoogle Cloud (fournisseurGoogle Cloud ) vous permet de provisionner et de gérer l'infrastructure Google Cloud .
Avant de commencer
Pour utiliser un terminal en ligne avec la gcloud CLI et Terraform déjà configurés, activez Cloud Shell :
En bas de la page, une session Cloud Shell démarre et affiche une invite de ligne de commande. L'initialisation de la session peut prendre quelques secondes.
Ce fichier décrit la ressource google_compute_instance, qui est la ressource Terraform pour l'instance de VM Compute Engine. google_compute_instance est configuré pour avoir les propriétés suivantes :
La propriété name est définie sur my-vm.
La propriété machine_type est définie sur n1-standard-1.
La propriété zone est définie sur us-central1-a.
boot_disk définit le disque de démarrage de l'instance.
network_interface est configuré pour utiliser le réseau par défaut dans votre projetGoogle Cloud .
Créer l'instance de VM Compute Engine
Dans Cloud Shell, exécutez la commande suivante pour vérifier que Terraform est disponible :
Initialisez Terraform à l'aide de la commande suivante. Cette commande prépare votre espace de travail pour que Terraform puisse appliquer votre configuration.
Validez la configuration Terraform en exécutant la commande suivante.
Cette commande effectue les actions suivantes :
Vérifie que la syntaxe de main.tf est correcte
Affiche un aperçu des ressources qui seront créées
terraformplan
La sortie devrait ressembler à ce qui suit :
Plan:1toadd,0tochange,0todestroy.
Note:Youdidn't use the -out option to save this plan, so Terraform can't
guaranteetotakeexactlytheseactionsifyourun"terraform apply"now.
Appliquez la configuration pour provisionner les ressources décrites dans le fichier main.tf :
terraformapply
Lorsque vous y êtes invité, saisissez yes.
Terraform appelle les API Google Cloud pour créer l'instance de VM définie dans le fichiermain.tf.
Connectez-vous à l'instance de VM que vous venez de créer en exécutant la commande suivante :
gcloudcomputessh--zone=us-central1-amy-vm
Effectuer un nettoyage
Pour éviter que les ressources utilisées dans cette démonstration soient facturées sur votre compte Google Cloud , supprimez le projet Google Cloud qui les contient.
Dans Cloud Shell, exécutez la commande suivante pour supprimer les ressources Terraform :
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/09/04 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 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)."]]