Cloud Run 服務教學課程中的 gcloud 指令列

在本教學課程中,您將在 Cloud Run 服務中使用 Google Cloud CLI,建立 Cloud Run 服務的清單。您可以將本教學課程中學到的知識,套用至現有的 Cloud 作業指令碼,或是在使用用戶端程式庫建構更強大的服務之前,先建構概念驗證。

您可以使用 gcloud CLI,就像在網路服務中使用任何殼層指令碼一樣,例如殼層快速入門導覽課程所示。在 Cloud Run 上,這兩項工具都會自動使用 Cloud Run 服務身分進行驗證,以便與 Cloud de Confiance by S3NS服務搭配使用。授予服務身分的任何權限,gcloud CLI 都能使用。

gcloud CLI 具備廣泛的資訊收集和資源管理功能,可跨 Cloud de Confiance by S3NS 執行,因此在網路服務中使用這項工具的挑戰,在於如何盡可能降低呼叫端濫用這些功能的風險。如果沒有安全控管機制,您可能會允許意外或蓄意的惡意活動,進而對在同一專案中執行的其他服務或資源造成風險。這類風險包括:

  • 啟用私人虛擬機器的 IP 位址探索功能
  • 允許存取同一專案中資料庫的私人資料
  • 啟用其他執行中服務的刪除功能

本教學課程中的幾個步驟說明如何實施控制措施,將風險降至最低,例如指定要在程式碼中執行的 gcloud 指令,而不是將其保留為使用者輸入內容。

在 Cloud Run 服務中使用指令列工具編寫指令碼,與在本機使用指令列類似。主要差異在於,您應在主要指令碼邏輯周圍加入額外限制。

目標

  • 使用 Dockerfile 編寫及建構自訂容器
  • 編寫、建構及部署 Cloud Run 服務
  • 在網路服務中安全使用 gcloud CLI
  • 產生 Cloud Run 服務報表並儲存至 Cloud Storage

費用

在本文件中,您會使用下列 Cloud de Confiance by S3NS計費元件:

事前準備

  1. In the Cloud de Confiance console, on the project selector page, select or create a Cloud de Confiance 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

  2. Verify that billing is enabled for your Cloud de Confiance project.

  3. 啟用 Artifact Registry、Cloud Build、Cloud Run 和 Cloud Storage API (如有尚未啟用的 API)。

    啟用 API 所需的角色

    如要啟用 API,您必須具備 serviceusage.services.enable 權限。如果您建立了專案,可能已透過擁有者角色 (roles/owner) 取得這項權限。否則,您可以透過 Service Usage 管理員角色 (roles/serviceusage.serviceUsageAdmin) 取得這項權限。瞭解如何授予角色。

    啟用 API

  4. 安裝並初始化 gcloud CLI。

必要的角色

如要取得完成教學課程所需的權限,請要求管理員在專案中授予您下列 IAM 角色:

如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。

您或許也能透過自訂角色或其他預先定義的角色,取得必要權限。

設定 gcloud 預設值

如要針對 Cloud Run 服務設定 gcloud 的預設值:

  1. 設定您的預設專案:

    gcloud config set project PROJECT_ID

    將 PROJECT_ID 替換為您為本教學課程建立的專案名稱。

  2. 為所選區域設定 gcloud:

    gcloud config set run/region REGION

    將 REGION 替換為您選擇的支援 Cloud Run 區域。

Cloud Run 位置

Cloud Run 具有區域性,這表示執行 Cloud Run 服務的基礎架構位於特定區域,並由 Google 負責管理,實現該區域內所有可用區之間的備援可用性。

選擇執行 Cloud Run 服務的區域時,主要考量因素是滿足延遲時間、可用性或耐用性需求。原則上可以選擇距離使用者最近的區域,但也應考慮 Cloud Run 服務所用其他 Cloud de Confiance產品的位置。如果跨多個位置使用 Cloud de Confiance 產品,可能會影響服務的延遲時間和費用。

Cloud Run 可在下列地區使用:

採用級別 1 定價

