開始之前,請先確認您符合下列必要條件:
安裝 Rust。如果尚未安裝 Rust,請參閱 Rust 文件中的入門指南。
您可以透過下列指令確認是否已安裝 Rust (以及 Rust 版本):
cargo --version安裝編輯器或 IDE。
安裝 Google Cloud CLI。
建立新的 Rust 專案
如要建立新的 Rust 專案,請執行下列指令:
cargo new my-project
執行下列指令,將目錄變更為新專案:
cd my-project
安裝 Google Cloud 用戶端程式庫
Rust 適用的 Cloud 用戶端程式庫是 Rust 開發人員整合 Google Cloud 服務 (例如 Secret Manager 和 Workflows) 的慣用工具。
將 Secret Manager 用戶端程式庫新增至新專案:
cargo add google-cloud-secretmanager-v1如果尚未啟用 Secret Manager API,請在「API 與服務」中啟用,或執行下列指令:
gcloud services enable secretmanager.googleapis.com將
google-cloud-gaxCrate 新增至新專案:cargo add google-cloud-gax將 tokio Crate 新增至新專案:
cargo add tokio --features macros在專案中編輯
src/main.rs,使用 Secret Manager 用戶端程式庫:#[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { use google_cloud_gax::paginator::ItemPaginator as _; use google_cloud_secretmanager_v1::client::SecretManagerService; let project_id = std::env::args().nth(1).unwrap(); let client = SecretManagerService::builder().build().await?; let mut items = client .list_secrets() .set_parent(format!("projects/{project_id}")) .by_item(); while let Some(item) = items.next().await { println!("{}", item?.name); } Ok(()) }最後,建構程式:
cargo build
程式應可順利建構。
執行 Rust 應用程式
如要在本機開發環境中使用 Cloud 用戶端程式庫,請設定應用程式預設憑證。
如要設定應用程式預設憑證,請執行下列指令:
gcloud auth application-default login
執行程式,並提供 Google Cloud 專案 ID:
PROJECT_ID=$(gcloud config get project)
cargo run ${PROJECT_ID}
程式會列印與專案 ID 相關聯的密鑰。如果沒有看到任何密鑰,可能是因為 Secret Manager 中沒有密鑰。建立密鑰並重新執行程式,輸出內容中應該會顯示密鑰。