How to Create Load Balancer in GCP using Terraform ?

As traffic controls, load balancers on the Google Cloud Platform (GCP) distribute incoming requests among multiple instances of your application. Consider them as traffic engineers that direct customers to the busiest locations to deliver a dependable and responsive service, especially during periods of great demand or when certain points of interest have problems. Here you’ll find comprehensive instructions for using Terraform to generate load balancers in GCP.

Step By Steps to create the load balancer in GCP using Terraform

First, we need to install Terraform. For more detailed information, refer to this link.
Step 1: Service Account Setup

  • Open Google Cloud Console.
  • Go to IAM & Admin > Service accounts.
  • Click “Create Service Account” and fill in the details.
  • Grant Storage Admin, Compute Admin, and Service Account User roles.

Step 2: Generate Key

  • Select the service account.
  • Under “Keys,” click “Add Key.”
  • Choose JSON key type and click “Create.”
  • Save the generated key file securely on your local machine.

Step 3: Create Load Balancer Using Terraform

  • Configure your Terraform file using the necessary provider and login information.
  • Name and describe the resources of the load balancer, including target pools, firewall rules, instance groups, health checks, and instance templates.
  • Use the terraform init, terraform plan, and terraform apply commands to initialize Terraform, preview the changes, and apply the configuration, in that order.

Code continioun for the above code.

Step 4: Terraform Code

  • Terraform Block: This block specifies the required provider and its version.
  • Provider Block: The project ID, region, and Google Cloud provider with authentication credentials are defined here, along with the load balancer’s deployment location.
  • Forwarding Rule Resource: This resource specifies the IP protocol, target pool, load balancing scheme, and forwarding rule for the load balancer.
  • Target Pool Resource: It specifies the load balancer’s target pool, which contains a list of instance groups to which traffic should be routed.
  • HTTP Health Check Resource: To keep track of the state of the instances in the target pool, this page configures an HTTP health check.
  • Instance Group Resource: It specifies the zone and designated port for the load balancer instance group.
  • Instance Template Resource: The machine type, disk configuration, and network interface are all specified in this resource, which also provides the template for instances in the instance group.
  • Firewall Rule Resource: It creates a firewall rule to let inbound traffic reach the load balancer on port 80.
terraform {
required_providers {
google = {
source = "hashicorp/google"
version = "5.25.0"
}
}
}

provider "google" {
credentials = file("C:/Users/GFG0429/Desktop/Prasad/Loadbalancer/cred.json")
project = "gcp-demo-project-413710"
region = "us-central1" # Specify the region for the load balancer
}

resource "google_compute_forwarding_rule" "lb_frontend" {
name = "lb-frontend"
target = google_compute_target_pool.lb_target_pool.self_link
port_range = "80"
ip_protocol = "TCP"
load_balancing_scheme = "EXTERNAL"
}

resource "google_compute_target_pool" "lb_target_pool" {
name = "lb-target-pool"

health_checks = [google_compute_http_health_check.lb_health_check.self_link]
}

resource "google_compute_http_health_check" "lb_health_check" {
name = "lb-health-check"
check_interval_sec = 1
timeout_sec = 1
healthy_threshold = 1
unhealthy_threshold = 2
port = 80
request_path = "/healthz"
}

resource "google_compute_instance_group" "instance_group" {
name = "instance-group"
zone = "us-central1-a"
description = "Instance group for load balancing"
named_port {
name = "http"
port = 80
}
}

resource "google_compute_instance_template" "lb_instance_template" {
name = "lb-instance-template"
description = "Instance template for load balancer instances"
machine_type = "n1-standard-1" # Specify the machine type for the instances

disk {
source_image = "ubuntu-2004-focal-v20240209"
disk_size_gb = 10
disk_type = "pd-standard"
}

network_interface {
network = "default"
}
}

resource "google_compute_firewall" "lb_firewall" {
name = "lb-firewall"
network = "default"

allow {
protocol = "tcp"
ports = ["80"]
}

source_ranges = ["0.0.0.0/0"]
}

Step 5: Create the resurces using the terraform apply commabnd as shown image below. As per the below image and code six resources created.

Step 7: Here is the load balancer created in the GCP. Refer the below image.

Step 8: Here is the loadbalacer ip in the GCP console.

Step 9: Terminate the terraform resoures using the below command. For your referrance refer the below image.

terraform destroy

Conclusion

Creating a load balancer in Google Cloud Platform (GCP) using Terraform offers a seamless and efficient way to distribute incoming traffic across multiple instances of your application. By following the step-by-step guide outlined above, you can ensure that your application remains highly available, responsive, and reliable, even during periods of high demand or individual instance failures. Leveraging Terraform for infrastructure as code enables you to automate the deployment and management of your load balancer resources, resulting in improved scalability, consistency, and maintainability of your GCP environment.

Create Load Balancer in GCP using Terraform – FAQs

How do you make a load balancer in Terraform?

To create a load balancer in Terraform, you define the load balancer configuration using Terraform’s Google Cloud provider and specify resources such as forwarding rules, target pools, health checks, and instance groups. Finally, you apply the Terraform configuration to provision the load balancer in your Google Cloud Platform (GCP) environment.

What is Terraform for GCP?

Terraform for Google Cloud Platform (GCP) is an infrastructure as code tool that allows users to define and provision GCP resources using declarative configuration files. It enables automation, scalability, and consistency in managing infrastructure on GCP.

Is load balancing automatic?

Yes, load balancing in modern cloud environments like Google Cloud Platform (GCP) often includes automatic features such as health checks and dynamic scaling, which adjust traffic distribution based on instance availability and performance, making it effectively automatic in operation.