Terraform Pub/Sub 튜토리얼

이 튜토리얼에서는 Cloud Storage 버킷에 함수 소스 코드 zip 파일을 업로드하고 리소스 프로비저닝을 위해 Terraform을 사용해서 Pub/Sub 함수를 배포하는 방법을 보여줍니다. Terraform은 선언적 구성 파일로 Google Cloud 리소스를 프로비저닝할 수 있는 오픈소스 도구입니다.

이 튜토리얼에서는 Node.js 함수가 예시로 사용되지만 Python, Go, 자바 함수도 작동합니다. 이 안내는 사용 중인 런타임 종류와 관계없이 동일합니다. Cloud Functions v2 API에서 Terraform을 사용하는 방법에 관한 자세한 내용은 Hashicorp의 참조 페이지를 참조하세요.

환경 설정

이 튜토리얼에서는 Cloud Shell에서 명령어를 실행합니다. Cloud Shell은 Google Cloud CLI가 포함되고 Google Cloud CLI가 사전 설치된 셸 환경으로, 현재 프로젝트의 값이 이미 설정되어 있습니다. Cloud Shell은 초기화하는 데 몇 분 정도 걸릴 수 있습니다.

Cloud Shell 열기

애플리케이션 준비

Cloud Shell에서 다음 단계를 수행하세요.

  1. 샘플 앱 저장소를 Cloud Shell 인스턴스에 클론합니다.

    git clone https://github.com/terraform-google-modules/terraform-docs-samples.git
  2. Cloud Run Functions 샘플 코드가 포함된 디렉터리로 변경합니다.

    cd terraform-docs-samples/functions/pubsub

    이 튜토리얼에서 사용된 Node.js 샘플은 기본 'Hello World' Pub/Sub 함수입니다. main.tf 파일은 다음과 같습니다.

    terraform {
      required_providers {
        google = {
          source  = "hashicorp/google"
          version = ">= 4.34.0"
        }
      }
    }
    
    resource "random_id" "bucket_prefix" {
      byte_length = 8
    }
    
    
    resource "google_service_account" "default" {
      account_id   = "test-gcf-sa"
      display_name = "Test Service Account"
    }
    
    resource "google_pubsub_topic" "default" {
      name = "functions2-topic"
    }
    
    resource "google_storage_bucket" "default" {
      name                        = "${random_id.bucket_prefix.hex}-gcf-source" # Every bucket name must be globally unique
      location                    = "US"
      uniform_bucket_level_access = true
    }
    
    data "archive_file" "default" {
      type        = "zip"
      output_path = "/tmp/function-source.zip"
      source_dir  = "function-source/"
    }
    
    resource "google_storage_bucket_object" "default" {
      name   = "function-source.zip"
      bucket = google_storage_bucket.default.name
      source = data.archive_file.default.output_path # Path to the zipped function source code
    }
    
    resource "google_cloudfunctions2_function" "default" {
      name        = "function"
      location    = "us-central1"
      description = "a new function"
    
      build_config {
        runtime     = "nodejs22"
        entry_point = "helloPubSub" # Set the entry point
        environment_variables = {
          BUILD_CONFIG_TEST = "build_test"
        }
        source {
          storage_source {
            bucket = google_storage_bucket.default.name
            object = google_storage_bucket_object.default.name
          }
        }
      }
    
      service_config {
        max_instance_count = 3
        min_instance_count = 1
        available_memory   = "256M"
        timeout_seconds    = 60
        environment_variables = {
          SERVICE_CONFIG_TEST = "config_test"
        }
        ingress_settings               = "ALLOW_INTERNAL_ONLY"
        all_traffic_on_latest_revision = true
        service_account_email          = google_service_account.default.email
      }
    
      event_trigger {
        trigger_region = "us-central1"
        event_type     = "google.cloud.pubsub.topic.v1.messagePublished"
        pubsub_topic   = google_pubsub_topic.default.id
        retry_policy   = "RETRY_POLICY_RETRY"
      }
    }

Terraform 초기화

main.tf 파일이 포함된 terraform-docs-samples/functions/pubsub 디렉터리에서 이 명령어를 실행하여 필요한 플러그인을 추가하고 .terraform 디렉터리를 빌드합니다.

terraform init

Terraform 구성 검증

Terraform 구성을 미리봅니다. 이 단계는 선택사항이지만 main.tf 문법이 올바른지 확인할 수 있습니다. 이 명령어는 생성할 리소스의 미리보기를 보여줍니다.

terraform plan

Terraform 구성 적용

구성을 적용하여 함수를 배포합니다. 메시지가 표시되면 yes를 입력합니다.

terraform apply

함수 트리거

Pub/Sub 함수를 테스트하려면 다음 안내를 따르세요.

  1. 주제에 메시지를 게시합니다(이 예시에서는 주제 이름이 functions2-topic임).

    gcloud pubsub topics publish TOPIC_NAME --message="Friend"
  2. 함수 로그를 읽어 결과를 확인합니다. 여기서 FUNCTION_NAME은 함수의 이름입니다(이 예시에서는 함수 이름이 function임).

    gcloud functions logs read FUNCTION_NAME

    새 '친구' 메시지가 포함된 로깅 출력을 볼 수 있습니다.

삭제

이 튜토리얼을 완료한 후 추가 비용이 발생하지 않도록 생성된 모든 리소스를 삭제할 수 있습니다.

Terraform에서는 terraform destroy 명령어를 실행하여 구성 파일에 정의된 모든 리소스를 삭제할 수 있습니다.

terraform destroy

Terraform에서 리소스를 삭제할 수 있도록 yes를 입력합니다.