arrow_back

HTTPS Content-Based Load Balancer with Terraform

Accedi Partecipa
Accedi a oltre 700 lab e corsi

HTTPS Content-Based Load Balancer with Terraform

Lab 1 ora universal_currency_alt 5 crediti show_chart Intermedio
info Questo lab potrebbe incorporare strumenti di AI a supporto del tuo apprendimento.
Accedi a oltre 700 lab e corsi

GSP206

Google Cloud self-paced labs logo

Overview

In this lab, you create an HTTPS load balancer to forward traffic to a custom URL map. The URL map sends traffic to the region closest to you with static assets being served from a Cloud Storage bucket. The TLS key and certificate is generated by Terraform using the TLS provider.

The following is a diagram of the architecture you create as part of this lab:

The Terraform Architecture, including the Cloud Load Balancing, three instances, and Cloud Storage.

Objectives

In this lab, you learn how to perform the following tasks:

  • Explore the load balancing modules for Terraform.
  • Configure Terraform in the Google Cloud environment.
  • Create a global HTTPS content-based load balancer.

Setup and requirements

Before you click the Start Lab button

Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources are made available to you.

This hands-on lab lets you do the lab activities in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials you use to sign in and access Google Cloud for the duration of the lab.

To complete this lab, you need:

  • Access to a standard internet browser (Chrome browser recommended).
Note: Use an Incognito (recommended) or private browser window to run this lab. This prevents conflicts between your personal account and the student account, which may cause extra charges incurred to your personal account.
  • Time to complete the lab—remember, once you start, you cannot pause a lab.
Note: Use only the student account for this lab. If you use a different Google Cloud account, you may incur charges to that account.

How to start your lab and sign in to the Google Cloud console

  1. Click the Start Lab button. If you need to pay for the lab, a dialog opens for you to select your payment method. On the left is the Lab Details pane with the following:

    • The Open Google Cloud console button
    • Time remaining
    • The temporary credentials that you must use for this lab
    • Other information, if needed, to step through this lab
  2. Click Open Google Cloud console (or right-click and select Open Link in Incognito Window if you are running the Chrome browser).

    The lab spins up resources, and then opens another tab that shows the Sign in page.

    Tip: Arrange the tabs in separate windows, side-by-side.

    Note: If you see the Choose an account dialog, click Use Another Account.
  3. If necessary, copy the Username below and paste it into the Sign in dialog.

    {{{user_0.username | "Username"}}}

    You can also find the Username in the Lab Details pane.

  4. Click Next.

  5. Copy the Password below and paste it into the Welcome dialog.

    {{{user_0.password | "Password"}}}

    You can also find the Password in the Lab Details pane.

  6. Click Next.

    Important: You must use the credentials the lab provides you. Do not use your Google Cloud account credentials. Note: Using your own Google Cloud account for this lab may incur extra charges.
  7. Click through the subsequent pages:

    • Accept the terms and conditions.
    • Do not add recovery options or two-factor authentication (because this is a temporary account).
    • Do not sign up for free trials.

After a few moments, the Google Cloud console opens in this tab.

Note: To access Google Cloud products and services, click the Navigation menu or type the service or product name in the Search field. Navigation menu icon and Search field

Activate Cloud Shell

Cloud Shell is a virtual machine that is loaded with development tools. It offers a persistent 5GB home directory and runs on the Google Cloud. Cloud Shell provides command-line access to your Google Cloud resources.

  1. Click Activate Cloud Shell Activate Cloud Shell icon at the top of the Google Cloud console.

  2. Click through the following windows:

    • Continue through the Cloud Shell information window.
    • Authorize Cloud Shell to use your credentials to make Google Cloud API calls.

When you are connected, you are already authenticated, and the project is set to your Project_ID, . The output contains a line that declares the Project_ID for this session:

Your Cloud Platform project in this session is set to {{{project_0.project_id | "PROJECT_ID"}}}

gcloud is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion.

  1. (Optional) You can list the active account name with this command:
gcloud auth list
  1. Click Authorize.

Output:

ACTIVE: * ACCOUNT: {{{user_0.username | "ACCOUNT"}}} To set the active account, run: $ gcloud config set account `ACCOUNT`
  1. (Optional) You can list the project ID with this command:
gcloud config list project

Output:

[core] project = {{{project_0.project_id | "PROJECT_ID"}}} Note: For full documentation of gcloud, in Google Cloud, refer to the gcloud CLI overview guide.

Task 1. Clone the sample repository

Enable Gemini Code Assist in the Cloud Shell IDE

You can use Gemini Code Assist in an integrated development environment (IDE) such as Cloud Shell to receive guidance on code or solve problems with your code. Before you can start using Gemini Code Assist, however, you need to enable it.

  1. In Cloud Shell, enable the Gemini for Google Cloud API with the following command:
gcloud services enable cloudaicompanion.googleapis.com
  1. Click Open Editor on the Cloud Shell toolbar.
