arrow_back

Using Terraform to Create Networks and Firewalls

Anmelden Teilnehmen
Zugriff auf über 700 Labs und Kurse nutzen

Using Terraform to Create Networks and Firewalls

Lab 2 Stunden universal_currency_alt 5 Guthabenpunkte show_chart Mittelstufe
info Dieses Lab kann KI-Tools enthalten, die den Lernprozess unterstützen.
Zugriff auf über 700 Labs und Kurse nutzen

Overview

In this lab, you create a secure network infrastructure for your database migration projects. You create both public and private VPCs with appropriate firewall rules in each. You add virtual machines to each network and test the communication between them. You do all of this using Terraform to demonstrate a more real-world workflow that you can use in your migration projects.

Objectives

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

  • Automate network creation.
  • Create firewall rules.
  • Create virtual machines.
  • Create a private network.

Setup and requirements

In this task, you use Qwiklabs and perform initialization steps for your lab.

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

  1. Sign in to Qwiklabs using an incognito window.

  2. Note the lab's access time (for example, 1:15:00), and make sure you can finish within that time.
    There is no pause feature. You can restart if needed, but you have to start at the beginning.

  3. When ready, click Start lab.

  4. Note your lab credentials (Username and Password). You will use them to sign in to the Google Cloud Console.

  5. Click Open Google Console.

  6. Click Use another account and copy/paste credentials for this lab into the prompts.
    If you use other credentials, you'll receive errors or incur charges.

  7. Accept the terms and skip the recovery resource page.

Task 1. Use Terraform to automate network creation

  1. In the Navigation menu (Navigation menu icon), click Home.

  2. In the Project info section, find your Project ID and copy and paste it into a text file. You will need it later.

The Project ID highlighted in the Project info section

  1. Click the Activate Cloud Shell (Activate Cloud Shell icon) icon in the upper right of the Console. The Cloud Shell terminal opens in a pane at the bottom of the window.

  2. Create a directory called terraform-networks and change to it:

mkdir terraform-networks cd terraform-networks
  1. Create the required Terraform files for this lab:
touch provider.tf touch terraform.tfvars touch test-server-linux.tf touch variables.tf touch vpc-network-public.tf touch vpc-firewall-rules-public.tf touch public-test-server-linux.tf touch random-id-generator.tf
  1. Enter ls to verify that your files were created in the terraform-networks folder.

  2. Click Open Editor in Cloud Shell, and then select the terraform-networks folder and open the provider.tf file.

  3. Enter the following code to configure the Google Cloud Terraform provider:

terraform { required_version = ">= 0.12" } provider "google" { project = var.project_id region = var.gcp_region_1 zone = var.gcp_zone_1 }

Notice the variables in the above code. You create those and some other variables now.

  1. Open the variables.tf file and enter the following code:
# GCP Project ID variable "project_id" { type = string description = "GCP Project ID" } # Region to use for Subnet 1 variable "gcp_region_1" { type = string description = "GCP Region" } # Zone used for VMs variable "gcp_zone_1" { type = string description = "GCP Zone" } # Define subnet for public network variable "subnet_cidr_public" { type = string description = "Subnet CIDR for Public Network" }

You defined the variables in the previous file, and you set the variables in another file.

  1. Open the terraform.tfvars file and add the following code:
# GCP Settings project_id = "{{{project_0.project_id|Project ID}}}" gcp_region_1 = "{{{ project_0.default_region | "REGION" }}}" gcp_zone_1 = "{{{ project_0.default_zone | "ZONE" }}}" # GCP Network Variables subnet_cidr_public = "10.1.1.0/24"
  1. Open the vpc-network-public.tf file and add the following:
