How to Create Load Balancer in GCP using Terraform ?
Last Updated :
26 Apr, 2024
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.
Similar Reads
How to Create Storage Bucket in GCP Using Terraform?
In Cloud Computing, it is very crucial to provide efficient storage solutions. Google Cloud Platform (GCP) offers an exemplary service through it's Storage Bucket. Storage Buckets are versatile containers for securely storing data objects while providing scalability, durability, and global accessibi
6 min read
How To Create VPC In GCP Using Terraform ?
When we are building an application to be hosted on a Cloud Platform we must configure networks and take security measures. If you are building an application that is open to users over the internet, you might want to control who gets access or not, and how users interact with each other. This is es
9 min read
How To Create EMR Cluster In AWS Using Terraform ?
In today's data-driven world, big data processing has become an integral part of many organizations' workflows. Amazon EMR (Elastic MapReduce) is a cloud-based platform provided by Amazon Web Services (AWS) that simplifies the process of running and scaling Apache Hadoop and Apache Spark clusters fo
10 min read
How To Create SQS In AWS Using Terraform ?
Amazon Simple Queue Service (SQS) is a completely managed message queuing service provided by AWS, offering scalable and reliable message conveyance between distributed parts of an application. It fills in as a fundamental building block for building event driven, microservice-based models, empoweri
8 min read
How to Create a Load Balancer on GCP?
A load balancer in GCP (Google Cloud Platform) is a service that distributes incoming network traffic across multiple backend resources such as virtual machines (VMs), container instances, and managed instance groups. The main purpose of a load balancer is to improve the availability and scalability
4 min read
How To Create Elastic IP In AWS Using Terraform ?
Using Terraform, creating an Elastic IP (EIP) on AWS entails specifying the resources required in a Terraform configuration file in order to create the EIP. A static IPv4 address intended for dynamic cloud computing is called an elastic IP. It is helpful in situations when you require a public IP ad
4 min read
How to Create AWS EC2 using Terraform?
AWS EC2 (Elastic Compute Cloud) is a web service provided by Amazon Web Services (AWS) that allows users to launch and oversee virtual servers, known as examples, in the cloud. It gives an adaptable and versatile foundation for running different sorts of applications and jobs. With Terraform EC2, cl
13 min read
How To Create AKS Cluster In Azure Using Terraform ?
Azure AKS also called as Azure Kubernetes Service is service that provides Kubernetes implementation in the Azure cloud. Azure Kubernetes service is a managed service that allows deployment of containerized applications in azure cloud. Setting up a Kubernetes cluster in azure is tedious task so lets
4 min read
How To Create Amazon EKS Cluster Using Terraform?
Amazon EKS Cluster allows to building of containerized applications without the overhead of managing, scaling, and deploying. Terraform makes it easy to deploy an EKS cluster to AWS by making it IaaC. By using terraform a template can be created for multiple clusters and their management. Let's see
5 min read
How To Create Key Pair In AWS Using Terraform ?
In cloud infrastructure management, secure admittance to instances is central. While working with Amazon Web Services (AWS) utilizing Terraform, creating key pairs is fundamental for secure access to EC2 instances. Key pairs comprise of a public key and a private key, where the public key is utilize
6 min read