PSA를 실행하는 기존 Cloud SQL 인스턴스에서 Private Service Connect 사용 설정하기 (Terraform)

1. 개요

다른 프로젝트 또는 VPC 네트워크에서 비공개 Cloud SQL 인스턴스에 연결하는 방법에는 여러 가지가 있습니다. 비공개 서비스 액세스 (PSA)를 사용하여 비공개 연결을 통해 Google 및 서드 파티 서비스의 내부 IP 주소에 연결할 수 있습니다. 이제 데이터베이스에 대한 액세스를 확장하기 위해 Private Service Connect (PSC)를 사용 설정할 수도 있습니다.

Private Service Connect (PSC)를 사용하면 서비스 제작자가 서비스 연결을 통해 서비스를 노출할 수 있습니다. 소비자는 이 연결을 사용하여 환경에서 PSC 엔드포인트 또는 PSC 백엔드를 만들 수 있습니다. 이러한 PSC 엔드포인트를 통해 사용자 지정 비공개 IP를 통해 프로듀서 서비스에 연결할 수 있습니다.

이 실습에서는 이 옵션을 구성하고 테스트할 수 있습니다.

이 실습에서는 CloudSQL에서 PSA 및 PSC 엔드포인트 액세스를 사용하는 방법을 보여주는 간단한 아키텍처를 빌드합니다.

그림 1.

e0e0f83704cc9d62.png

이 실습에서는 프로젝트 2개 또는 동일한 프로젝트의 별도 VPC가 필요합니다.

목표

이 실습에서는 다음 작업을 실행하는 방법을 알아봅니다.

  • 서비스 네트워킹 사용 설정
  • PSA 설정
  • PSA로 CloudSQL 인스턴스 만들기
  • PSC 서비스 연결을 사용 설정합니다.
  • CloudSQL 데이터베이스에 연결할 PSC 엔드포인트를 소비자 VPC에 만듭니다.
  • 생산자 VPC와 소비자 VPC 모두에서 테스트 VM의 SQL 데이터베이스 액세스 권한 확인

2. 설정 및 요구사항

자습형 환경 설정

  1. Google Cloud Console에 로그인하여 새 프로젝트를 만들거나 기존 프로젝트를 재사용합니다. 아직 Gmail이나 Google Workspace 계정이 없는 경우 계정을 만들어야 합니다.

fbef9caa1602edd0.png

a99b7ace416376c4.png

5e3ff691252acf41.png

  • 프로젝트 이름은 이 프로젝트 참가자의 표시 이름입니다. 이는 Google API에서 사용하지 않는 문자열이며 언제든지 업데이트할 수 있습니다.
  • 프로젝트 ID는 모든 Google Cloud 프로젝트에서 고유하며, 변경할 수 없습니다(설정된 후에는 변경할 수 없음). Cloud 콘솔은 고유한 문자열을 자동으로 생성합니다. 일반적으로는 신경 쓰지 않아도 됩니다. 대부분의 Codelab에서는 프로젝트 ID (일반적으로 PROJECT_ID로 식별됨)를 참조해야 합니다. 생성된 ID가 마음에 들지 않으면 다른 임의 ID를 생성할 수 있습니다. 또는 직접 시도해 보고 사용 가능한지 확인할 수도 있습니다. 이 단계 이후에는 변경할 수 없으며 프로젝트 기간 동안 유지됩니다.
  • 참고로 세 번째 값은 일부 API에서 사용하는 프로젝트 번호입니다. 이 세 가지 값에 대한 자세한 내용은 문서를 참고하세요.
  1. 다음으로 Cloud 리소스/API를 사용하려면 Cloud 콘솔에서 결제를 사용 설정해야 합니다. 이 Codelab 실행에는 많은 비용이 들지 않습니다. 이 튜토리얼이 끝난 후에 요금이 청구되지 않도록 리소스를 종료하려면 만든 리소스 또는 프로젝트를 삭제하면 됩니다. Google Cloud 신규 사용자는 300달러(USD) 상당의 무료 체험판 프로그램에 참여할 수 있습니다.

Cloud Shell 시작

Google Cloud를 노트북에서 원격으로 실행할 수 있지만, 이 Codelab에서는 Cloud에서 실행되는 명령줄 환경인 Google Cloud Shell을 사용합니다.