resource "google_compute_network" "public-vpc" { name = "public-vpc" auto_create_subnetworks = "false" routing_mode = "GLOBAL" } resource "google_compute_subnetwork" "public-subnet_1" { name = "public-subnet-1" ip_cidr_range = var.subnet_cidr_public network = google_compute_network.public-vpc.name region = var.gcp_region_1 } Note: The above Terraform code creates a VPC with one subnet. In the subnet, notice the two variables for ip_cidr_range and region. Also notice how the network property refers back to the VPC created before the subnet.
  1. To confirm that the procedure has worked up to this point, in the Google Cloud Console, on the Navigation menu (Navigation menu icon), click VPC network. You should have one network named default.

  2. In Cloud Shell, click Open Terminal. Make sure you are in the correct folder:

cd ~/terraform-networks
  1. To initialize Terraform, enter the following command:
terraform init

A message should indicate that "Terraform has been successfully initialized!".

  1. To build the Terraform plan, enter the following command:
terraform plan

Make sure there are no errors and look at what resources will be created.

The plan should tell you that two resources will be created: a network and a subnetwork.

  1. To create the resources, run the following command:
terraform apply -auto-approve

The -auto-approve parameter runs the script without prompting you.

  1. Wait for the script to complete, and then in the Console, click Refresh in the VPC networks toolbar. You see your new network and subnet.

You're not done configuring the network.

  1. Delete what you just created with the following command:
terraform destroy -auto-approve
  1. Click Refresh to verify that the network was deleted.

Click Check my progress to verify the objective. Use Terraform to automate network creation

Review

At this point, you have used Terraform to create a network and subnet. Next, you create some firewall rules.

Task 2. Use Terraform to create firewall rules

  1. In Cloud Shell, click Open Editor. Open the vpc-firewall-rules-public.tf file in the terraform-networks folder.

  2. To add a firewall rule that will allow SSH into machines in this network, add the following code:

# allow ssh resource "google_compute_firewall" "public-allow-ssh" { name = "${google_compute_network.public-vpc.name}-allow-ssh" network = google_compute_network.public-vpc.name allow { protocol = "tcp" ports = ["22"] } source_ranges = [ "0.0.0.0/0" ] target_tags = ["allow-ssh"] } Note: This rule allows SSH from everywhere, but only to machines that have the "allow-ssh" tag.
  1. Windows machines require RDP, not SSH. Add the following RDP rule below the SSH rule:
# allow rdp resource "google_compute_firewall" "public-allow-rdp" { name = "${google_compute_network.public-vpc.name}-allow-rdp" network = google_compute_network.public-vpc.name allow { protocol = "tcp" ports = ["3389"] } source_ranges = [ "0.0.0.0/0" ] target_tags = ["allow-rdp"] }

Ping is useful for testing.

  1. Add the following rule below the previous rules to enable it:
# allow ping only from everywhere resource "google_compute_firewall" "public-allow-ping" { name = "${google_compute_network.public-vpc.name}-allow-ping" network = google_compute_network.public-vpc.name allow { protocol = "icmp" } source_ranges = [ "0.0.0.0/0" ] }
  1. As you did before, switch the terminal and run the following command to check for errors and see what will be created:
terraform plan
  1. Run the following Terraform command and verify that the network, subnet, and firewall rules are all being created using the Console:
terraform apply -auto-approve

Click Check my progress to verify the objective. Use Terraform to create firewall rules

Review

Now you have a network and some firewall rules. Next, you add a test server to the network and see whether the firewall rules work.

Task 3. Use Terraform to create virtual machines

  1. Open the Cloud Shell code editor, and then open the file random-id-generator.tf and add the following code:
# Terraform plugin for creating random ids resource "random_id" "instance_id" { byte_length = 4 }

This Terraform plug-in is used to generate a unique name for VMs added programatically.

  1. To create a virtual machine in the public network, open the test-server-linux.tf file and add the following code:
# Create Test Server in Public VPC resource "google_compute_instance" "test-server-linux" { name = "public-test-server-linux-${random_id.instance_id.hex}" machine_type = "f1-micro" zone = var.gcp_zone_1 tags = ["allow-ssh"] boot_disk { initialize_params { image = "debian-cloud/debian-11" } } metadata_startup_script = "sudo apt-get update;" network_interface { network = google_compute_network.public-vpc.name subnetwork = google_compute_subnetwork.public-subnet_1.name access_config { } } } output "test-server-linux" { value = google_compute_instance.test-server-linux.name } output "test-server-linux-external-ip" { value = google_compute_instance.test-server-linux.network_interface.0.access_config.0.nat_ip } output "test-server-linux-internal-ip" { value = google_compute_instance.test-server-linux.network_interface.0.network_ip } Note: The output variables will return the name and internal and external IP addresses for the machine created. Also, this machine is tagged with the "allow-ssh" tag so you can connect to it.

Lastly, take a look at the code in the network_interface section that configures this machine to be in the public network you created earlier.
  1. Run the Terraform plan and apply commands as you did earlier to create this machine. If an error appears, you may need to run terraform init again before running the other two commands.

When the commands complete, you should see the VM name and internal and external IP addresses.

  1. From the Cloud Shell terminal, make sure you can ping the external IP address of that machine.

  2. In the Console, go to the Compute Engine service to see the VM you just created.

  3. Click SSH to make sure your firewall rule works, and then exit the SSH session.

Click Check my progress to verify the objective. Use Terraform to create virtual machines

Task 4. Use Terraform to create a private network

  1. Use the configuration of the public network as a guide and create a second private network. In the variables.tf file, add a variable for the private subnet IP CIDR range, and set its value in the terraform.tfvars file.

  2. Duplicate the vpc-network-public.tf file and change the names and variables appropriately.

  3. Using the public firewall rules as a guide, add firewall rules for the private network. In the source_ranges section, don't allow traffic from all sources: only allow traffic from the public subnet IP CIDR range.

  4. Create a test server in the private network, using the public one as a guide.

Note: Try to complete this lab on your own. If you get stuck, there is a complete solution in GitHub at the following URL: GoogleCloudPlatform/training-data-analyst.
  1. When you have everything created, try to SSH into the public test server. The server in the private network won't be accessible yet. You will fix that in the next lab.

Congratulations! You have created a secure network infrastructure for your database migration projects. You created both public and private VPCs with appropriate firewall rules in each. You added virtual machines to each network and tested the communication between them. You did all of this using Terraform.

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.

Vorbereitung

  1. Labs erstellen ein Google Cloud-Projekt und Ressourcen für einen bestimmten Zeitraum
  2. Labs haben ein Zeitlimit und keine Pausenfunktion. Wenn Sie das Lab beenden, müssen Sie von vorne beginnen.
  3. Klicken Sie links oben auf dem Bildschirm auf Lab starten, um zu beginnen

Privates Surfen verwenden

  1. Kopieren Sie den bereitgestellten Nutzernamen und das Passwort für das Lab
  2. Klicken Sie im privaten Modus auf Konsole öffnen

In der Konsole anmelden

  1. Melden Sie sich mit Ihren Lab-Anmeldedaten an. Wenn Sie andere Anmeldedaten verwenden, kann dies zu Fehlern führen oder es fallen Kosten an.
  2. Akzeptieren Sie die Nutzungsbedingungen und überspringen Sie die Seite zur Wiederherstellung der Ressourcen
  3. Klicken Sie erst auf Lab beenden, wenn Sie das Lab abgeschlossen haben oder es neu starten möchten. Andernfalls werden Ihre bisherige Arbeit und das Projekt gelöscht.

Diese Inhalte sind derzeit nicht verfügbar

Bei Verfügbarkeit des Labs benachrichtigen wir Sie per E-Mail

Sehr gut!

Bei Verfügbarkeit kontaktieren wir Sie per E-Mail

Es ist immer nur ein Lab möglich

Bestätigen Sie, dass Sie alle vorhandenen Labs beenden und dieses Lab starten möchten

Privates Surfen für das Lab verwenden

Nutzen Sie den privaten oder Inkognitomodus, um dieses Lab durchzuführen. So wird verhindert, dass es zu Konflikten zwischen Ihrem persönlichen Konto und dem Teilnehmerkonto kommt und zusätzliche Gebühren für Ihr persönliches Konto erhoben werden.