Note: To open the Cloud Shell Editor, click Open Editor on the Cloud Shell toolbar. You can switch between Cloud Shell and the code Editor by clicking Open Editor or Open Terminal, as required.
  1. In the Cloud Shell Editor, navigate to Cloud Code > Help and Feedback > Change Settings.

  2. In the Settings, search for Gemini Code Assist.

  3. Locate and ensure that the checkbox is selected for Geminicodeassist: Enable, and close the Settings.

  4. Click Cloud Code - No Project in the status bar at the bottom of the screen.

  5. Authorize the plugin as instructed. If a project is not automatically selected, click Select a Google Cloud Project, and choose .

  6. Verify that your Google Cloud project () displays in the Cloud Code status message in the status bar.

Clone the repository and update the files

  1. In the Cloud Shell terminal, clone the terraform-google-lb-http repository:
git clone https://github.com/terraform-google-modules/terraform-google-lb-http.git
  1. Navigate to the multi-backend-multi-mig-bucket-https-lb directory:
cd ~/terraform-google-lb-http/examples/multi-backend-multi-mig-bucket-https-lb
  1. On the Cloud Shell toolbar, click the Open Editor icon.

To help you be more productive while minimizing context switching, Gemini Code Assist provides AI-powered smart actions directly in your code editor. In this section, you decide to use Gemini Code Assist to help you modify some resources with Terraform.

  1. In the Cloud Shell Editor's file Explorer, navigate to terraform-google-lb-http > examples > multi-backend-multi-mig-bucket-https-lb > main.tf.

  2. Open the main.tf configuration file. This action enables Gemini Code Assist, as indicated by the presence of the Gemini Code Assist: Smart Actions icon in the upper-right corner of the editor.

  3. Click the Gemini Code Assist: Smart Actions Gemini Code Assist icon on the toolbar.

You want to add the arguments create_ssl_certificate and managed_ssl_certificate_domains to your gce-lb-https module in the configuration file main.tf.

  1. To update the main.tf configuration file, paste the following prompt into the Gemini Code Assist inline text field that opens from the toolbar.
In the main.tf configuration file, update the "gce-lb-https" module. Add the following arguments without altering other values: * create_ssl_certificate = true * managed_ssl_certificate_domains = ["example.com"]
  1. To prompt Gemini Code Assist to modify the code accordingly, press ENTER.

  2. When prompted in the Gemini Diff view, click Accept.

The updated arguments for the "gce-lb-https" module in the main.tf configuration file now looks something like this:

... create_url_map = false ssl = true create_ssl_certificate = true managed_ssl_certificate_domains = ["example.com"] private_key = tls_private_key.example.private_key_pem certificate = tls_self_signed_cert.example.cert_pem backends = { ...
  1. In the Cloud Shell Editor, still in the same directory, navigate to variables.tf. As before, notice the Gemini Code Assist: Smart Actions icon in the upper-right corner of the editor.

  2. Click the Gemini Code Assist: Smart Actions Gemini Code Assist icon on the toolbar.

  3. To update the region definitions in the variables.tf file, paste the following prompt into the Gemini Code Assist inline text field that opens from the toolbar.

Update the region definitions in the variables.tf file to meet the following requirements: * For the group1_region variable, set the "default" argument to {{{project_0.default_region | region 1}}}. * For the group2_region variable, set the "default" argument to {{{project_0.default_region_2 | region 2}}}. * For the group3_region variable, set the "default" argument to {{{project_0.default_region_3 | region 3}}}.
  1. To prompt Gemini to modify the code accordingly, press ENTER.

  2. When prompted in the Gemini Diff view, click Accept.

The updated region definitions in the variable blocks in the file variables.tf now look as follows:

variable "group1_region" { default = "{{{project_0.default_region | region 1}}}" } variable "group2_region" { default = "{{{project_0.default_region_2 | region 2}}}" } variable "group3_region" { default = "{{{project_0.default_region_3 | region 3}}}" } variable "network_name" { default = "ml-bk-ml-mig-bkt-s-lb" } variable "project" { type = string }
  1. When you have finished editing this line, remember to Save this updated file by selecting the File option in the Code Editor and clicking Save.

Task 2. Run Terraform

Initialize a working directory

The terraform init command is used to initialize a working directory containing Terraform configuration files. This command performs several different initialization steps to prepare a working directory for use. This command is always safe to run multiple times, to bring the working directory up to date with changes in the configuration.

  • Run the command:
terraform init

Example output:

... Terraform has been successfully initialized!

Create an execution plan

The terraform plan command is used to create an execution plan. Terraform performs a refresh, unless explicitly disabled, and then determines what actions are necessary to achieve the desired state specified in the configuration files.

This command is a convenient way to check whether the execution plan for a set of changes matches your expectations without making any changes to real resources or the state. For example, terraform plan might be run before committing a change to version control, to create confidence that it will behave as expected.

  1. Run the following command to create an execution plan:
terraform plan -out=tfplan -var 'project={{{project_0.project_id | Project ID}}}'

Example output:

... Plan: 43 to add, 0 to change, 0 to destroy.

The optional -out argument can be used to save the generated plan to a file for later execution with terraform apply.

  1. Run the following command to list out the current directory content:
ls

Example output:

diagram.png gceme.sh.tpl gcp-logo.svg main.tf mig.tf outputs.tf README.md test.sh tfplan tls.tf variables.tf

Take note of the saved Terraform plan (tfplan).

Apply the changes

The terraform apply command is used to apply the changes required to reach the desired state of the configuration, or the pre-determined set of actions generated by a terraform plan execution plan.

  1. Run the following command to apply the Terraform plan:
terraform apply tfplan

Example output (yours will differ):

... Apply complete! Resources: 43 added, 0 changed, 0 destroyed. ... Outputs: asset-url = https://34.96.112.153/assets/gcp-logo.svg group1_region = us-west1 group2_region = us-central1 group3_region = us-east1 load-balancer-ip = 34.96.112.153

Verify the resources created by Terraform:

  1. In the Cloud console, from the Navigation menu (Navigation menu) click View All Products > Network services > Load Balancing.

  2. Wait until you see the green checkmark in the Backends column.

  3. Click on the ml-bk-ml-mig-bkt-s-lb load balancer and check its details.

Load Balancer Frontend listing the available details, including the various protocols, hosts, and path rules.

Load Balancer Backend listing the backend services and buckets, each include items such as Type, Zone, and Capacity.

  1. Run the following to get the external URL:
EXTERNAL_IP=$(terraform output | grep load-balancer-ip | cut -d = -f2 | xargs echo -n) echo https://${EXTERNAL_IP}
  1. Click on the EXTERNAL_IP link that is returned to open the load balancer URL in a new browser tab. It takes a few minutes to load.
Note: If you don't get the expected output in the browser, make sure your load balancer details panel is the same as an above screenshot and wait for a few minutes. Note: If you get a privacy error, click on Advanced and then proceed.

You should see the Google Cloud logo and instance details from the group closest to your geographical region.

Google Cloud instance details such as Name, Zone, Machine Type, and Internal IP.

Click Check my progress to verify the objective. Apply the changes in Terraform

  1. Now append the URL with group1, group2 and group3.

Your final URLs should look as follows (make sure to replace EXTERNAL_IP with your load balancer IP): https://EXTERNAL_IP/group1.

  • For group1: You should see the Google Cloud logo and instance details from the group in .

https://EXTERNAL_IP/group2

  • For group2: You should see the Google Cloud logo and instance details from the group in

https://EXTERNAL_IP/group3

  • For group3: You should see the Google Cloud logo and instance details from the group in

Congratulations!

In this lab, you learned how to configure load balancing modules in Terraform in conjunction with Gemini Code Assist. You then used the modules to create a global HTTPS Content-Based Load Balancer, and used it to test its response to the group closest to your geographical region.

Next steps / Learn more

Google Cloud training and certification

...helps you make the most of Google Cloud technologies. Our classes include technical skills and best practices to help you get up to speed quickly and continue your learning journey. We offer fundamental to advanced level training, with on-demand, live, and virtual options to suit your busy schedule. Certifications help you validate and prove your skill and expertise in Google Cloud technologies.

Manual Last Updated September 2, 2025

Lab Last Tested September 2, 2025

Copyright 2025 Google LLC. All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.

Prima di iniziare

  1. I lab creano un progetto e risorse Google Cloud per un periodo di tempo prestabilito
  2. I lab hanno un limite di tempo e non possono essere messi in pausa. Se termini il lab, dovrai ricominciare dall'inizio.
  3. In alto a sinistra dello schermo, fai clic su Inizia il lab per iniziare

Utilizza la navigazione privata

  1. Copia il nome utente e la password forniti per il lab
  2. Fai clic su Apri console in modalità privata

Accedi alla console

  1. Accedi utilizzando le tue credenziali del lab. L'utilizzo di altre credenziali potrebbe causare errori oppure l'addebito di costi.
  2. Accetta i termini e salta la pagina di ripristino delle risorse
  3. Non fare clic su Termina lab a meno che tu non abbia terminato il lab o non voglia riavviarlo, perché il tuo lavoro verrà eliminato e il progetto verrà rimosso

Questi contenuti non sono al momento disponibili

Ti invieremo una notifica via email quando sarà disponibile

Bene.

Ti contatteremo via email non appena sarà disponibile

Un lab alla volta

Conferma per terminare tutti i lab esistenti e iniziare questo

Utilizza la navigazione privata per eseguire il lab

Utilizza una finestra del browser in incognito o privata per eseguire questo lab. In questo modo eviterai eventuali conflitti tra il tuo account personale e l'account Studente, che potrebbero causare addebiti aggiuntivi sul tuo account personale.