Terraform 튜토리얼


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

이 튜토리얼에서는 Node.js HTTP 함수가 예시로 사용되지만 Python, Go, 자바 HTTP 함수도 작동합니다. 이 안내는 사용 중인 런타임과 종류와 관계없이 동일합니다.

Terraform으로 배포할 때는 함수의 압축된 소스 파일을 Cloud Storage 버킷(source_archive_bucket)에 업로드해야 하며 Terraform 구성에서 Cloud Storage 객체 이름(source_archive_object)도 지정해야 합니다. 자세한 내용은 Terraform 사양 가이드를 참조하세요.

Cloud Run Functions는 source_archive_bucket에 업로드한 소스 파일을 gcf-v2-sources-PROJECT_NUMBER-REGION(Cloud Run Functions) 또는 gcf-sources-PROJECT_NUMBER-REGION Cloud Run Functions(1세대) 형식의 버킷 이름이 있는 프로젝트의 버킷에 복사합니다. 이 구성은 CMEK 종속 항목에 따라 다릅니다.

목표

  • Terraform을 사용하여 HTTP 함수를 배포하는 방법을 알아봅니다.

비용

이 문서에서는 비용이 청구될 수 있는 Google Cloud구성요소( )를 사용합니다.

For details, see Cloud Run functions pricing.

프로젝트 사용량을 기준으로 예상 비용을 산출하려면 가격 계산기를 사용합니다.

Google Cloud 신규 사용자는 무료 체험판을 사용할 수 있습니다.

시작하기 전에

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Cloud Functions, Cloud Run, Cloud Build, Artifact Registry, and Cloud Storage APIs.

    Enable the APIs

  5. Install the Google Cloud CLI.

  6. 외부 ID 공급업체(IdP)를 사용하는 경우 먼저 제휴 ID로 gcloud CLI에 로그인해야 합니다.

  7. gcloud CLI를 초기화하려면, 다음 명령어를 실행합니다.

    gcloud init
  8. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  9. Verify that billing is enabled for your Google Cloud project.

  10. Enable the Cloud Functions, Cloud Run, Cloud Build, Artifact Registry, and Cloud Storage APIs.

    Enable the APIs

  11. Install the Google Cloud CLI.

  12. 외부 ID 공급업체(IdP)를 사용하는 경우 먼저 제휴 ID로 gcloud CLI에 로그인해야 합니다.

  13. gcloud CLI를 초기화하려면, 다음 명령어를 실행합니다.

    gcloud init
  14. gcloud CLI가 이미 설치되어 있으면 다음 명령어를 실행하여 업데이트합니다.

    gcloud components update
  15. 개발 환경을 준비합니다.

    Node.js 설정 가이드로 이동

  16. 필요한 역할

    • 함수를 배포하는 사용자에게는 Cloud Functions 개발자(roles/cloudfunctions.developer) IAM 역할 또는 동일한 권한이 포함된 역할이 있어야 합니다. 또한 배포 추가 구성을 참조하세요.

    • Cloud Storage 버킷에 액세스할 수 있는 권한을 얻으려면 관리자에게 함수를 배포하는 IAM ID에 스토리지 관리자(roles/storage.admin) 역할을 부여해 달라고 요청하세요. Cloud Storage 역할 및 권한에 대한 자세한 내용은 Cloud Storage용 IAM을 참조하세요.

    환경 설정

    이 튜토리얼에서는 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/basic

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

      terraform {
        required_providers {
          google = {
            source  = "hashicorp/google"
            version = ">= 4.34.0"
          }
        }
      }
      
      resource "random_id" "default" {
        byte_length = 8
      }
      
      resource "google_storage_bucket" "default" {
        name                        = "${random_id.default.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  = "functions/hello-world/"
      }
      resource "google_storage_bucket_object" "object" {
        name   = "function-source.zip"
        bucket = google_storage_bucket.default.name
        source = data.archive_file.default.output_path # Add path to the zipped function source code
      }
      
      resource "google_cloudfunctions2_function" "default" {
        name        = "function-v2"
        location    = "us-central1"
        description = "a new function"
      
        build_config {
          runtime     = "nodejs22"
          entry_point = "helloHttp" # Set the entry point
          source {
            storage_source {
              bucket = google_storage_bucket.default.name
              object = google_storage_bucket_object.object.name
            }
          }
        }
      
        service_config {
          max_instance_count = 1
          available_memory   = "256M"
          timeout_seconds    = 60
        }
      }
      
      resource "google_cloud_run_service_iam_member" "member" {
        location = google_cloudfunctions2_function.default.location
        service  = google_cloudfunctions2_function.default.name
        role     = "roles/run.invoker"
        member   = "allUsers"
      }
      
      output "function_uri" {
        value = google_cloudfunctions2_function.default.service_config[0].uri
      }

    Terraform 초기화

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

    terraform init
    

    Terraform 구성 적용

    main.tf 파일이 포함된 동일한 terraform-docs-samples/functions/basic 디렉터리에서 구성을 적용하여 함수를 배포합니다. 메시지가 표시되면 yes를 입력합니다.

    terraform apply
    

    함수 테스트

    1. 함수 배포가 완료되면 URI 속성을 기록하거나 다음 명령어를 사용하여 찾을 수 있습니다.

      gcloud functions describe function-v2 --gen2 --region=us-central1 --format="value(serviceConfig.uri)"
      
    2. 이 URL을 요청하여 함수의 'Hello World' 메시지를 표시합니다. 함수는 인증이 필요하도록 배포됩니다. 따라서 요청에 사용자 인증 정보를 제공해야 합니다.

      curl -H "Authorization: Bearer $(gcloud auth print-identity-token)" YOUR_FUNCTION_URL

    삭제

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

    Terraform에서는 main.tf 파일이 포함된 terraform-docs-samples/functions/basic 디렉터리에서 terraform destroy 명령어를 실행하여 구성 파일에 정의된 모든 리소스를 삭제할 수 있습니다.

    terraform destroy
    

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