Create a Cloud function

Check my progress

/ 30

Create a Cloud Storage bucket and BigQuery dataset

Check my progress

/ 30

Deploy your function

Check my progress

/ 40

This lab may incorporate AI tools to support your learning.

總覽

「Cloud Run functions」是由事件觸發的程式碼,事件包括 HTTP 要求、訊息服務發送的訊息,或是檔案上傳作業等。「Cloud 事件」是雲端環境中發生的「事項」,可能是資料庫內的資料出現異動、儲存系統中新增了檔案,或是建立新的虛擬機器執行個體。

Cloud Run functions 由事件觸發,只有發生事件時才會執行,因此適用於必須迅速完成或不必隨時保持運作的工作。

在本實作實驗室中,您將瞭解如何建立、部署及測試 Cloud Run functions,利用 Google Cloud SDK 載入 BigQuery 資料表。

學習內容

  • 建立 Cloud Run functions
  • 部署及測試 Cloud Run functions
  • 查看 BigQuery 中的資料及 Cloud Run functions 記錄

設定和需求

每個實驗室都會提供新的 Google Cloud 專案和一組資源,讓您在時限內免費使用。

  1. 按一下「Start Lab」按鈕。如果研究室會產生費用,畫面中會出現選擇付款方式的彈出式視窗。左側的「Lab Details」窗格會顯示下列項目:

    • 「Open Google Cloud console」按鈕
    • 剩餘時間
    • 必須在這個研究室中使用的臨時憑證
    • 完成這個實驗室所需的其他資訊 (如有)
  2. 點選「Open Google Cloud console」;如果使用 Chrome 瀏覽器,也能按一下滑鼠右鍵,選取「在無痕視窗中開啟連結」

    接著,實驗室會啟動相關資源並開啟另一個分頁,當中顯示「登入」頁面。

    提示:您可以在不同的視窗中並排開啟分頁。

    注意:如果頁面中顯示「選擇帳戶」對話方塊,請點選「使用其他帳戶」
  3. 如有必要,請將下方的 Username 貼到「登入」對話方塊。

    {{{user_0.username | "Username"}}}

    您也可以在「Lab Details」窗格找到 Username

  4. 點選「下一步」

  5. 複製下方的 Password,並貼到「歡迎使用」對話方塊。

    {{{user_0.password | "Password"}}}

    您也可以在「Lab Details」窗格找到 Password

  6. 點選「下一步」

    重要事項:請務必使用實驗室提供的憑證,而非自己的 Google Cloud 帳戶憑證。 注意:如果使用自己的 Google Cloud 帳戶來進行這個實驗室,可能會產生額外費用。
  7. 按過後續的所有頁面:

    • 接受條款及細則。
    • 由於這是臨時帳戶,請勿新增救援選項或雙重驗證機制。
    • 請勿申請免費試用。

Google Cloud 控制台稍後會在這個分頁開啟。

注意:如要查看列出 Google Cloud 產品和服務的選單,請點選左上角的「導覽選單」,或在「搜尋」欄位輸入服務或產品名稱。 「導覽選單」圖示

啟動 Google Cloud Shell

Google Cloud Shell 是搭載多項開發工具的虛擬機器,提供永久的 5 GB 主目錄,而且在 Google Cloud 中運作。

Google Cloud Shell 提供指令列存取權,方便您使用 Google Cloud 資源。

  1. 在 Cloud 控制台的右上方找到工具列,然後按一下「開啟 Cloud Shell」按鈕。

    特別標明的「Cloud Shell」圖示

  2. 按一下「繼續」

佈建並連線至環境的作業需要一些時間才能完成。連線建立完成即代表已通過驗證,而且專案已設為您的「PROJECT_ID」。示例如下:

在 Cloud Shell 終端機中,特別標明了專案 ID

gcloud 是 Google Cloud 的指令列工具,已預先安裝於 Cloud Shell,並支援 Tab 鍵完成功能。

  • 您可以使用下列指令來列出使用中的帳戶:
gcloud auth list

輸出內容:

Credentialed accounts: - @.com (active)

輸出內容示例:

Credentialed accounts: - google1623327_student@qwiklabs.net
  • 您可以使用下列指令來列出專案 ID:
gcloud config list project

輸出內容:

[core] project =

輸出內容示例:

[core] project = qwiklabs-gcp-44776a13dea667a6 注意事項:如需 gcloud 的完整說明,請參閱 gcloud CLI 總覽指南

工作 1:啟用 API

在這項工作中,您會先啟用相關 API,再建立 Cloud Run functions。

  1. 在 Cloud Shell 執行下列指令,設定 PROJECT_ID 變數:
export PROJECT_ID=$(gcloud config get-value project)
  1. 執行下列指令,設定 Region 變數:
export REGION={{{project_0.default_region | "REGION"}}} gcloud config set compute/region $REGION
  1. 執行下列指令來設定變數:
gcloud config set run/region $REGION gcloud config set run/platform managed gcloud config set eventarc/location $REGION
  1. 執行下列指令,啟用所有必要服務:
gcloud services enable \ artifactregistry.googleapis.com \ cloudfunctions.googleapis.com \ cloudbuild.googleapis.com \ eventarc.googleapis.com \ run.googleapis.com \ logging.googleapis.com \ pubsub.googleapis.com 注意:Eventarc 可能需要幾分鐘才能將所有權限套用至服務代理

工作 2:設定必要權限

在這項工作中,您會將 Eventarc 事件接收權限授予預設的 Compute Engine 服務帳戶,以及將發布訊息到 Pub/Sub 主題的權限授予 Cloud Storage 服務代理,藉此啟用事件導向工作流程和 Storage 觸發的動作。

  1. 在 Cloud Shell 執行下列指令,設定 PROJECT_NUMBER 變數:
export PROJECT_NUMBER=$(gcloud projects describe $PROJECT_ID --format='value(projectNumber)')
  1. 執行下列指令,為專案中的預設 Compute Engine 服務帳戶授予必要權限,以便接收 Eventarc 事件:
gcloud projects add-iam-policy-binding $PROJECT_ID \ --member="serviceAccount:$PROJECT_NUMBER-compute@developer.gserviceaccount.com" \ --role="roles/eventarc.eventReceiver"
  1. 執行下列指令,擷取專案的 Cloud Storage 服務代理,並授予向 Pub/Sub 主題發布訊息的權限:
SERVICE_ACCOUNT="$(gcloud storage service-agent --project=$PROJECT_ID)" gcloud projects add-iam-policy-binding $PROJECT_ID \ --member="serviceAccount:${SERVICE_ACCOUNT}" \ --role='roles/pubsub.publisher'

工作 3:建立函式

在這項工作中,您會建立 loadBigQueryFromAvro 這個簡單的函式。這個函式會讀取上傳至 Cloud Storage 的 Avro 檔案,然後建立資料表並載入 BigQuery。

  1. 在 Cloud Shell 執行下列指令,建立並開啟 index.js 這個檔案:
nano index.js
  1. 將下列 Cloud 函式的程式碼複製到 index.js 檔案:
