arrow_back

Using Terraform to Create Clients and Servers

로그인 가입
700개 이상의 실습 및 과정 이용하기

Using Terraform to Create Clients and Servers

실습 2시간 universal_currency_alt 크레딧 5개 show_chart 중급
info 이 실습에는 학습을 지원하는 AI 도구가 통합되어 있을 수 있습니다.
700개 이상의 실습 및 과정 이용하기

Overview

In this lab, you provision a Linux virtual machine in a private network to act as a database server. You also create a virtual machine that you can use as a bastion host to connect to the database server as an administrator. You configure the database server for remote connections and add a user account. You then install the MySQL-MariaDB client software to connect to the database server from a client machine.

Objectives

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

  • Create client and server VMs.
  • Administer your database server.
  • Connect to the database from a client.

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. Create client and server VMs

  1. Open a new web browser window and navigate to the Google Cloud Console (console.cloud.google.com). Use the project selector to choose the first project with a leading name of 'qwiklabs-gcp.'

  2. On the Navigation menu (Navigation menu icon), click Cloud overview.

  3. 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 will open in a pane at the bottom of the window.

  2. Activate the Identity-Aware Proxy API which will allow you to connect to all of the Virtual Machines created within this project without configuring SSH keys. Enter the following command in the Cloud Shell:

gcloud services enable iap.googleapis.com
  1. To clone a GitHub repository that includes a completed version of the previous lab, enter the following command:
git clone https://github.com/GoogleCloudPlatform/training-data-analyst
  1. Change to the following folder:
cd ~/training-data-analyst/courses/db-migration/terraform-clients-servers/
  1. Type ls and you see this folder has the Terraform files completed from the last lab.

  2. Click Open Editor, and then from the training-data-analyst/courses/db-migration/terraform-clients-servers/ folder, open the terraform.tfvars file.

  3. Change the values in the terraform.tfvars file as noted below.

Item Value
project_id
gcp_region_1
gcp_zone_1



  1. Create a Debian Linux machine in the private network. Add a file named vm-mysql-server.tf, and paste the following Terraform code into it:
# Create a MySQL Server in Private VPC resource "google_compute_instance" "mysql-server" { name = "mysql-server-${random_id.instance_id.hex}" machine_type = "f1-micro" zone = var.gcp_zone_1 tags = ["allow-ssh", "allow-mysql"] boot_disk { initialize_params { image = "debian-cloud/debian-11" } } network_interface { network = google_compute_network.private-vpc.name subnetwork = google_compute_subnetwork.private-subnet_1.name # access_config { } } } output "mysql-server" { value = google_compute_instance.mysql-server.name } output "mysql-server-external-ip" { value = "NONE" } output "mysql-server-internal-ip" { value = google_compute_instance.mysql-server.network_interface.0.network_ip }
  1. Create a machine in the public network that you can use to administer that server. Add a file named vm-mysql-client.tf, and paste the following Terraform code into it:
# Create MySQL Client in Public VPC resource "google_compute_instance" "mysql-client" { name = "mysql-client-${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" } } network_interface { network = google_compute_network.public-vpc.name subnetwork = google_compute_subnetwork.public-subnet_1.name access_config { } } } output "mysql-client" { value = google_compute_instance.mysql-client.name } output "mysql-client-external-ip" { value = google_compute_instance.mysql-client.network_interface.0.access_config.0.nat_ip } output "mysql-client-internal-ip" { value = google_compute_instance.mysql-client.network_interface.0.network_ip }
  1. Create a firewall rule to allow communication to MySQL Server from the public network. Open the vpc-firewall-rules-private.tf file, and add the following firewall rule to the end:
# allow MySQL only from public subnet resource "google_compute_firewall" "private-allow-mysql" { name = "${google_compute_network.private-vpc.name}-allow-mysql" network = google_compute_network.private-vpc.name allow { protocol = "tcp" ports = ["3306"] } source_ranges = [ "${var.subnet_cidr_public}" ] target_tags = ["allow-mysql"] }
  1. To initialize Terraform and create the plan, return to the Cloud Shell terminal and enter the following commands:
terraform init terraform plan
  1. To create the resources, run the following command:
terraform apply -auto-approve

Click Check my progress to verify the objective. Create client and server VMs

Task 2. Administer your database server

  1. When the Terraform process completes, on the Navigation menu (Navigation menu icon), click Compute Engine. Multiple machines should be listed.

  2. Find the mysql-server- machine, and make note of its internal IP address (it is likely 10.2.2.2 or 10.2.2.3).

  3. Click SSH for the mysql-server- machine to connect to that machine.

Note: At this point, you need to install MySQL on the server. However, because the server has no external IP address, it has no access to the internet, so you can't run the command to install MySQL. You fix that by adding a NAT using the Google Cloud NAT service.
  1. Execute the following command to see that it doesn't work; it eventually fails when trying to access the internet:
sudo apt install wget
  1. The message returned in the terminal will appear as follows:
Could not connect to debian.map...
  1. Type CTRL+C to end the command.

  2. Return to the Cloud Shell Code Editor, and in the training-data-analyst/courses/db-migration/terraform-clients-servers folder, add a file called cloud-nat.tf, and then add the following Terraform code to that file:

resource "google_compute_router" "nat-router" { name = "nat-router" region = google_compute_subnetwork.private-subnet_1.region network = google_compute_network.private-vpc.id bgp { asn = 64514 } } resource "google_compute_router_nat" "private-nat" { name = "private-nat" router = google_compute_router.nat-router.name region = google_compute_router.nat-router.region nat_ip_allocate_option = "AUTO_ONLY" source_subnetwork_ip_ranges_to_nat = "ALL_SUBNETWORKS_ALL_IP_RANGES" log_config { enable = true filter = "ERRORS_ONLY" } }
  1. Return to the Cloud Shell Terminal and run the following command to confirm you have no errors:
terraform plan
  1. Then apply the plan to create the NAT:
terraform apply -auto-approve
  1. Return to your SSH window that is connected to the MySQL Server. Run the following commands to install MySQL:
sudo apt-get update sudo apt-get install -y default-mysql-server
  1. To ensure that MySQL-MariaDB is running, enter the following command:
sudo systemctl status mysql

The output will appear as follows:

mariadb.service - MariaDB 10.5.15 database server Loaded: loaded (/lib/systemd/system/mariadb.service; enabled; vendor preset: enabled) Active: active (running) since Mon 2022-08-01 20:55:10 UTC; 33s ago
  1. Type "q" to exit.

  2. Create a password for the root user with the following command:

sudo mysql_secure_installation

The initial password will be blank.

  1. Follow the instructions to create a password for root using a password you will remember. Select Yes to all the remaining prompts.

  2. Log in to the database using the root account with the following command:

sudo mysql -u root -p
  1. Enter your newly created password when prompted.

You need a user account to log in with from the client machine.

  1. To create a user named dbops with the password password, use the following command:
CREATE USER 'dbops'@'%' IDENTIFIED BY 'password'; GRANT ALL PRIVILEGES ON * . * TO 'dbops'@'%'; FLUSH PRIVILEGES;
  1. Type exit to exit the MySQL client.

By default, the database server only listens for connections on the local machine. A quick fix to the configuration will change that.

  1. Use the following command to open the configuration file in the Nano text editor:
sudo nano /etc/mysql/mariadb.conf.d/50-server.cnf
  1. Find the line bind-address and comment it out adding a "#" to the front of the line:
#bind-address = 127.0.0.1
  1. Type CTRL+X to exit, and answer Y when prompted to save your changes.

  2. To restart the database, enter the following command:

sudo systemctl restart mariadb

Click Check my progress to verify the objective. Administer your database server

  1. Type exit again to leave the server and return to the client VM.

Task 3. Connect to the database from a client

  1. To connect to the MySQL-MariaDB database from your client machine, you must install MySQL-MariaDB client software.

  2. On the Navigation menu (Navigation menu icon), click Compute Engine. Click SSH for the mysql-client- machine to connect to that terminal.

  3. In the new SSH window, enter the following commands to complete the installation:

sudo apt-get update sudo apt-get install -y default-mysql-client
  1. Return to the Navigation menu (Navigation menu icon), click Compute Engine. Find the mysql-server- machine, and make note of its internal IP address (it is likely 10.2.2.2 or 10.2.2.3).

  2. To connect to your database, use the following command (replace SERVERIP with the IP address you just verified):

mysql -h SERVERIP -u dbops -p'password'
  1. Enter "\s" at the MariaDB prompt.

  2. Details will be returned for the Database server.

  3. Type exit to exit the MySQL client.

At this point, there's no database so there's nothing else to do, but you have a complete solution in place. Your database server is in a secure network with no public access. You have a Linux machine in the public network that can be used to administer the database and connect to the machine using the MySQL-MariaDB client software.

Click Check my progress to verify the objective. Connect to the database from a client

  1. Close your SSH session, and then return to the Cloud Shell terminal.

  2. To delete everything you created earlier in the lab, enter the following command:

terraform destroy -auto-approve

Congratulations! You have provisioned a Linux virtual machine in a private network to act as a database server. You also created a virtual machine that you can use as a bastion host to connect to the database server as an administrator. You configured the database server for remote connections and added a user account. You then installed the MySQL client software to connect to the database server from a client machine.

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개만 가능

모든 기존 실습을 종료하고 이 실습을 시작할지 확인하세요.

시크릿 브라우징을 사용하여 실습 실행하기

이 실습을 실행하려면 시크릿 모드 또는 시크릿 브라우저 창을 사용하세요. 개인 계정과 학생 계정 간의 충돌로 개인 계정에 추가 요금이 발생하는 일을 방지해 줍니다.