arrow_back

Using Terraform to Create Networks and Firewalls

ログイン 参加
700 以上のラボとコースにアクセス

Using Terraform to Create Networks and Firewalls

ラボ 2時間 universal_currency_alt クレジット: 5 show_chart 中級
info このラボでは、学習をサポートする AI ツールが組み込まれている場合があります。
700 以上のラボとコースにアクセス

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.

始める前に

  1. ラボでは、Google Cloud プロジェクトとリソースを一定の時間利用します
  2. ラボには時間制限があり、一時停止機能はありません。ラボを終了した場合は、最初からやり直す必要があります。
  3. 画面左上の [ラボを開始] をクリックして開始します

シークレット ブラウジングを使用する

  1. ラボで使用するユーザー名パスワードをコピーします
  2. プライベート モードで [コンソールを開く] をクリックします

コンソールにログインする

    ラボの認証情報を使用して
  1. ログインします。他の認証情報を使用すると、エラーが発生したり、料金が発生したりする可能性があります。
  2. 利用規約に同意し、再設定用のリソースページをスキップします
  3. ラボを終了する場合や最初からやり直す場合を除き、[ラボを終了] はクリックしないでください。クリックすると、作業内容がクリアされ、プロジェクトが削除されます

このコンテンツは現在ご利用いただけません

利用可能になりましたら、メールでお知らせいたします

ありがとうございます。

利用可能になりましたら、メールでご連絡いたします

1 回に 1 つのラボ

既存のラボをすべて終了して、このラボを開始することを確認してください

シークレット ブラウジングを使用してラボを実行する

このラボの実行には、シークレット モードまたはシークレット ブラウジング ウィンドウを使用してください。これにより、個人アカウントと受講者アカウントの競合を防ぎ、個人アカウントに追加料金が発生することを防ぎます。