מדריך Terraform

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

במדריך הזה נעשה שימוש בפונקציית HTTP של Node.js כדוגמה, אבל הוא מתאים גם לפונקציות HTTP של Python,‏ Go ו-Java. ההוראות זהות לא משנה באיזה זמן ריצה משתמשים.

כשפורסים באמצעות Terraform, צריך להעלות את קובץ המקור הדחוס של הפונקציה לקטגוריה של Cloud Storage‏ (source_archive_bucket), וגם לציין את שם האובייקט ב-Cloud Storage‏ (source_archive_object) בהגדרות של Terraform. מידע נוסף זמין במדריך המפרט של Terraform.

פונקציות Cloud Run מעתיקות את קובץ המקור שמעלים ב-source_archive_bucket לקטגוריה בפרויקט עם שם קטגוריה בפורמט gcf-v2-sources-PROJECT_NUMBER-REGION(פונקציות Cloud Run) או gcf-sources-PROJECT_NUMBER-REGION פונקציות Cloud Run (דור ראשון). ההגדרה הזו משתנה בהתאם לתלות ב-CMEK.

מטרות

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

עלויות

במסמך הזה משתמשים ברכיבים הבאים של 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 Run, 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 Run, 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. מכינים את סביבת הפיתוח.

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

התפקידים הנדרשים

  • למשתמשים שמבצעים פריסה של פונקציות צריך להיות תפקיד Cloud Functions Developer (roles/cloudfunctions.developer) ב-IAM או תפקיד שכולל את אותן הרשאות. אפשר לעיין גם במאמר הגדרות נוספות לפריסה.

  • כדי לקבל את ההרשאות לגישה לקטגוריה של Cloud Storage, צריך לבקש מהאדמין להקצות לזהות ה-IAM שמבצעת את הפריסה של הפונקציה את התפקיד אדמין לניהול אחסון (roles/storage.admin). פרטים נוספים על תפקידים והרשאות ב-Cloud Storage זמינים במאמר IAM ל-Cloud Storage.

הגדרת הסביבה

במדריך הזה מריצים פקודות ב-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/basic

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

בספרייה terraform-docs-samples/functions/basic שמכילה את הקובץ main.tf, מריצים את הפקודה הבאה כדי להוסיף את הפלאגינים הנדרשים וליצור את הספרייה .terraform:

terraform init

החלת ההגדרות של Terraform

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

terraform destroy

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