Google Cloud Console의 오른쪽 상단 툴바에 있는 Cloud Shell 아이콘을 클릭합니다.

55efc1aaa7a4d3ad.png

환경을 프로비저닝하고 연결하는 데 몇 분 정도 소요됩니다. 완료되면 다음과 같이 표시됩니다.

7ffe5cbb04455448.png

가상 머신에는 필요한 개발 도구가 모두 들어있습니다. 영구적인 5GB 홈 디렉터리를 제공하고 Google Cloud에서 실행되므로 네트워크 성능과 인증이 크게 개선됩니다. 이 Codelab의 모든 작업은 브라우저 내에서 수행할 수 있습니다. 아무것도 설치할 필요가 없습니다.

3. 작업 1. (Terraform)을 사용하여 데이터베이스 프로젝트의 환경 설정

데이터베이스 프로젝트에서 서비스 네트워킹을 사용 설정하고, VPC를 만들고, PSA 범위를 만들고, 서비스 네트워킹 피어링을 만들고, 방화벽 규칙을 만듭니다. Cloud 콘솔을 열고 데이터베이스에 사용할 프로젝트를 선택합니다.

  1. 콘솔 오른쪽 상단에 있는 Cloud Shell을 열고 Cloud Shell에 데이터베이스 프로젝트의 데이터베이스 프로젝트 ID가 표시되는지 확인한 다음 액세스를 허용하라는 메시지가 표시되면 확인합니다. 4261e776f64ea978.png
  2. terraform-db-psc라는 폴더를 만들고 해당 폴더로 이동합니다.
mkdir terraform-db-psc  && cd terraform-db-psc
  1. main.tf, variable.tf, nat-vm.tf, database.tf 파일을 만듭니다.
touch main.tf variable.tf nat-vm.tf database.tf 
  1. Cloud Shell 편집기 뷰로 전환합니다. 편집기를 선택하고 인터페이스를 로드할 수 있도록 필요한 프롬프트를 허용합니다.
  2. 로드되면 File > Open Folder로 이동하여 /home/your-user-name/terraform-db-psc로 이동하고 Ok를 선택하여 편집기에서 폴더를 엽니다. 78f5eb9f2f82f1b0.png
  3. variable.tf 파일을 선택하고 다음을 추가합니다. your-database-project-id-here 텍스트를 실제 데이터베이스 프로젝트 ID(따옴표 포함)로 바꿉니다. your-consumer-project-id-here 텍스트를 실제 소비자 프로젝트 ID(따옴표 포함)로 바꿉니다.
variable "project_id" {
  type = string
  default = "your-database-project-id-here"
}

variable "project_id_consumer" {
  type = set(string)
  default = ["your-consumer-project-id-here"]
}

variable "network_id" {
  type = string
  default = "database-net"
}

variable "region_id" {
  type = string
  default = "us-east1"
}

variable "db_password" {
  type = string
  default = "cloudsql24"
}
  1. 그런 다음 main.tf 파일을 엽니다. 아래에 설명된 대로 다양한 작업을 실행하는 terraform 코드를 추가합니다.

API 사용 설정

resource "google_project_service" "default"

VPC 만들기

resource "google_compute_network" "default"

방화벽 규칙 추가

resource "google_compute_firewall" "allow_icmp"

PSA 범위 만들기

resource "google_compute_global_address" "psa_range"

피어링 만들기

resource "google_service_networking_connection" "private_connection"

  1. 다음을 복사하여 main .tf 파일에 붙여넣습니다.
resource "google_project_service" "default" {
 for_each = toset([
   "compute.googleapis.com",
   "servicenetworking.googleapis.com", 
   "sqladmin.googleapis.com",
   "cloudresourcemanager.googleapis.com"
 ])

 service            = each.value
 disable_on_destroy = false
}

resource "google_compute_network" "default" {
 project                = var.project_id
 name                    = var.network_id
 auto_create_subnetworks = true
 mtu                     = 1460
 routing_mode            = "GLOBAL"
}

resource "google_compute_global_address" "psa_range" {
  name                  = "psa-range-${google_compute_network.default.name}"
  project               = var.project_id
  purpose               = "VPC_PEERING"
  address_type          = "INTERNAL"
  prefix_length         = 20
  address               = "172.18.0.0"
  network               = google_compute_network.default.id

}

