פרסום וקבלת אירועים על ידי יצירת אוטובוס והרשמה (Terraform)

במדריך למתחילים הזה מוסבר איך להשתמש ב-Terraform כדי ליצור אפיק (bus) של Eventarc Advanced ולהירשם לפרויקט Google Cloud , כדי שתוכלו לפרסם ולקבל הודעות אירועים.

  • אוטובוס פועל כנתב מרכזי שמקבל הודעות ממקורות אירועים או שספקים מפרסמים.

  • הרשמה מנתבת הודעות שהאפיק מקבל ליעד אחד או יותר דרך פייפליין עיבוד.

במדריך למתחילים הזה:

  1. פריסת שירות לקבלת אירועים ב-Cloud Run.

  2. יוצרים אוטובוס מתקדם של Eventarc.

  3. הפעלת אירועים ממקורות של Google.

  4. יצירת פייפליין מתקדם של Eventarc והרשמה.

  5. כדי לפרסם הודעת אירוע באוטובוס, צריך ליצור תהליך עבודה.

  6. צפייה בנתוני האירועים ביומנים של Cloud Run.

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

מידע נוסף על שימוש ב-Terraform זמין במאמרי העזרה בנושא Terraform ב- Google Cloud.

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

יכול להיות שהגבלות אבטחה שהוגדרו בארגון שלכם ימנעו מכם להשלים את השלבים הבאים. מידע לפתרון בעיות זמין במאמר פיתוח אפליקציות בסביבה 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. If you're using an existing project for this guide, verify that you have the permissions required to complete this guide. If you created a new project, then you already have the required permissions.

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

  5. Enable the Cloud Resource Manager and Identity and Access Management (IAM) 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

  6. 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

  7. If you're using an existing project for this guide, verify that you have the permissions required to complete this guide. If you created a new project, then you already have the required permissions.

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

  9. Enable the Cloud Resource Manager and Identity and Access Management (IAM) 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

  10. במסוף Google Cloud , מפעילים את Cloud Shell.

    הפעלת Cloud Shell

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

  11. ‫Terraform משולב בסביבת Cloud Shell, ואפשר להשתמש ב-Cloud Shell כדי לפרוס את משאבי Terraform בלי להתקין את Terraform.

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

כדי לקבל את ההרשאות שדרושות לביצוע ההפעלה המהירה הזו, צריך לבקש מהאדמין להקצות לכם את תפקידי ה-IAM הבאים בפרויקט:

להסבר על מתן תפקידים, ראו איך מנהלים את הגישה ברמת הפרויקט, התיקייה והארגון.

יכול להיות שאפשר לקבל את ההרשאות הנדרשות גם באמצעות תפקידים בהתאמה אישית או תפקידים מוגדרים מראש.

הכנה לפריסת Terraform

לפני שפורסים משאבים של Terraform, צריך ליצור קובץ תצורה של Terraform. קובץ תצורה של Terraform מאפשר להגדיר את מצב הסיום המועדף של התשתית באמצעות התחביר של Terraform.

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

    export GOOGLE_CLOUD_PROJECT=PROJECT_ID

    מחליפים את PROJECT_ID במזהה הפרויקט. Google Cloud

    שימו לב: אם תגדירו ערכים ספציפיים בקובץ התצורה של Terraform, הם יבטלו את ערכי ברירת המחדל של משתני הסביבה.

  2. לכל קובץ תצורה של Terraform צריכה להיות ספרייה משלו (שנקראת גם מודול ברמה הבסיסית). יוצרים ספרייה חדשה ב-Cloud Shell ובה יוצרים קובץ חדש:

    mkdir DIRECTORY && cd DIRECTORY && touch main.tf

    מחליפים את DIRECTORY בשם של ספריית Terraform.

    שם הקובץ חייב לכלול את הסיומת .tf. לדוגמה, במדריך למתחילים הזה, קובץ התצורה הוא main.tf.

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

מעתיקים את קטעי הקוד הבאים של Terraform לקובץ main.tf. לחלופין, כדי להעתיק את כל דוגמת הקוד מ-GitHub, בפינה השמאלית העליונה של קטע הקוד, לוחצים על > View on GitHub (הצגה ב-GitHub).

הפעלת ממשקי ה-API

משתמשים במשאב google_project_service של Terraform כדי להפעיל את ממשקי ה-API שנדרשים להחלת ההגדרות של Terraform:

# Enable APIs
resource "google_project_service" "apis" {
  for_each = toset([
    "eventarc.googleapis.com",
    "eventarcpublishing.googleapis.com",
    "run.googleapis.com"
  ])
  service            = each.key
  disable_on_destroy = false
}

יצירה של חשבון שירות

למטרות בדיקה, יוצרים חשבון שירות ייעודי ומעניקים לו תפקידי IAM ספציפיים.

משתמשים במשאבי Terraform‏ google_service_account ו-google_project_iam_member כדי ליצור את חשבון השירות ולהעניק לו את התפקידים הנדרשים לפרסום ולקבלת אירועים:

# Used to retrieve project information later
data "google_project" "project" {}

# Create a dedicated service account
resource "google_service_account" "default" {
  account_id   = "eventarc-advanced-sa"
  display_name = "Eventarc Advanced quickstart service account"
}

# Grant permission to receive Eventarc events
resource "google_project_iam_member" "eventreceiver" {
  project = data.google_project.project.id
  role    = "roles/eventarc.eventReceiver"
  member  = "serviceAccount:${google_service_account.default.email}"
}

# Grant permission to invoke Cloud Run services
resource "google_project_iam_member" "runinvoker" {
  project = data.google_project.project.id
  role    = "roles/run.invoker"
  member  = "serviceAccount:${google_service_account.default.email}"
}

יצירת יעד לאירועים

משתמשים במשאב Terraform‏ google_cloud_run_v2_service כדי ליצור שירות Cloud Run כיעד לאירועים שמתעד את התוכן של אירוע:

# Deploy Cloud Run service
resource "google_cloud_run_v2_service" "default" {
  name     = "example-service"
  location = "us-central1"

  deletion_protection = false # set to "true" in production

  template {
    containers {
      # This sample container listens to HTTP requests and logs received events
      image = "us-docker.pkg.dev/cloudrun/container/hello"
    }
    service_account = google_service_account.default.email
  }

  depends_on = [google_project_service.apis]
}

יצירת אפיק Eventarc Advanced

אוטובוס מקבל הודעות על אירועים ממקור הודעות או שספק מפרסם אותן והוא פועל כנתב הודעות. מידע נוסף זמין במאמר יצירת אפיק (bus) להעברת הודעות.

משתמשים במשאב Terraform‏ google_eventarc_message_bus כדי ליצור Eventarc Advanced bus:

# Create an Eventarc Advanced bus
resource "google_eventarc_message_bus" "default" {
  location       = "us-central1"
  message_bus_id = "example-bus"
}

הפעלת אירועים ממקורות של Google

כדי לפרסם אירועים ממקורות של Google, צריך ליצור משאב GoogleApiSource שמייצג מינוי לאירועי Google API עבור Eventarc Advanced bus מסוים. מידע נוסף זמין במאמר בנושא פרסום אירועים ממקורות של Google.

משתמשים במשאב Terraform‏ google_eventarc_google_api_source כדי להפעיל אירועים ממקורות של Google:

# Enable events from Google API sources
resource "google_eventarc_google_api_source" "default" {
  location             = "us-central1"
  google_api_source_id = "example-google-api-source"
  destination          = google_eventarc_message_bus.default.id
}

כל סוגי האירועים הנתמכים של Google שנשלחים ישירות ממקור של Google נאספים עכשיו ומתפרסמים באוטובוס.

יצירת צינור עיבוד נתונים מתקדם של Eventarc

צינור מאפשר להגדיר יעד, וגם מספק אפשרות להמיר אירועים תואמים לפני העברתם ליעד.

משתמשים במשאב Terraform‏ google_eventarc_pipeline כדי ליצור צינור:

# Create an Eventarc Advanced pipeline
resource "google_eventarc_pipeline" "default" {
  location    = "us-central1"
  pipeline_id = "example-pipeline"
  destinations {
    http_endpoint {
      uri = google_cloud_run_v2_service.default.uri
    }
    authentication_config {
      google_oidc {
        service_account = google_service_account.default.email
      }
    }
  }
}

יעד האירוע הוא כתובת ה-URL המוגדרת במלואה של שירות Cloud Run, למשל: https://SERVICE_NAME-abcdef-uc.a.run.app. כתובת האימייל בחשבון השירות משמשת ליצירת אסימון OIDC.

יצירת הרשמה ל-Eventarc Advanced

ההרשמה קובעת אילו הודעות ינותבו ליעד, ומציינת את צינור הנתונים שמשמש להגדרת יעד להודעות האירועים. מידע נוסף מופיע במאמר בנושא יצירת רישום לקבלת אירועים.

משתמשים במשאב google_eventarc_enrollment של Terraform כדי ליצור הרשמה:

# Create an Eventarc Advanced enrollment
resource "google_eventarc_enrollment" "default" {
  location      = "us-central1"
  enrollment_id = "example-enrollment"
  message_bus   = google_eventarc_message_bus.default.id
  destination   = google_eventarc_pipeline.default.id
  cel_match     = "message.type == 'google.cloud.workflows.workflow.v1.created'"
}

ביטוי ההתאמה להרשמה משתמש ב-Common Expression Language ‏ (CEL) כדי לפרסם הודעות אירועים בכל פעם שנוצר תהליך עבודה. בשלב הבא, יוצרים תהליך עבודה.

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

