Google Compute Engine VM Provisioning with Terraform

Terraform brings infrastructure as code to Google Cloud Compute Engine, allowing you to describe a VM instance in a declarative configuration file and have the Terraform provider for Google Cloud create and manage that resource through the Compute Engine API. The workflow is consistent across the quickstart for creating a VM instance using Terraform and the module ecosystem built around google_compute_instance and google_compute_instance_template.

The quickstart teaches how to use Terraform to create a Compute Engine Virtual Machine instance and connect to that VM instance. HashiCorp Terraform is an Infrastructure as code tool that lets you provision and manage cloud infrastructure. Terraform provider for Google Cloud lets you provision and manage Google Cloud infrastructure.

Prerequisites and Cloud Shell Setup

Before you begin work with Terraform and Compute Engine, you need access to a Google Cloud project and a working Terraform installation.

To use an online terminal with the gcloud CLI and Terraform already set up, activate Cloud Shell. At the bottom of the page, a Cloud Shell session starts and displays a command-line prompt. It can take a few seconds for the session to initialize.

Roles required to select or create a project are relevant for project setup.

  • Selecting a project does not require a specific IAM role. You can select any project that you have been granted a role on.
  • Creating a project requires the Project Creator role roles/resourcemanager.projectCreator, which contains the resourcemanager.projects.create permission.

Create a Google Cloud project with the command:

gcloud projects create PROJECT_ID

Replace PROJECT_ID with a name for the Google Cloud project you are creating.

Understanding googlecomputeinstance Resource

This file defines the Google Cloud resources that you want to create.

The file main.tf describes the google_compute_instance resource, which is the Terraform resource for the Compute Engine VM instance.

google_compute_instance is configured to have the following properties:

  • name is set to my-vm
  • machine_type is set to n1-standard-1
  • zone is set to us-central1-a
  • boot_disk sets the boot disk for the instance
  • network_interface is set to use the default network in your Google Cloud project

The resource definition captures the essential identity and placement of a VM. The name identifies the instance within the project and zone. The machine type controls the compute capacity. The zone pins the instance to a specific location. Boot disk and network interface provide storage and connectivity.

Terraform Workflow for VM Creation

HashiCorp Terraform is an infrastructure-as-code tool that lets you provision and manage cloud infrastructure. Terraform provides plugins called providers that let you interact with cloud providers and other APIs. You can use the Terraform provider for Google Cloud to provision and manage Google Cloud resources, including Compute Engine.

Terraform has a declarative and configuration-oriented syntax, which you can use to describe the infrastructure that you want to provision in your Google Cloud project. After you author this configuration in one or more Terraform configuration files, you can use the Terraform CLI to apply this configuration to your Compute Engine resources.

How Terraform works is summarized in the following steps:

  • You describe the infrastructure you want to provision in a Terraform configuration file. You do not need to write code describing how to provision the infrastructure. Terraform provisions the infrastructure for you.
  • You run the terraform plan command, which evaluates your configuration and generates an execution plan. You can review the plan and make changes as needed

The CLI commands that drive the lifecycle are:

terraform init terraform validate terraform plan terraform apply terraform destroy

The available commands for execution are listed when you run terraform with no arguments. 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

Verifying and Initializing Terraform

Create the Compute Engine VM instance.

In Cloud Shell, run the following command to verify that Terraform is available:

terraform

The output should be similar to the following:

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

Initialize Terraform by running the following command. This command prepares your workspace so Terraform can apply your configuration.

terraform init

The output should be similar to the following:

Initializing the backend... Initializing provider plugins... - Finding latest version of hashicorp/google..

Planning and Applying Configuration

This command takes the following actions:

  • Verifies that the syntax of main.tf is correct.
  • Shows a preview of the resources that will be created.

terraform plan

The output should be similar to the following:

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.

Apply the configuration to provision resources described in the main.tf file:

terraform apply

When prompted, enter yes.

Terraform calls Google Cloud APIs to create the VM instance defined in the main.tf file.

The output should be similar to the following:

Apply complete! Resources: 1 added, 0 changed, 0 destroyed

Connecting and Cleaning Up

Connect to the VM instance you just created by running the following command:

gcloud compute ssh --zone=us-central1-a my-vm

Clean up to avoid incurring charges to your Google Cloud account for the resources used.

In Cloud Shell, run the following command to delete the Terraform resources:

terraform destroy

When prompted, enter yes.

The output should be similar to the following:

Destroy complete! Resources: 1 destroyed.

To avoid incurring charges to your Google Cloud account for the resources used on this page, delete the Google Cloud project with the resources.

Using Terraform Modules for Compute Instances

Modules and blueprints help you automate provisioning and managing of Google Cloud resources at scale.

A module is a reusable set of Terraform configuration files that creates a logical abstraction of Terraform resources. A blueprint is a package of deployable and reusable modules, and a policy that implements and documents a specific solution.