resource "google_service_networking_connection" "private_connection" {
  network = google_compute_network.default.self_link
  service = "servicenetworking.googleapis.com"

  reserved_peering_ranges = [
    google_compute_global_address.psa_range.name,
  ]
}

resource "google_compute_firewall" "allow_icmp" {
 name    = "allow-icmp-${google_compute_network.default.name}"
 network = google_compute_network.default.id
 project = var.project_id

 allow {
   protocol = "icmp"
 }

 source_ranges = ["0.0.0.0/0"]
 target_tags   = ["allow-icmp"]
}

resource "google_compute_firewall" "allow_ssh" {
 name    = "allow-ssh-${google_compute_network.default.name}"
 network = google_compute_network.default.id
 project = var.project_id

 allow {
   protocol = "tcp"
   ports    = ["22"]
 }

 source_ranges = ["0.0.0.0/0"]
 target_tags   = ["allow-ssh"]
}

resource "google_compute_firewall" "allow_sql" {
 name    = "allow-sql-${google_compute_network.default.name}"
 network = google_compute_network.default.id
 project = var.project_id

 allow {
   protocol = "tcp"
   ports    = ["3306"]
 }

 source_ranges = ["0.0.0.0/0"]
}

resource "google_compute_firewall" "allow_internal" {
 name    = "allow-internal-${google_compute_network.default.name}"
 network = google_compute_network.default.id
 project = var.project_id

 allow {
   protocol = "icmp"
 }

 allow {
   protocol = "tcp"
   ports    = ["0-65535"]
 }
 allow {
   protocol = "udp"
   ports    = ["0-65535"]
 }

 source_ranges = ["10.128.0.0/9", "172.18.0.0/20"] # Include PSA range
}
  1. Cloud Shell 터미널로 다시 전환하고 terraform-db-psc 디렉터리 cd terraform-db-psc에 있는지 확인한 다음 다음 명령어를 실행합니다.

terraform init

작업 디렉터리를 초기화합니다. 이 단계에서는 지정된 구성에 필요한 제공자를 다운로드합니다.

terraform plan

Terraform이 인프라를 배포하기 위해 취할 작업을 보여주는 실행 계획을 생성합니다.

  1. 이제 리소스를 만들려면 terraform apply 명령어를 실행하고 yes를 입력하여 실행합니다.

4. 작업 2. PSA (Terraform)로 CloudSQL 인스턴스 만들기

Terraform을 사용하여 연결을 허용하는 PSA 옵션이 있는 CloudSQL 인스턴스를 만들어 보겠습니다. 데이터베이스 프로젝트에서 이 구성을 완료합니다.

  1. Cloud Shell 편집기 뷰로 전환합니다. 현재 위치가 terraform-db-psc 폴더인지 확인합니다. database.tf 파일을 선택하고 다음을 추가합니다.
resource "google_sql_database_instance" "default" {
  name             = "psc-psa-sql-db"
  region           = var.region_id
  database_version = "MYSQL_8_0"  
  settings {
    tier              = "db-f1-micro"
    availability_type = "REGIONAL"
    backup_configuration {
      enabled            = true
      binary_log_enabled = true
    }
    ip_configuration {      
      ipv4_enabled    = "false"
      private_network = google_compute_network.default.id
      
    }
  }
  deletion_protection = false 
}

resource "google_sql_user" "users" {
  name     = "testsql"
  instance = google_sql_database_instance.default.name
  password = var.db_password 
}

  1. Cloud Shell 터미널로 다시 전환하고 terraform-db-psc 디렉터리에 있는지 확인합니다. 이제 리소스를 만들려면 terraform apply 명령어를 실행하고 yes를 입력하여 실행합니다. PSA를 사용하여 CloudSQL 인스턴스를 만드는 데 최대 15분이 걸릴 수 있습니다.

데이터베이스 확인

  1. 완료되면 콘솔에서 SQL로 이동하여 새로 만든 psc-psa-sql-db 데이터베이스 인스턴스를 선택합니다.
  2. 왼쪽에서 SQL 옵션 슬라이드아웃을 펼치고 연결을 선택합니다.
  3. 요약 탭에서 연결에 관한 정보를 확인할 수 있습니다.
  4. 내부 IP 주소를 복사하여 시스템의 다른 위치에 저장합니다. 보시다시피 예약된 범위에서 할당되었습니다.
  5. 작업 3 단계 5를 완료하려면 이 IP가 필요합니다.