採用級別 2 定價

  • asia-east2 (香港)
  • asia-northeast3 (韓國首爾)
  • asia-southeast1 (新加坡)
  • asia-southeast2 (雅加達)
  • asia-south2 (印度德里)
  • australia-southeast1 (雪梨)
  • australia-southeast2 (墨爾本)
  • europe-central2 (波蘭華沙) 節能綠葉圖示 低二氧化碳
  • europe-west10 (柏林)
  • europe-west12 (杜林) 節能綠葉圖示 低二氧化碳排放
  • europe-west2 (英國倫敦) 節能綠葉圖示 低二氧化碳排放
  • europe-west3 (德國法蘭克福)
  • europe-west6 (瑞士蘇黎世) 節能綠葉圖示 低二氧化碳
  • me-central1 (杜哈)
  • me-central2 (達曼)
  • northamerica-northeast1 (蒙特婁) 節能綠葉圖示 低二氧化碳排放
  • northamerica-northeast2 (多倫多) 節能綠葉圖示 低二氧化碳排放
  • southamerica-east1 (巴西聖保羅) 節能綠葉圖示 低二氧化碳排放
  • southamerica-west1 (智利聖地牙哥) 節能綠葉圖示 低二氧化碳排放
  • us-west2 (洛杉磯)
  • us-west3 (鹽湖城)
  • us-west4 (拉斯維加斯)

如果您已建立 Cloud Run 服務,可以在Cloud de Confiance 控制台的 Cloud Run 資訊主頁中查看區域。

擷取程式碼範例

如要擷取要使用的程式碼範例:

  1. 將應用程式存放區範例複製到本機電腦中:

    git clone https://github.com/GoogleCloudPlatform/cloud-run-samples.git

    您也可以下載範例 ZIP 檔案,然後解壓縮。

  2. 變更為包含 Cloud Run 程式碼範例的目錄:

    cd cloud-run-samples/gcloud-report/

檢查程式碼

本節包含您擷取的程式碼範例相關資訊。

產生報表並上傳至 Cloud Storage

這個殼層指令碼會產生目前專案和區域中的 Cloud Run 服務報表,並將結果上傳至 Cloud Storage。列出名稱包含所提供字串 search 引數的服務。

指令碼會使用 gcloud run services list 指令、gcloud 進階格式選項和 gcloud 串流移轉複製模式。

set -eo pipefail

# Check for required environment variables.
requireEnv() {
  test "${!1}" || (echo "gcloud-report: '$1' not found" >&2 && exit 1)
}
requireEnv GCLOUD_REPORT_BUCKET

# Prepare formatting: Default search term to include all services.
search=${1:-'.'}
limits='spec.template.spec.containers.resources.limits.flatten("", "", " ")'
format='table[box, title="Cloud Run Services"](name,status.url,metadata.annotations.[serving.knative.dev/creator],'${limits}')'

# Create a specific object name that will not be overridden in the future.
obj="gs://${GCLOUD_REPORT_BUCKET}/report-${search}-$(date +%s).txt"

# Write a report containing the service name, service URL, service account or user that
# deployed it, and any explicitly configured service "limits" such as CPU or Memory.
gcloud run services list \
  --format "${format}" \
  --filter "metadata.name~${search}" | gcloud storage cp --gzip-in-flight-all - "${obj}"

# /dev/stderr is sent to Cloud Logging.
echo "gcloud-report: wrote to ${obj}" >&2
echo "Wrote report to ${obj}"

這個指令碼可以安全地做為服務執行,因為重複叫用指令碼會更新報表,不會造成進一步的高昂流失。使用 gcloud CLI 的其他指令碼在重複叫用時,可能會產生較高費用,例如建立新的 Cloud 資源或執行高成本工作。冪等指令碼在重複叫用時會產生相同結果,因此以服務形式執行較為安全。

在 HTTP 要求上叫用指令碼

這段 Go 程式碼會設定網路服務,執行殼層指令碼來產生報表。由於搜尋查詢是使用者輸入內容,程式碼會驗證該內容,確保只包含英文字母、數字或連字號,防止輸入惡意指令。這組字元範圍夠小,可防止指令注入式攻擊。

網路服務會將搜尋參數做為引數傳遞至殼層指令碼。


// Service gcloud-report is a Cloud Run shell-script-as-a-service.
package main

import (
	"log"
	"net/http"
	"os"
	"os/exec"
	"regexp"
)

func main() {
	http.HandleFunc("/", scriptHandler)

	// Determine port for HTTP service.
	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
		log.Printf("defaulting to port %s", port)
	}

	// Start HTTP server.
	log.Printf("listening on port %s", port)
	if err := http.ListenAndServe(":"+port, nil); err != nil {
		log.Fatal(err)
	}
}