משתמשים ב-Terraform CLI כדי להקצות תשתית על סמך קובץ ההגדרות. מידע נוסף מופיע במאמר בנושא פקודות בסיסיות ב-Terraform.

  1. מפעילים את Terraform. צריך לעשות את זה רק פעם אחת לכל ספרייה.

    terraform init

    אופציונלי: כדי להשתמש בגרסה העדכנית ביותר של הפלאגין שמתממשק עם שירותים חיצוניים של Google, תוכלו לכלול את האפשרות -upgrade:

    terraform init -upgrade
  2. בודקים את ההגדרות ומוודאים שהמשאבים שמערכת Terraform תיצור או תעדכן תואמים לציפיות שלכם:

    terraform plan

    מתקנים את ההגדרות לפי הצורך.

  3. מריצים את הפקודה הבאה ומזינים yes בהודעה שמופיעה, כדי להחיל את הגדרות Terraform:

    terraform apply

    בדרך כלל, מחילים את כל ההגדרה בבת אחת. אבל אפשר גם לטרגט משאב ספציפי. לדוגמה:

    terraform apply -target="google_eventarc_message_bus.default"

    ממתינים עד שב-Terraform תוצג ההודעה "Apply complete!‎".

פרסום הודעת אירוע באפיק על ידי יצירת תהליך עבודה

‫Workflows היא פלטפורמת תזמור מנוהלת במלואה שמבצעת שירותים בסדר שאתם מגדירים: תהליך עבודה. יוצרים תהליך עבודה כדי ליצור סוג אירוע נתמך ממקור של Google.

  1. בספריית הבית, יוצרים קובץ חדש בשם myWorkflow.yaml.

  2. מעתיקים את תהליך העבודה הבא ומדביקים אותו בקובץ החדש, ואז שומרים אותו:

    main:
        params: [input]
        steps:
        - checkSearchTermInInput:
            switch:
                - condition: '${"searchTerm" in input}'
                  assign:
                    - searchTerm: '${input.searchTerm}'
                  next: readWikipedia
        - getLocation:
            call: sys.get_env
            args:
                name: GOOGLE_CLOUD_LOCATION
            result: location
        - setFromCallResult:
            assign:
                - searchTerm: '${text.split(location, "-")[0]}'
        - readWikipedia:
            call: http.get
            args:
                url: 'https://en.wikipedia.org/w/api.php'
                query:
                    action: opensearch
                    search: '${searchTerm}'
            result: wikiResult
        - returnOutput:
                return: '${wikiResult.body[1]}'
    

    בתהליך העבודה הזה, האזור שבו תהליך העבודה נפרס מועבר אל Wikipedia API ומוחזרת רשימה של מאמרים קשורים בוויקיפדיה.

  3. מפעילים את תהליך העבודה באמצעות הפקודה gcloud workflows deploy:

    gcloud workflows deploy example-workflow --source=myWorkflow.yaml \
        --service-account=eventarc-advanced-sa@PROJECT_ID.iam.gserviceaccount.com \
        --location=us-central1

צפייה בנתוני האירועים ביומני Cloud Run

אחרי שמפרסמים אירוע באפיק (bus) Eventarc Advanced, אפשר לבדוק את היומנים של שירות Cloud Run כדי לוודא שהאירוע התקבל כמצופה.

  1. מסננים את הרשומות ביומן שנוצרו על ידי השירות:

    gcloud logging read 'jsonPayload.message: "Received event of type google.cloud.workflows.workflow.v1.created."'
    
  2. מחפשים רשומה ביומן שדומה לזו:

    message: 'Received event of type google.cloud.workflows.workflow.v1.created.
    Event data: {"@type":"type.googleapis.com/google.events.cloud.workflows.v1.WorkflowEventData","payload":{"name":"projects/PROJECT_ID/locations/us-central1/workflows/example-workflow","state":"ACTIVE"...
    

יצרתם בהצלחה Eventarc Advanced אפיק (bus) ורישום, הפעלתם את הפרסום של אירועים ממקורות של Google, יצרתם תהליך עבודה ליצירת סוג אירוע נתמך מפלאגין שמתממשק עם שירותים חיצוניים של Google, ואז אימתתם את התוצאה הצפויה ביומנים של שירות מקבל האירועים.

הסרת המשאבים

כדי להסיר משאבים שהוחלו בעבר על הגדרות Terraform, מריצים את הפקודה הבאה ומזינים yes בהודעה שמופיעה:

terraform destroy

אפשר גם למחוק את Google Cloud הפרויקט כדי להימנע מחיובים. אם מוחקים את הפרויקט Google Cloud , החיוב על כל המשאבים שנעשה בהם שימוש באותו פרויקט יופסק.

  1. במסוף Google Cloud , נכנסים לדף Manage resources.

    כניסה לדף Manage resources

  2. ברשימת הפרויקטים, בוחרים את הפרויקט שרוצים למחוק ולוחצים על Delete.
  3. כדי למחוק את הפרויקט, כותבים את מזהה הפרויקט בתיבת הדו-שיח ולוחצים על Shut down.

המאמרים הבאים