5c00f08b0f44c957.png

  1. 왼쪽에서 SQL 옵션 슬라이드아웃을 펼치고 사용자를 선택합니다.
  2. 비밀번호가 cloudsql24testsql이라는 사용자 이름이 표시됩니다. 이 사용자 이름은 나중에 DB에 액세스하는 데 사용됩니다.

5. 작업 3. 테스트 VM을 만들고 db 프로젝트 내에서 SQL 인스턴스에 연결 (Terraform)

Terraform을 사용하여 테스트 VM과 NAT 게이트웨이를 만들어 보겠습니다. 데이터베이스 프로젝트에서 이 구성을 완료합니다.

  1. Cloud Shell 편집기 뷰로 전환합니다. 현재 위치가 terraform-db-psc 폴더인지 확인합니다. nat-vm.tf 파일을 선택하고 다음을 추가합니다.
resource "google_compute_router" "default" {
  name    = "outbound-nat"
  region  = var.region_id
  network = google_compute_network.default.id

 bgp {
  asn = 64514
  }
}

resource "google_compute_router_nat" "default" {
  name = "outbound-nat-gw"
  router = google_compute_router.default.name
  region = google_compute_router.default.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"
  }
}


resource "google_compute_instance" "sql_net_vm" {
  name         = "db-vm-test"
  machine_type = "e2-medium"
  zone         = "${var.region_id}-b"
  project      = var.project_id

  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-11"
    }
  }

  network_interface {
    network = google_compute_network.default.self_link
  }

  # No external IP address
  network_performance_config {
    total_egress_bandwidth_tier = "DEFAULT"
  }

  tags = ["allow-icmp", "allow-ssh", "allow-internal", "allow-health-check"]

  # Install MariaDB at startup
  metadata_startup_script = <<EOF
#!/bin/bash
apt-get update
apt-get install -y mariadb-server
systemctl enable mariadb
EOF
}
  1. Cloud Shell 터미널로 다시 전환하여 terraform-db-psc 디렉터리에 있는지 확인합니다. 이제 리소스를 만들려면 terraform plan, then terraform apply 명령어를 실행하고 yes를 입력하여 실행합니다. 그러면 MariaDB가 설치된 NAT 게이트웨이와 VM이 생성됩니다.

데이터베이스 확인

소비자 프로젝트에서 완료

  1. VM 인스턴스로 이동합니다. db-vm-test를 선택합니다.
  2. SSH 옵션을 선택하여 VM에 연결합니다.
  3. 다음을 사용하여 이전에 복사한 로컬 IP를 통해 DB에 연결합니다.
mysql --host=172.18.0.2 --user=testsql --password=cloudsql24

참고: 연결하려면 IP 주소를 실제 IP로 변경하세요.

  1. 연결이 설정되면 다음 localvpcsqldb를 사용하여 데이터베이스를 만듭니다.
CREATE DATABASE localvpcsqldb;
  1. 완료되면 exit를 입력하여 연결을 종료합니다. exit를 다시 입력하여 VM을 닫습니다.

6. 작업 4. CloudSQL 인스턴스에 PSC 사용 설정

gcloud 명령어를 사용하여 연결을 허용하는 PSC 옵션을 사용 설정해 보겠습니다. 데이터베이스 프로젝트에서 이 구성을 완료합니다.

  1. Cloud Shell 뷰로 전환합니다.
  2. Cloud Shell에서 다음 명령어를 실행합니다.
  • YOUR_DB_PROJECT_HERE를 데이터베이스 프로젝트 ID로 바꿉니다.
  • YOUR_CONSUMER_PROJECT_HERE를 소비자 프로젝트 ID로 바꿉니다.
project_id=YOUR_DB_PROJECT_HERE
allowed_project=YOUR_CONSUMER_PROJECT_HERE

gcloud beta sql instances patch psc-psa-sql-db \
--project=$project_id \
--enable-private-service-connect \
--allowed-psc-projects=$allowed_project
  1. 이렇게 하면 기존 데이터베이스가 PSC 첨부파일로 업데이트됩니다. 10분 이상 걸립니다.

대기 시간 초과 오류가 발생하면 진행 상황을 계속 확인할 수 있는 명령어도 표시됩니다. '`gcloud beta sql operations wait –project를 실행하여 작업을 계속 기다릴 수 있습니다.'와 같은 내용

