מדריך בנושא 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, if any are not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the APIs

  5. Install the Google Cloud CLI.

  6. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  7. To initialize the gcloud CLI, run the following command:

    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, if any are not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the APIs

  11. Install the Google Cloud CLI.

  12. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  13. To initialize the gcloud CLI, run the following command:

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

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

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

הגדרת הסביבה

במדריך הזה מריצים פקודות ב-Cloud Shell. ‫Cloud Shell היא סביבת מעטפת שבה ה-CLI של Google Cloud כבר מותקן, כולל 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:

    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.