Caricamento in corso…
Nessun risultato trovato.

Applica le tue competenze nella console Google Cloud

07

Getting Started with Terraform for Google Cloud

Accedi a oltre 700 lab e corsi

Creating a Remote Backend

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

Overview

In this lab, you will create a local backend and then create a Cloud Storage bucket to migrate the state to a remote backend

Objectives

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

  • Create a local backend.
  • Create a Cloud Storage backend.
  • Refresh your Terraform state.

Task 1. Sign in to the Cloud console

For each lab, you get a new Google Cloud project and set of resources for a fixed time at no cost.

  1. Click the Start Lab button. If you need to pay for the lab, a pop-up opens for you to select your payment method. On the left is the Lab Details panel 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 panel.

  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 panel.

  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 view a menu with a list of Google Cloud products and services, click the Navigation menu at the top-left, or type the service or product name in the Search field. Navigation menu icon

Task 2. Verify Terraform is installed

  1. On the Google Cloud menu, click Activate Cloud Shell.

  2. If prompted, click Continue.

  3. Confirm that Terraform is installed by running the following command:

terraform --version

Task 3. Add a local backend

In this section, you will configure a local backend which will then be moved to a Cloud Storage bucket.

  1. In a new Cloud Shell window, create a main.tf configuration file.
touch main.tf
  1. To retrieve your Project ID, run the following command:
gcloud config list --format 'value(core.project)'
  1. On the Cloud Shell toolbar, click Open Editor. To switch between Cloud Shell and the code editor, click Open Editor or Open Terminal as required.
  2. Copy the Cloud Storage bucket resource code into your main.tf configuration file:
provider "google" { project = "{{{project_0.project_id|Project ID}}}" region = "{{{project_0.default_region|Region}}}" } resource "google_storage_bucket" "test-bucket-for-state" { name = "{{{project_0.project_id|Project ID}}}" location = "US" # Replace with EU for Europe region uniform_bucket_level_access = true }
  1. Add a local backend to your main.tf file:
terraform { backend "local" { path = "terraform/state/terraform.tfstate" } }

This will reference a terraform.tfstate file in the terraform/state directory.

The final code in main.tf is as shown below.

provider "google" { project = "{{{project_0.project_id|Project ID}}}" region = "{{{project_0.default_region|Region}}}" } resource "google_storage_bucket" "test-bucket-for-state" { name = "{{{project_0.project_id|Project ID}}}" location = "US" # Replace with EU for Europe region uniform_bucket_level_access = true } terraform { backend "local" { path = "terraform/state/terraform.tfstate" } }

Terraform must initialize any configured backend before use.

  1. On the Cloud Shell toolbar, click Open Terminal, then initialize Terraform using the following command:
terraform init
  1. Apply the changes. Type yes at the prompt to confirm.
terraform apply

The Cloud Shell Editor should now display the state file called terraform.tfstate in the terraform/state directory.

  1. Examine your state file:
terraform show

Your google_storage_bucket.test-bucket-for-state resource should be displayed.

Click Check my progress to verify local backend is created.

Add a local backend

Task 4. Add a Cloud Storage backend

  1. Navigate back to your main.tf file in the editor. You will now replace the current local backend with a gcs backend.
  2. To change the existing local backend configuration, replace the code for local backend with the following configuration in the main.tf file.
terraform { backend "gcs" { bucket = "{{{project_0.project_id|Project ID}}}" prefix = "terraform/state" } }

The final code in main.tf is as shown below:

provider "google" { project = "{{{project_0.project_id|Project ID}}}" region = "{{{project_0.default_region|Region}}}" } resource "google_storage_bucket" "test-bucket-for-state" { name = "{{{project_0.project_id|Project ID}}}" location = "US" # Replace with EU for Europe region uniform_bucket_level_access = true } terraform { backend "gcs" { bucket = "{{{project_0.project_id|Project ID}}}" prefix = "terraform/state" } }
  1. Initialize your backend again. Type yes at the prompt to confirm.
terraform init -migrate-state
  1. In the Google Cloud console, in the Navigation menu, click Cloud Storage and then Buckets.
  2. Click on your bucket and navigate to the file terraform/state/default.tfstate.

Your state file now exists in a Cloud Storage bucket!

remote_backend

Click Check my progress to verify remote backend is created.

Add a Cloud Storage backend

Task 5. Refresh the state

The terraform refresh command is used to reconcile the state Terraform knows about (via its state file) with the real-world infrastructure. This can be used to detect any drift from the last-known state and to update the state file. This does not modify infrastructure, but does modify the state file. If the state is changed, this may cause changes to occur during the next plan or apply.

  1. Return to your storage bucket in the Cloud console. Select the check box next to the name, and click the Labels button on the top. The info panel with Labels tabs will open up.
  2. Click +ADD LABEL. Set the Key2 = key and Value2 = value.
  3. Click Save.
  4. Return to Cloud Shell and use the following command to update the state file:
terraform refresh

Click Check my progress to verify terraform is refreshed.

Refresh the state

Task 6. Clean up the workspace

  1. First, revert your backend to local so you can delete the storage bucket. Copy and replace the gcs configuration with the following:
terraform { backend "local" { path = "terraform/state/terraform.tfstate" } }
  1. Initialize the local backend again. Type yes at the prompt to confirm.
terraform init -migrate-state
  1. In the main.tf file, add the force_destroy = true argument to your google_storage_bucket resource. When you delete a bucket, this boolean option will delete all contained objects.
Note: If you try to delete a bucket that contains objects, Terraform will fail that run.

Your resource configuration should resemble the following:

resource "google_storage_bucket" "test-bucket-for-state" { name = "{{{project_0.project_id|Project ID}}}" location = "US" # Replace with EU for Europe region uniform_bucket_level_access = true force_destroy = true }
  1. Apply the changes. Type yes at the prompt to confirm.
terraform apply
  1. You can now successfully destroy your infrastructure. Type yes at the prompt to confirm.
terraform destroy

Click Check my progress to verify the backend is deleted.

Clean up the workspace

Congratulations!

In this lab, you learned how to manage backends and state with Terraform. You created local and Cloud Storage backends to manage your state file, and also refreshed the state. In this lab, you learned how to perform the following tasks:

  • Create a local backend.
  • Create a Cloud Storage backend.
  • Refresh your Terraform state.

End your lab

When you have completed your lab, click End Lab. Google Cloud Skills Boost removes the resources you’ve used and cleans the account for you.

You will be given an opportunity to rate the lab experience. Select the applicable number of stars, type a comment, and then click Submit.

The number of stars indicates the following:

  • 1 star = Very dissatisfied
  • 2 stars = Dissatisfied
  • 3 stars = Neutral
  • 4 stars = Satisfied
  • 5 stars = Very satisfied

You can close the dialog box if you don't want to provide feedback.

For feedback, suggestions, or corrections, please use the Support tab.

Copyright 2022 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.

Indietro Avanti

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.
Anteprima