func scriptHandler(w http.ResponseWriter, r *http.Request) {
	search := r.URL.Query().Get("search")
	re := regexp.MustCompile(`^[a-z]+[a-z0-9\-]*$`)
	if !re.MatchString(search) {
		log.Printf("invalid search criteria %q, using default", search)
		search = "."
	}

	cmd := exec.CommandContext(r.Context(), "/bin/bash", "script.sh", search)
	cmd.Stderr = os.Stderr
	out, err := cmd.Output()
	if err != nil {
		log.Printf("Command.Output: %v", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	w.Write(out)
}

go.mod 檔案會在 Go 模組中宣告應用程式依附元件:

module github.com/GoogleCloudPlatform/cloud-run-samples/gcloud-report

go 1.19

定義容器環境

Dockerfile 會定義如何為服務建構環境。這與 helloworld-shell 快速入門導覽課程中的 Dockerfile 類似,但最終容器映像檔是以 gcloud Google Cloud CLI 映像檔為基礎。這樣一來,您的服務就能使用 gcloud,不必自訂 Google Cloud CLI 的安裝和設定步驟。


# Use the official golang image to create a binary.
# This is based on Debian and sets the GOPATH to /go.
# https://hub.docker.com/_/golang
FROM golang:1.20-buster as builder

# Create and change to the app directory.
WORKDIR /app

# Retrieve application dependencies.
# This allows the container build to reuse cached dependencies.
# Expecting to copy go.mod and if present go.sum.
COPY go.* ./
RUN go mod download

# Copy local code to the container image.
COPY invoke.go ./

# Build the binary.
RUN go build -mod=readonly -v -o server

# Use a gcloud image based on debian:buster-slim for a lean production container.
# https://docs.docker.com/develop/develop-images/multistage-build/#use-multi-stage-builds
FROM gcr.io/google.com/cloudsdktool/cloud-sdk:slim

WORKDIR /app

# Copy the binary to the production image from the builder stage.
COPY --from=builder /app/server /app/server
COPY *.sh /app/
RUN chmod +x /app/*.sh

# Run the web service on container startup.
CMD ["/app/server"]

建立 Artifact Registry 標準存放區

建立 Artifact Registry 標準存放區,用於儲存容器映像檔:

gcloud artifacts repositories create REPOSITORY \
    --repository-format=docker \
    --location=REGION

更改項目:

  • REPOSITORY:存放區的專屬名稱。
  • REGION:Artifact Registry 的 Cloud de Confiance by S3NS 區域。

設定 Cloud Storage bucket

建立 Cloud Storage bucket,用於上傳報表:

gcloud storage buckets create gs://REPORT_ARCHIVE_BUCKET

將 REPORT_ARCHIVE_BUCKET 替換成全域不重複的 bucket 名稱。

設定服務身分

為了限制服務對其他基礎架構的權限,您需要建立服務身分,並自訂執行工作所需的特定 IAM 權限。

在本例中,必要權限包括讀取 Cloud Run 服務,以及讀取和寫入 Cloud Storage bucket。

  1. 建立服務帳戶:

    gcloud iam service-accounts create gcloud-report-identity

  2. 授予服務帳戶讀取 Cloud Run 服務的權限:

    gcloud projects add-iam-policy-binding PROJECT_ID \
      --member=serviceAccount:gcloud-report-identity@PROJECT_ID.s3ns.iam.gserviceaccount.com \
      --role roles/run.viewer
  3. 授予服務帳戶讀取及寫入 Cloud Storage bucket 的權限:

    gcloud storage buckets add-iam-policy-binding gs://REPORT_ARCHIVE_BUCKET \
      --member=serviceAccount:gcloud-report-identity@PROJECT_ID.s3ns.iam.gserviceaccount.com \
      --role=roles/storage.objectUser

這項自訂服務身分的存取權有限,可防止服務存取其他 Cloud de Confiance by S3NS 資源。

推出服務

運送代碼包含三個步驟:

  • 使用 Cloud Build 建構容器映像檔
  • 將容器映像檔上傳至 Artifact Registry
  • 將容器映像檔部署至 Cloud Run。

如要推送程式碼:

  1. 建構容器並發布至 Artifact Registry:

    gcloud builds submit --tag REGION-docker.pkg.dev/PROJECT_ID/REPOSITORY/gcloud-report

    更改項目:

    • 將 PROJECT_ID 替換為 Cloud de Confiance 專案 ID
    • REPOSITORY:Artifact Registry 存放區的名稱。
    • REGION:Artifact Registry 的 Cloud de Confiance by S3NS 區域。

    gcloud-report 是服務名稱。

    成功後,系統會顯示「SUCCESS」訊息,其中包含 ID、建立時間和映像檔名稱。映像檔會儲存在 Artifact Registry 中,日後如有需要,可以重複使用。

  2. 執行下列指令來部署服務:

    gcloud run deploy gcloud-report \
       --image REGION-docker.pkg.dev/PROJECT_ID/REPOSITORY/gcloud-report \
       --update-env-vars GCLOUD_REPORT_BUCKET=REPORT_ARCHIVE_BUCKET \
       --service-account gcloud-report-identity \
       --no-allow-unauthenticated

    更改項目:

    • 將 PROJECT_ID 替換為 Cloud de Confiance 專案 ID。
    • REPOSITORY:Artifact Registry 存放區的名稱。
    • REGION:服務所在的 Cloud de Confiance by S3NS 區域。

    gcloud-report 是容器名稱和服務名稱的一部分。容器映像檔會部署到您先前在「設定 gcloud」中設定的服務和區域 (Cloud Run)。

    --no-allow-unauthenticated 旗標會限制對服務的公開存取權。只要將服務設為不公開,即可透過 Cloud Run 的內建驗證機制,封鎖未經授權的要求。如要進一步瞭解以 Identity and Access Management (IAM) 為基礎的驗證,請參閱「使用 IAM 管理存取權」。

    等待部署作業完成。這項作業大約需要半分鐘。 部署成功後,指令列會顯示服務網址。

  3. 如果您要將程式碼更新部署到服務,請重複上述步驟。每次部署到服務都會建立一個新的修訂版本,並會在就緒時自動開始處理流量。

如要瞭解如何授予 Cloud de Confiance 使用者叫用這項服務的權限,請參閱「使用 IAM 管理存取權」。專案編輯者和擁有者會自動取得這項存取權。

產生報表

如要產生 Cloud Run 服務報表,請按照下列步驟操作:

  1. 使用 curl 傳送已驗證的要求:

    curl -H "Authorization: Bearer $(gcloud auth print-identity-token)" SERVICE_URL

    將 SERVICE_URL 替換為 Cloud Run 在部署完成後提供的網址。

    如果您建立新專案並按照本教學課程操作,輸出內容會與下列內容相似:

    Wrote report to gs://REPORT_ARCHIVE_BUCKET/report-.-DATE.txt

    檔案名稱中的 . 是原始碼中提及的預設搜尋引數。

    如要使用搜尋功能,請在要求中加入 search 引數:

    curl -H "Authorization: Bearer $(gcloud auth print-identity-token)" SERVICE_URL?search=gcloud

    這項查詢會傳回類似以下的輸出內容:

    Wrote report to gs://REPORT_ARCHIVE_BUCKET/report-gcloud-DATE.txt
  2. 在本機使用 gcloud CLI 擷取檔案:

    gcloud storage cp gs://REPORT_FILE_NAME .

    指令中的 . 代表目前使用的目錄。

    將 REPORT_FILE_NAME 替換為上一個步驟輸出的 Cloud Storage 物件名稱。

開啟檔案即可查看報表。內容應該會類似這樣:

專案中 Cloud Run 服務清單的螢幕截圖,其中包含四個服務屬性的資料欄。
這四個資料欄是從服務說明中擷取而來。包括服務「名稱」、首次部署時指派的「網址」、服務的初始「建立者」,以及服務的 CPU 和記憶體「限制」。

提升未來穩健性

如要進一步開發這項服務,建議您使用更強大的程式設計語言重寫,並使用 Cloud Run Admin API 和 Cloud Storage 用戶端程式庫。

只要在 gcloud CLI 指令中加入 --log-http,即可查看正在執行的 API 呼叫 (以及部分驗證詳細資料)。

自動執行這項作業

現在,Cloud Run 服務報表可由 HTTP 要求觸發,您可以使用自動化功能,在需要時產生報表:

清除所用資源

為避免系統向您的 Cloud de Confiance by S3NS 帳戶收取額外費用,請刪除您透過本教學課程部署的所有資源。

刪除專案

如果您是為了這個教學課程建立新專案,請刪除專案。如果您使用現有專案,並想保留專案,但不要本教學課程新增的變更,請刪除為本教學課程建立的資源。

如要避免付費,最簡單的方法就是刪除您為了本教學課程所建立的專案。

刪除專案的方法如下:

  1. 前往 Cloud de Confiance 控制台的「Manage resources」(管理資源) 頁面。

    前往「Manage resources」(管理資源)

  2. 在專案清單中選取要刪除的專案,然後點選「Delete」(刪除)。
  3. 在對話方塊中輸入專案 ID,然後按一下 [Shut down] (關閉) 以刪除專案。

刪除教學課程資源

  1. 刪除您在本教學課程中部署的 Cloud Run 服務。Cloud Run 服務在收到要求前不會產生費用。

    如要刪除 Cloud Run 服務,請執行下列指令:

    gcloud run services delete SERVICE-NAME

    將 SERVICE-NAME 改為您的服務名稱。

    您也可以從Cloud de Confiance 控制台刪除 Cloud Run 服務。

  2. 移除您在教學課程設定期間新增的 gcloud 預設區域設定:

     gcloud config unset run/region
    
  3. 移除專案設定:

     gcloud config unset project
    
  4. 刪除在本教學課程中建立的其他 Cloud de Confiance 資源:

後續步驟