快速入門導覽課程:在 Cloud Shell 中設定 Rust

Cloud Shell 是執行小型範例和測試的絕佳環境。本指南說明如何在 Cloud Shell 中設定 Rust,並安裝其中一個 Cloud 用戶端程式庫。

啟動 Cloud Shell

  1. 在 Google Cloud 控制台的專案選擇器中,選取專案。
  2. 開啟 https://shell.cloud.google.com 啟動新的殼層。系統可能會提示您授權 Cloud Shell 使用您的憑證發出Google Cloud API 呼叫。

設定 Rust

  1. Cloud Shell 預先安裝了 rustup。您可以使用此工具安裝及設定預設的 Rust 版本:

    rustup default stable
    
  2. 確認您已安裝最新版的 Rust:

    cargo --version
    

在 Cloud Shell 中安裝 Rust 用戶端程式庫

  1. 建立新的 Rust 專案:

    cargo new my-project
    
  2. 將目錄變更為新專案:

    cd my-project
    
  3. Secret Manager 用戶端程式庫新增至新專案:

    cargo add google-cloud-secretmanager-v1
    
  4. google-cloud-gax Crate 新增至新專案:

    cargo add google-cloud-gax
    
  5. tokio Crate 新增至新專案:

    cargo add tokio --features macros
    
  6. 在專案中編輯 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(())
    }
    
  7. 執行程式,並提供 Google Cloud 專案 ID:

    PROJECT_ID=$(gcloud config get project)
    cargo run ${PROJECT_ID}
    

    程式會列印與專案 ID 相關聯的密鑰。如果沒有看到任何密鑰,可能是因為 Secret Manager 中沒有任何密鑰。建立密鑰並重新執行程式,輸出內容中應該會顯示密鑰。