This module is used to create compute instances using google_compute_instance_from_template, with no instance groups.

The module is used to create compute instances and only compute instances using google_compute_instance_from_template, with no instance groups.

Key input parameters for the compute instance module are:

Name Description Type Default Required
access_config Access configurations, i.e. IPs via which the VM instance can be accessed via the Internet. list(object({ [] no
addhostnamesuffix Adds a suffix to the hostname bool true no
aliasipranges Optional An array of alias IP ranges for this network interface. Can only be specified for network interfaces on subnet-mode networks. list(object({ [] no
deletion_protection Enable deletion protection on this instance. Note: you must disable deletion protection before removing the resource, or the instance cannot be deleted and the Terraform run will not complete successfully. bool false no
hostname Hostname of instances string "" no
hostnamesuffixseparator Separator character to compose hostname when addhostnamesuffix is set to true. string "-" no
instance_template Instance template self_link used to create compute instances string n/a yes
ipv6accessconfig IPv6 access configurations. Currently a max of 1 IPv6 access configuration is supported. If not specified, the instance will have no external IPv6 Internet access

The module focuses on instance creation from a template without managing instance groups, giving direct control over individual VM properties while reusing a common template definition.

Instance Template Submodule

This submodule allows you to create a google_compute_instance_template resource, which is used as the basis for the other instance, managed, and unmanaged instance groups submodules.

Key input parameters for the instance template submodule are:

Name Description Type Default Required
access_config Access configurations, i.e. IPs via which the VM instance can be accessed via the Internet. list(object({ [] no
additional_disks List of maps of additional disks. See documentation list(object({ [] no
additional_networks Additional network interface details for GCE, if any. list(object({ [] no
additionalnetworksstr Additional network interface details for GCE provided as a JSON-encoded string. Expected format: '[{"network":"vpc-1","subnetwork":"sub-1"}]' string "[]" no
aliasiprange An array of alias IP ranges for this network interface. Can only be specified for network interfaces on subnet-mode networks. ipcidrrange: The IP CIDR range represented by this alias IP range. This IP CIDR range must belong to the specified subnetwork and cannot contain IP addresses reserved by system or used by other network interfaces.

Instance templates provide a reusable blueprint for VMs. They decouple the definition of machine type, disks, network interfaces, and metadata from the actual instance creation, enabling consistent scaling and updates.

Modules and Blueprints Overview

The following table lists modules and blueprints related to Compute Engine:

Module or blueprint Details
terraform-google-vm Collection of opinionated submodules that you can use as building blocks to provision VMs in Google Cloud.
terraform-google-startup-scripts Provides a library of useful startup scripts to embed in VMs.
terraform-google-container-vm Deploys containers on Compute Engine instances

These building blocks support different operational patterns. The terraform-google-vm collection contains opinionated submodules for provisioning VMs. Startup scripts modules allow embedding initialization logic. Container VM modules enable container deployment directly on Compute Engine instances.

What's next for working with Terraform and Compute Engine includes:

  • Terraform code samples for Compute Engine
  • Terraform on Google Cloud documentation
  • Google Cloud provider documentation in HashiCorp
  • Infrastructure as code for Google Cloud

Conclusion

Provisioning Google Compute Engine instances with Terraform combines declarative configuration with provider-driven API interaction. The google_compute_instance resource captures the core identity of a VM with properties such as name, machinetype, zone, bootdisk, and network_interface. The Terraform CLI workflow of init, plan, apply, and destroy gives visibility and control before any cloud resources are created.

The quickstart demonstrates a minimal path from a main.tf file defining my-vm as n1-standard-1 in us-central1-a to connecting via gcloud compute ssh and cleaning up with terraform destroy. For production use, the Terraform module ecosystem provides reusable abstractions. The compute instance module creates VMs from a template via google_compute_instance_from_template with parameters like instance_template, deletion_protection, hostname, and access_config. The instance template submodule centralizes definition of google_compute_instance_template with options for additional_disks, additional_networks, access_config, and alias IP ranges.

Modules and blueprints scale this approach. Terraform modules abstract resources into reusable building blocks, while blueprints package modules with policy for repeatable solutions. The terraform-google-vm, terraform-google-startup-scripts, and terraform-google-container-vm modules illustrate how the community builds on core resources to cover VM provisioning, startup automation, and container workloads.

Using Terraform with Compute Engine lets teams describe desired infrastructure once, review changes with terraform plan, and apply them consistently across projects. The combination of direct resource definitions and modular abstractions supports both one-off VM creation and large-scale fleet management with governance and repeatability.

Sources

  1. docs.cloud.google.com/docs/terraform/create-vm-instance
  2. github.com/terraform-google-modules/terraform-google-vm/blob/master/modules/compute_instance/README.md
  3. github.com/terraform-google-modules/terraform-google-vm/blob/master/modules/instance_template/README.md
  4. docs.cloud.google.com/compute/docs/terraform

Related Posts