시작부터 PSA 및 PSC가 사용 설정된 데이터베이스새롭게 배포할 수 있습니다.

데이터베이스 확인

  1. 완료되면 콘솔에서 SQL로 이동하여 psc-psa-sql-db 데이터베이스 인스턴스를 선택합니다.
  2. 왼쪽에서 SQL 옵션 슬라이드아웃을 펼치고 연결을 선택합니다.
  3. 요약 탭에서 연결에 관한 정보를 확인할 수 있습니다.
  4. 서비스 첨부파일 주소를 복사하여 시스템의 다른 곳에 저장합니다.
  5. 다음 작업 5단계 8번을 완료하려면 이 정보가 필요합니다.

2cf5ce71eceea326.png

7. 작업 5. 소비자 프로젝트 환경 설정 (Terraform)

소비자 프로젝트에서 방화벽 규칙과 서브넷이 있는 커스텀 VPC를 만듭니다. Cloud 콘솔을 열고 사용할 프로젝트를 선택합니다.

  1. 콘솔 상단의 오른쪽에 있는 Google Cloud 아이콘 옆에 있는 드롭다운을 클릭한 다음 all 탭을 선택합니다.

프로젝트 표시줄프로젝트 바 2

  1. 나열된 프로젝트에서 소비자 프로젝트 ID를 선택하여 계속 진행합니다.
  2. 콘솔 오른쪽 상단에 있는 Cloud Shell을 열고 Cloud Shell에 소비자 프로젝트 ID가 표시되는지 확인한 후 액세스를 허용하라는 메시지가 표시되면 확인합니다.
  3. terraform-consumer-psc라는 폴더를 만들고 해당 폴더로 이동합니다.
mkdir terraform-consumer-psc  && cd terraform-consumer-psc
  1. main.tf, variable.tf, psc.tf 파일을 만듭니다.
touch main.tf variable.tf psc.tf 
  1. 소비자 프로젝트 IDCloud Shell 편집기 뷰로 전환합니다. 편집기를 선택하고 인터페이스를 로드할 수 있도록 필요한 프롬프트를 허용합니다.
  2. 로드되면 File > Open Folder로 이동하여 /home/your-user-name/terraform-consumer-psc로 이동하고 Ok를 선택하여 편집기에서 폴더를 엽니다. 78f5eb9f2f82f1b0.png
  3. variable.tf 파일을 선택하고 다음을 추가합니다. your-consumer-project-id-here 텍스트를 실제 소비자 프로젝트 ID로 바꾸고 따옴표로 묶습니다. your-psc-attachment-id-here 텍스트를 psc 첨부파일 주소로 바꾸고 따옴표로 묶습니다. 4단계 5~7번 d7ac9629a59abfc6.png에서 복사한 ID입니다.
variable "project_id" {
  type = string
  default = "your-consumer-project-id-here"
}

variable "psc_attachment_id" {
  type = string
  default = "your-psc-attachment-id-here"
}

variable "network_id" {
  type = string
  default = "psc-endpoint-vpc"
}

variable "region_id" {
  type = string
  default = "us-east1"
}

  1. 그런 다음 main.tf 파일을 엽니다. 아래에 설명된 대로 다양한 작업을 실행하는 terraform 코드를 추가합니다.

API 사용 설정

resource "google_project_service"

VPC 만들기

resource "google_compute_network"

NAT 게이트웨이 만들기

resource "google_compute_router"
resource "google_compute_router_nat"

방화벽 규칙 추가

resource "google_compute_firewall"

  1. 다음을 복사하여 main .tf 파일에 붙여넣습니다.
resource "google_project_service" "default" {
  for_each = toset([
    "compute.googleapis.com",
    "cloudresourcemanager.googleapis.com"
  ])

  service            = each.value
  disable_on_destroy = false
}

resource "google_compute_network" "default" {
  project                 = var.project_id
  name                    = var.network_id
  auto_create_subnetworks = false
  mtu                     = 1460
  routing_mode            = "GLOBAL"
}

resource "google_compute_subnetwork" "vm_subnet_pc" {
  name          = "vm-net"
  ip_cidr_range = "192.168.80.0/24"
  region        = var.region_id
  network       = google_compute_network.default.name
  project       = var.project_id
}

