How to Deploy a CentOS Linux VM Instance in GCP using Terraform
--
In this story, we will learn how to deploy a CentOS Linux VM Instance (VM) in GCP (Google Cloud Platform) using Terraform.
Prerequisite: GCP Credentials
Before creating our GCP VM Instances, we will need GCP Credentials to execute our Terraform code.
Please refer to the “How to Create a Service Account for Terraform in GCP (Google Cloud Platform)” story if you need help to create the credentials.
Note: Using private key .json files are great for learning and testing however they are not recommended in production environments. Never push private keys files to code repositories.
Creating a Terraform file for GCP Authentication
First, we create a file called “provider-variables.tf”, used by the GCP authentication variables, and add the following code to the file.
We will need a GCP Project Name, a GCP Region, and a .JSON file name with the private keys to authenticate to GCP.
# GCP authentication file
variable "gcp_auth_file" {
type = string
description = "GCP authentication file"
}# define GCP region
variable "gcp_region" {
type = string
description = "GCP region"
}# define GCP project name
variable "gcp_project" {
type = string
description = "GCP project name"
}
Then we create the “provider-main.tf” file and add the following code:
The version in the “required_providers” / “google” section is useful to pin a specific version but is not required.
# Define Terraform provider
terraform {
required_version = "~> 1.0" required_providers {
google = {
source = "hashicorp/google"
version = "4.11.0" # pinning version
}
}
}# Define GCP provider
provider "google" {
credentials = file(var.gcp_auth_file)
project = var.gcp_project
region = var.gcp_region
zone = var.gcp_zone
}
Finally, we use Provider in the terraform.tfvars file:
# GCP Settings
gcp_project = "kopicloud-medium"
gcp_region =…