Creating a virtual machine with Terraform in GCP

Tech Lead & Architect | 13+ Years in Cloud, Backend, and AI - Experienced software engineer with expertise in Java, Spring Boot, Microservices, Angular, React, Kafka, DevOps, Python, PySpark, Databricks, and Generative AI. Certified in TOGAF, AWS, and Google Cloud. Passionate about building scalable, secure, and high-performance systems. Enthusiast in Data Engineering & Agentic AI. Author of 1,200+ technical articles sharing insights across diverse tech stacks.
Date: 2023-02-24
Creating Virtual Machines in Google Cloud Platform with Terraform: A Comprehensive Guide
This article explores the process of provisioning a virtual machine (VM) in Google Cloud Platform (GCP) using Terraform, a powerful infrastructure-as-code tool. We will delve into the fundamental concepts of Terraform, its role in managing cloud infrastructure, and the step-by-step process of creating a GCP VM using Terraform scripts. No programming expertise is assumed; the focus will remain on the conceptual understanding of the process.
Terraform: A Foundation for Infrastructure Management
Terraform, developed by HashiCorp, is an open-source tool that revolutionizes how we manage and provision cloud infrastructure. Instead of manually configuring cloud resources through web interfaces, Terraform allows you to define your infrastructure using declarative configuration files. This means you describe the desired state of your infrastructure – the types of resources, their configurations, and their interconnections – and Terraform handles the process of creating, modifying, and deleting these resources to match your specification. It supports a wide range of cloud providers, including GCP, Amazon Web Services (AWS), and Microsoft Azure, as well as various on-premises solutions. This consistency makes it easier to manage infrastructure across multiple platforms. It manages both low-level components, such as compute instances, storage, and networking, and higher-level components like SaaS applications and DNS configurations. The key benefit is that it allows for version control, automation, and repeatable deployments, significantly reducing the risk of human error and increasing efficiency.
Setting Up the Environment: Prerequisites and Tools
Before embarking on the VM creation process, certain prerequisites need to be met. Firstly, you'll need to have the Google Cloud SDK (Software Development Kit) installed and configured on your local machine. The SDK provides the necessary tools for interacting with GCP. Crucially, you need to be logged into a GCP account with appropriate permissions to create and manage resources. The tutorial assumes this step has already been completed. Secondly, a suitable text editor or Integrated Development Environment (IDE) is required for writing and editing Terraform configuration files. The original tutorial mentions using Visual Studio Code as a preferred choice. While the choice of editor is largely a matter of personal preference, ensuring it supports syntax highlighting for Terraform files is beneficial for readability and error detection.
Terraform Configuration Files: Defining the Infrastructure
Terraform uses configuration files written in a HashiCorp Configuration Language (HCL) to define the desired infrastructure. These files describe the resources to be created and their attributes. In this context, we’ll focus on two key files: provider.tf and main.tf.
The provider.tf file specifies the cloud provider – in this case, Google Cloud Platform. This file contains details necessary for Terraform to communicate with GCP, including the project ID, region, and zone where the VM will reside. The specific details, such as project ID, would be added here; however, for security reasons, these details have been omitted from the example. The region and zone specify the geographical location of your virtual machine, influencing factors like latency and pricing.
The main.tf file contains the core configuration for the VM and related resources. Here, the instructions would detail the creation of several crucial components. First, it defines two firewall rules – one for SSH access and another for webserver traffic. These firewall rules control which inbound and outbound network traffic is allowed to reach the virtual machine, adding a layer of security. The specific ports opened in these rules would be defined within this file. Next, it defines the parameters for the VM itself, specifying the machine type (e.g., e2-micro), which dictates the VM's computational resources. Other configurable parameters would include operating system image, boot disk size, and any custom metadata. This file also includes commands to create and attach persistent disks for storage beyond the boot disk's capacity, enhancing the storage options available to the VM. The configuration would ensure the VM receives a publicly accessible external IP address, which will be displayed as output once the deployment completes. Although the example utilizes a simplified configuration, the actual file would allow for more detailed customization, such as specifying instance labels, custom scripts for initial VM setup and many other details.
Deploying the Infrastructure: Terraform Commands
Once the Terraform configuration files are ready, the infrastructure can be deployed using a sequence of Terraform commands. The process involves three main steps.
First, the terraform init command initializes the Terraform working directory. This command downloads the necessary plugins, which are specific modules that handle interactions with the targeted cloud provider, in this instance GCP. This ensures Terraform can correctly communicate with the cloud environment.
Second, the terraform plan command creates an execution plan, outlining the changes Terraform will make to the infrastructure. This is a crucial step for verification, allowing you to review exactly what resources will be created or modified before making any actual changes. This prevents accidental deployments of unintended configurations.
Third, the terraform apply command executes the plan, creating the resources in GCP. This command takes the configuration, communicates with the GCP API, and provisions the necessary resources, namely the VM instance, firewall rules, and any associated network configurations. After successful completion, the publicly accessible external IP address of the newly created VM will be displayed as output.
Deleting Resources: Terraform Destroy
After verifying the VM’s functionality, it's essential to remove the created resources to avoid incurring unnecessary costs. This is done using the terraform destroy command. This command safely removes all the resources created by Terraform, reversing the effects of the terraform apply command. This step is as crucial as the deployment, preventing unnecessary costs from unmanaged resources.
Conclusion
This article has detailed the process of creating a virtual machine in Google Cloud Platform using Terraform. While the focus has been on conceptual understanding, the process involves defining the infrastructure's desired state in configuration files and using Terraform commands to manage the deployment and deletion of resources. The power of Terraform lies in its ability to automate, version, and repeatably deploy infrastructure, making it an indispensable tool for cloud management. By mastering Terraform, you gain control and efficiency in managing your cloud resources, reducing human errors, and streamlining your workflow.