resource "google_compute_subnetwork" "psc_subnet_ip" {
  name          = "psc-subnet"
  ip_cidr_range = "192.168.100.0/24"
  region        = var.region_id
  network       = google_compute_network.default.name
  project       = var.project_id
}

resource "google_compute_router" "default" {
  name    = "outbound-nat"
  region  = var.region_id
  network = google_compute_network.default.id

 bgp {
  asn = 64514
  }
}

resource "google_compute_router_nat" "default" {
  name = "outbound-nat-gw"
  router = google_compute_router.default.name
  region = google_compute_router.default.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"
  }
}

resource "google_compute_firewall" "allow_icmp" {
  name    = "allow-icmp-${google_compute_network.default.name}"
  network = google_compute_network.default.id
  project = var.project_id

  allow {
    protocol = "icmp"
  }

  source_ranges = ["0.0.0.0/0"]
  
}

resource "google_compute_firewall" "allow_ssh" {
  name    = "allow-ssh-${google_compute_network.default.name}"
  network = google_compute_network.default.id
  project = var.project_id

  allow {
    protocol = "tcp"
    ports    = ["22"]
  }

  source_ranges = ["0.0.0.0/0"]
  target_tags   = ["allow-ssh"]
}


resource "google_compute_firewall" "allow_internal" {
  name    = "allow-internal-${google_compute_network.default.name}"
  network = google_compute_network.default.id
  project = var.project_id

  allow {
    protocol = "icmp"
    }


  allow {
    protocol = "tcp"
    ports    = ["0-65535"]
  }
  allow {
    protocol = "udp"
    ports    = ["0-65535"]
  }

  source_ranges = ["192.168.0.0/16"]
 }
  1. Cloud Shell 터미널로 다시 전환하여 소비자 프로젝트의 terraform-consumer-psc 디렉터리 cd terraform-consumer-psc에 있는지 확인하고 다음 명령어를 실행합니다.

terraform init

작업 디렉터리를 초기화합니다. 이 단계에서는 지정된 구성에 필요한 제공자를 다운로드합니다.

terraform plan

Terraform이 인프라를 배포하기 위해 취할 작업을 보여주는 실행 계획을 생성합니다.

  1. 이제 리소스를 만들려면 terraform apply 명령어를 실행하고 yes를 입력하여 실행합니다.

8. 작업 6. 소비자 프로젝트 및 테스트 VM에서 SQL DB 연결에 대한 PSC 엔드포인트 만들기 (Terraform)

소비자 프로젝트에서 이 구성을 완료합니다.

  1. Cloud Shell 편집기로 다시 전환하여 terraform-consumer-psc 디렉터리를 열고 psc.tf 파일을 선택합니다. 다음 Terraform 코드를 파일에 추가합니다. 이렇게 하면 고정 내부 IP, PSC 엔드포인트, Maria DB가 설치된 테스트 VM이 생성됩니다.
resource "google_compute_address" "default" {
  name = "psc-ip-1"
  region = var.region_id
  address_type = "INTERNAL"
  subnetwork = google_compute_subnetwork.psc_subnet_ip.name
  address = "192.168.100.100" 
}

resource "google_compute_forwarding_rule" "default" {
  name = "psc-sql-endpoint"
  region = var.region_id
  network = google_compute_network.default.name
  ip_address = google_compute_address.default.self_link
  load_balancing_scheme = ""
  target = var.psc_attachment_id
}


resource "google_compute_instance" "sql_test_vm" {
  name         = "remote-sql-test-vm"
  machine_type = "e2-medium"
  zone         = "${var.region_id}-b"
  project      = var.project_id

  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-11"
    }
  }

  network_interface {
    subnetwork = google_compute_subnetwork.vm_subnet_pc.name
  }

  # No external IP address
  network_performance_config {
    total_egress_bandwidth_tier = "DEFAULT"
  }

  tags = ["allow-icmp", "allow-ssh", "allow-internal", "allow-health-check"]

  # Install MariaDB at startup
  metadata_startup_script = <<EOF
#!/bin/bash
apt-get update
apt-get install -y mariadb-server
systemctl enable mariadb
EOF
}
  1. Cloud Shell 터미널로 다시 전환하여 소비자 프로젝트의 terraform-consumer-psc 디렉터리 cd terraform-consumer-psc에 있는지 확인하고 다음 명령어를 실행합니다.