/** * index.js Cloud Function - Avro on GCS to BQ */ const {Storage} = require('@google-cloud/storage'); const {BigQuery} = require('@google-cloud/bigquery'); const storage = new Storage(); const bigquery = new BigQuery(); exports.loadBigQueryFromAvro = async (event, context) => { try { // Check for valid event data and extract bucket name if (!event || !event.bucket) { throw new Error('Invalid event data. Missing bucket information.'); } const bucketName = event.bucket; const fileName = event.name; // BigQuery configuration const datasetId = 'loadavro'; const tableId = fileName.replace('.avro', ''); const options = { sourceFormat: 'AVRO', autodetect: true, createDisposition: 'CREATE_IF_NEEDED', writeDisposition: 'WRITE_TRUNCATE', }; // Load job configuration const loadJob = bigquery .dataset(datasetId) .table(tableId) .load(storage.bucket(bucketName).file(fileName), options); await loadJob; console.log(`Job ${loadJob.id} completed. Created table ${tableId}.`); } catch (error) { console.error('Error loading data into BigQuery:', error); throw error; } };
  1. 在 nano 依序按下 Ctrl+xY,接著按下 Enter 鍵來儲存檔案。
建立函式。

工作 4:建立 Cloud Storage bucket 和 BigQuery 資料集

在這項工作中,您會設定 Cloud Storage bucket 做為背景基礎架構,以便儲存叫用 Cloud Run functions 的資產,接著將輸出內容儲存至 BigQuery。

  1. 在 Cloud Shell 執行下列指令,建立新的 Cloud Storage bucket 做為測試環境位置:
gcloud storage buckets create gs://$PROJECT_ID --location=$REGION
  1. 執行下列指令,建立 BigQuery 資料集來儲存資料:
bq mk -d loadavro 建立 Cloud Storage bucket 和 BigQuery 資料集。

工作 5:部署函式

在這項工作中,您會部署並觸發新建立的 Cloud Run functions,以便將資料載入 BigQuery。

  1. 在 Cloud Shell 執行下列指令,安裝兩個 JavaScript 程式庫,以便從 Cloud Storage 讀取資料,並將輸出內容儲存至 BigQuery:
npm install @google-cloud/storage @google-cloud/bigquery
  1. 輸入下列指令來部署函式:
gcloud functions deploy loadBigQueryFromAvro \ --gen2 \ --runtime nodejs20 \ --source . \ --region $REGION \ --trigger-resource gs://$PROJECT_ID \ --trigger-event google.storage.object.finalize \ --memory=512Mi \ --timeout=540s \ --service-account=$PROJECT_NUMBER-compute@developer.gserviceaccount.com 注意:如果看到與 Eventarc 服務代理套用相關的錯誤訊息,請稍候幾分鐘,然後再試一次。
  1. 執行下列指令,確認觸發條件是否已成功建立。輸出內容大致如下:
gcloud eventarc triggers list --location=$REGION NAME: loadbigqueryfromavro-177311 TYPE: google.cloud.storage.object.v1.finalized DESTINATION: Cloud Functions: loadBigQueryFromAvro ACTIVE: Yes LOCATION: europe-west1
  1. 執行下列指令,下載 Avro 檔案。Cloud Run functions 處理完此檔案後,就會將輸出內容儲存至 BigQuery:
wget https://storage.googleapis.com/cloud-training/dataengineering/lab_assets/idegc/campaigns.avro
  1. 執行下列指令,將 Avro 檔案移至剛才建立的測試環境 Cloud Storage bucket,這個動作將觸發 Cloud Run functions:
gcloud storage cp campaigns.avro gs://{{{project_0.project_id |PROJECT_ID}}} 部署函式。

工作 6:確認資料已載入 BigQuery

在這項工作中,您會使用 bq 指令查詢 loadavro.campaigns 資料表,確認 Cloud Run functions 處理的資料已順利載入 BigQuery。

  1. 在 Cloud Shell 執行下列 bq 指令,查看 BigQuery 新資料表中的資料:
bq query \ --use_legacy_sql=false \ 'SELECT * FROM `loadavro.campaigns`;' 注意:Cloud Run functions 的處理速度通常很快,不過 BigQuery 有可能在您執行查詢後未傳回結果。如果遇到這種狀況,請稍後片刻,然後重新執行查詢。

查詢結果大致如下:

輸出內容範例:

+------------+--------+---------------------+--------+---------------------+----------+-----+ | created_at | period | campaign_name | amount | advertising_channel | bid_type | id | +------------+--------+---------------------+--------+---------------------+----------+-----+ | 2020-09-17 | 90 | NA - Video - Other | 41 | Video | CPC | 81 | | 2021-01-19 | 30 | NA - Video - Promo | 325 | Video | CPC | 137 | | 2021-06-28 | 30 | NA - Video - Promo | 78 | Video | CPC | 214 | | 2021-03-15 | 30 | EU - Search - Brand | 465 | Search | CPC | 170 | | 2022-01-01 | 30 | EU - Search - Brand | 83 | Search | CPC | 276 | | 2020-02-18 | 30 | EU - Search - Brand | 30 | Search | CPC | 25 | | 2021-06-08 | 30 | EU - Search - Brand | 172 | Search | CPC | 201 | | 2020-11-29 | 60 | EU - Search - Other | 83 | Search | CPC | 115 | | 2021-09-11 | 30 | EU - Search - Other | 86 | Search | CPC | 237 | | 2022-02-17 | 30 | EU - Search - Other | 64 | Search | CPC | 296 | +------------+--------+---------------------+--------+---------------------+----------+-----+

工作 7:查看記錄

在這項工作中,您會擷取與 loadBigQueryFromAvro 服務相關聯的所有記錄項目。

  1. 在 Cloud Shell 執行下列指令,檢查 Cloud Run functions 的記錄:
gcloud logging read "resource.labels.service_name=loadBigQueryFromAvro"

記錄中的訊息大致如下:

resource: labels: configuration_name: loadbigqueryfromavro location: europe-west1 project_id: qwiklabs-gcp-04-16fde64676e4 revision_name: loadbigqueryfromavro-00001-wim service_name: loadbigqueryfromavro type: cloud_run_revision spanId: '5804952652695382607' textPayload: | Job undefined completed. Created table campaigns. timestamp: '2025-03-10T17:24:43.560594Z'

恭喜!

您已使用 Google Cloud SDK 建立、部署及測試 Cloud Run functions,成功建立及載入 BigQuery 資料表。

Copyright 2026 Google LLC 保留所有權利。Google 和 Google 標誌是 Google LLC 的商標,其他公司和產品名稱則有可能是其關聯公司的商標。

Before you begin

  1. Labs create a Google Cloud project and resources for a fixed time
  2. Labs have a time limit and no pause feature. If you end the lab, you'll have to restart from the beginning.
  3. On the top left of your screen, click Start lab to begin

Use private browsing

  1. Copy the provided Username and Password for the lab
  2. Click Open console in private mode

Sign in to the Console

  1. Sign in using your lab credentials. Using other credentials might cause errors or incur charges.
  2. Accept the terms, and skip the recovery resource page
  3. Don't click End lab unless you've finished the lab or want to restart it, as it will clear your work and remove the project

This content is not currently available

We will notify you via email when it becomes available

Great!

We will contact you via email if it becomes available

One lab at a time

Confirm to end all existing labs and start this one

Use private browsing to run the lab

Using an Incognito or private browser window is the best way to run this lab. This prevents any conflicts between your personal account and the Student account, which may cause extra charges incurred to your personal account.

Complete this quick step to start your lab.