Guía de inicio rápido: crear 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 ella.
HashiCorp Terraform es una herramienta de infraestructura como código (IaC) que te permite aprovisionar y gestionar la infraestructura en la nube. El proveedor de Terraform para Google Cloud (proveedorGoogle Cloud ) te permite aprovisionar y gestionar Google Cloud infraestructura.
Antes de empezar
Para usar un terminal online con la CLI de gcloud 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 un mensaje de la línea de comandos. La sesión puede tardar unos segundos en inicializarse.
-
Create or select 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 theresourcemanager.projects.create
permission. Learn how to grant roles.
-
Create a Google Cloud project:
gcloud projects create PROJECT_ID
Replace
PROJECT_ID
with a name for the Google Cloud project you are creating. -
Select the Google Cloud project that you created:
gcloud config set project PROJECT_ID
Replace
PROJECT_ID
with your Google Cloud project name.
-
Verify that billing is enabled for your Google Cloud project.
-
Enable the Compute Engine API:
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin
), which contains theserviceusage.services.enable
permission. Learn how to grant roles.gcloud services enable compute.googleapis.com
-
Grant roles to your user account. Run the following command once for each of the following IAM roles:
roles/compute.instanceAdmin.v1
gcloud projects add-iam-policy-binding PROJECT_ID --member="user:USER_IDENTIFIER" --role=ROLE
Replace the following:
PROJECT_ID
: your project ID.USER_IDENTIFIER
: the identifier for your user account. For examples, see Represent workforce pool users in IAM policies.ROLE
: the IAM role that you grant to your user account.
Preparar el entorno
Clona el repositorio de GitHub que contiene ejemplos de Terraform:
git clone https://github.com/terraform-google-modules/terraform-docs-samples.git --single-branch
Ve al directorio que contiene el ejemplo de inicio rápido:
cd terraform-docs-samples/compute/quickstart/create_vm
Revisar los archivos de Terraform
Revisa el archivo main.tf
. Este archivo define los Google Cloud
recursos que quieres crear.
cat main.tf
La salida es similar a la siguiente:
En este archivo se describe el recurso google_compute_instance
, que es el recurso de Terraform de la instancia de VM de Compute Engine. google_compute_instance
se configura para que tenga las siguientes propiedades:
- La opción
name
está configurada comomy-vm
. - La opción
machine_type
está configurada comon1-standard-1
. - La opción
zone
está configurada comous-central1-a
. boot_disk
define el disco de arranque de la instancia.network_interface
se ha configurado para usar la red predeterminada de tuGoogle Cloud proyecto.
Crear la instancia de VM de Compute Engine
En Cloud Shell, ejecuta el siguiente comando para verificar que Terraform está disponible:
terraform
La salida debería ser similar a la siguiente:
Usage: terraform [global options] <subcommand> [args] The available commands for execution are listed below. The primary workflow commands are given first, followed by less common or more advanced commands. Main commands: init Prepare your working directory for other commands validate Check whether the configuration is valid plan Show changes required by the current configuration apply Create or update infrastructure destroy Destroy previously-created infrastructure
Inicializa Terraform ejecutando el siguiente comando. Este comando prepara tu espacio de trabajo para que Terraform pueda aplicar tu configuración.
terraform init
La salida debería ser similar a la siguiente:
Initializing the backend... Initializing provider plugins... - Finding latest version of hashicorp/google... - Installing hashicorp/google v5.35.0... - Installed hashicorp/google v5.35.0 (signed by HashiCorp) Terraform has created a lock file .terraform.lock.hcl to record the provider selections it made above. Include this file in your version control repository so that Terraform can guarantee to make the same selections by default when you run "terraform init" in the future. Terraform has been successfully initialized!
Valida la configuración de Terraform ejecutando 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 van a crear.
terraform plan
La salida debería ser similar a la siguiente:
Plan: 1 to add, 0 to change, 0 to destroy. Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these actions if you run "terraform apply" now.
- Verifica que la sintaxis de
Aplica la configuración para aprovisionar los recursos descritos en el archivo
main.tf
:terraform apply
Cuando se te solicite, introduce
yes
.Terraform llama a las APIs para crear la instancia de VM definida en el archivo
main.tf
. Google CloudLa salida debería ser similar a la siguiente:
Apply complete! Resources: 1 added, 0 changed, 0 destroyed
Conectarse a la instancia de VM
Conéctate a la instancia de VM que acabas de crear ejecutando el siguiente comando:
gcloud compute ssh --zone=us-central1-a my-vm
Limpieza
Para evitar que se apliquen cargos en tu Google Cloud cuenta por los recursos utilizados en esta página, elimina el Google Cloud proyecto con los recursos.
En Cloud Shell, ejecuta el siguiente comando para eliminar los recursos de Terraform:
terraform destroy
Cuando se te solicite, introduce yes
.
La salida debería ser similar a la siguiente:
Destroy complete! Resources: 1 destroyed.
Siguientes pasos
- Consulta cómo desplegar un servidor web Flask básico con Terraform.
- Consulta cómo almacenar el estado de Terraform en un segmento de Cloud Storage.