terraform plan

Terraform이 인프라를 배포하기 위해 취할 작업을 보여주는 실행 계획을 생성합니다.

  1. 이제 리소스를 만들려면 terraform apply 명령어를 실행하고 yes를 입력하여 실행합니다.

9. 작업 7. PSC IP 주소를 통해 VM에서 엔드포인트 연결 확인

소비자 프로젝트에서 완료

  1. VM 인스턴스로 이동합니다. remote-sql-test-vm을 선택합니다.
  2. SSH 옵션을 선택하여 VM에 연결합니다.
  3. 다음을 사용하여 엔드포인트를 통해 DB에 연결합니다.
mysql --host=192.168.100.100 --user=testsql --password=cloudsql24
  1. 연결이 설정되면 다음 psc-sql-db를 사용하여 데이터베이스를 만듭니다.
CREATE DATABASE remotepscpsasqldb;
  1. 완료되면 exit를 입력하여 연결을 종료합니다. exit를 다시 입력하여 VM을 닫습니다.

10. 작업 8. 데이터베이스 항목 확인

데이터베이스 프로젝트에서 이 인증을 완료합니다.

  1. 콘솔 상단의 오른쪽에 있는 Google Cloud 아이콘 옆에 있는 드롭다운을 클릭한 다음 all 탭을 선택합니다.

프로젝트 표시줄프로젝트 바 2

  1. 나열된 프로젝트에서 데이터베이스 프로젝트 ID를 선택하여 계속합니다.
  2. SQL로 이동하여 데이터베이스 psc-psa-sql-db를 선택하고 SQL 옵션을 펼친 다음 데이터베이스를 선택합니다. 방금 만든 remotepscpsasqldb라는 데이터베이스가 소비자 프로젝트 VM에 표시되고 db 프로젝트 VM에 localvpcsqldb도 표시됩니다.**.**

36f5c03124ca20f6.png

11. 삭제

소비자 프로젝트에서 완료

  1. 소비자 프로젝트 ID 선택
  2. Cloud Shell로 이동하여 소비자 프로젝트 ID가 표시되는지 확인합니다.
  3. terraform-consumer-psc 디렉터리 cd terraform-consumer-psc로 이동하여 다음 명령어 terraform destroy를 실행하고 yes를 입력하면 Terraform을 사용하여 소비자 프로젝트에서 만든 모든 리소스가 삭제됩니다.

데이터베이스 프로젝트에서 완료

  1. 데이터베이스 프로젝트 ID 선택
  2. Cloud Shell로 이동하여 데이터베이스 프로젝트 ID가 표시되는지 확인합니다.
  3. terraform-db-psc 디렉터리 cd terraform-db-psc로 이동하여 다음 명령어 terraform destroy를 실행하고 yes를 입력합니다. 그러면 Terraform으로 db 프로젝트에서 만든 대부분의 리소스가 삭제됩니다. 서비스 네트워킹이 삭제되지 않고 오류가 발생할 수 있습니다.
  4. 그런 다음 terraform-db-psc 폴더에서 다음 파일을 삭제합니다.
rm -r terraform.tfstate terraform.tfstate.backup
  1. 그런 다음 콘솔에서 VPC 네트워크로 이동합니다.
  2. database-net VPC를 선택하고 PRIVATE SERVICES ACCESS를 선택한 다음 Allocated IP Ranges for Services(서비스에 할당된 IP 범위)에서 psa-range-database-net을 선택하고 Release(출시) 옵션을 선택합니다.

e4dbfa8953c5b036.png

  1. 그런 다음 VPC 네트워크 피어링을 선택하고 servicenetworking-googleapis-com을 선택한 후 삭제 옵션을 선택합니다.

4deab14044461d2d.png

  1. 그런 다음 VPC 네트워크 삭제 를 선택합니다.2f4e96399b73d405.png

12. 축하합니다

축하합니다. PSA 및 PSC 연결이 포함된 Cloud SQL 인스턴스를 구성하고 다른 VPC에 Private Service Connect 엔드포인트를 만들었습니다.

자세히 알아보기

Private Service Connect 및 Cloud SQL에 대해 자세히 알아보세요.

기타 관련 Codelab: https://codelabs.developers.google.com/codelabs/cloudsql-psc-terraform