מדריך בנושא Pub/Sub ב-Terraform

במדריך הזה נסביר איך לפרוס פונקציית Pub/Sub על ידי העלאה של קובץ zip של קוד המקור של הפונקציה לקטגוריה של Cloud Storage, באמצעות Terraform להקצאת המשאבים. ‫Terraform הוא כלי בקוד פתוח שמאפשר להקצות Google Cloud משאבים באמצעות קובצי תצורה מוצהרים.

במדריך הזה נעשה שימוש בפונקציית Node.js כדוגמה, אבל הוא מתאים גם לפונקציות Python,‏ Go ו-Java. ההוראות זהות בין אם אתם משתמשים באחד מהזמנים האלה להפעלה. לפרטים על שימוש ב-Terraform עם Cloud Functions API v2, אפשר לעיין בדפי העיון של Hashicorp.

מטרות

  • כאן תוכלו ללמוד איך משתמשים ב-Terraform כדי לפרוס פונקציה של Pub/Sub.

עלויות

במסמך הזה משתמשים ברכיבים הבאים של Google Cloud, והשימוש בהם כרוך בתשלום:

For details, see Cloud Run functions pricing.

כדי להעריך את ההוצאות בהתאם לתחזית השימוש שלכם, אתם יכולים להיעזר במחשבון העלויות.

משתמשים חדשים של Google Cloud ? יכול להיות שאתם זכאים לתקופת ניסיון בחינם.

לפני שמתחילים

  1. נכנסים לחשבון Google Cloud . אם אתם משתמשים חדשים ב- Google Cloud, צרו חשבון כדי שתוכלו להעריך את הביצועים של המוצרים שלנו בתרחישים מהעולם האמיתי. לקוחות חדשים מקבלים בחינם גם קרדיט בשווי 300$ להרצה, לבדיקה ולפריסה של עומסי העבודה.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

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

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

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  5. התקינו את ה-CLI של Google Cloud.

  6. אם אתם משתמשים בספק זהויות חיצוני (IdP), קודם אתם צריכים להיכנס ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

  7. כדי לאתחל את ה-CLI של gcloud, הריצו את הפקודה הבאה:

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

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

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

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

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  11. התקינו את ה-CLI של Google Cloud.

  12. אם אתם משתמשים בספק זהויות חיצוני (IdP), קודם אתם צריכים להיכנס ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

  13. כדי לאתחל את ה-CLI של gcloud, הריצו את הפקודה הבאה:

    gcloud init
  14. אם כבר התקנתם את ה-CLI של gcloud, מריצים את הפקודה הבאה כדי לעדכן אותו:

    gcloud components update
  15. מקצים לחשבון השירות של Compute שמוגדר כברירת מחדל את התפקידים roles/run.invoker ו-roles/cloudbuild.builds.builder.
  16. מכינים את סביבת הפיתוח.

    למדריך ההגדרה של Node.js

הגדרת הסביבה

במדריך הזה מריצים פקודות ב-Cloud Shell. ‫Cloud Shell היא סביבת מעטפת שבה ה-CLI של Google Cloud כבר מותקן, כולל ה-CLI של Google Cloud, ומוגדרים בה ערכים לפרויקט הנוכחי. יכול להיות שיעברו כמה דקות עד ש-Cloud Shell יאותחל:

פתיחת Cloud Shell

הכנת הבקשה

ב-Cloud Shell, מבצעים את השלבים הבאים:

  1. משכפלים את מאגר האפליקציות לדוגמה למופע Cloud Shell:

    git clone https://github.com/terraform-google-modules/terraform-docs-samples.git
  2. עוברים לספרייה שמכילה את הקוד לדוגמה של פונקציות Cloud Run:

    cd terraform-docs-samples/functions/pubsub

    הדוגמה ל-Node.js שבה נעשה שימוש במדריך הזה היא פונקציית Pub/Sub בסיסית של Hello World. הנה הקובץ 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

בספרייה terraform-docs-samples/functions/pubsub שמכילה את הקובץ main.tf, מריצים את הפקודה הבאה כדי להוסיף את הפלאגינים הנדרשים וליצור את הספרייה .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 destroy כדי להסיר את כל המשאבים שהוגדרו בקובץ התצורה של Terraform:

terraform destroy

כדי לאפשר ל-Terraform למחוק את המשאבים, כותבים yes.