在 Cloud Shell 上设置 Rust

Cloud Shell 提供了一个基于浏览器的命令行环境,用于运行示例和测试 Google Cloud API。本文档介绍了如何在 Cloud Shell 中使用 Rust 版 Cloud 客户端库配置 Rust 工具链并运行 Secret Manager 示例。

准备工作

在运行本文档中的命令之前,请选择或创建一个已启用结算功能的 Google Cloud 项目。

启动 Cloud Shell

完成以下步骤以选择项目并打开 Cloud Shell 会话:

  1. 在 Google Cloud 控制台中,选择或创建一个 Google Cloud 项目。

    转到“项目选择器”

  2. 点击 Google Cloud 控制台顶部的激活 Cloud Shell,启动 Shell 会话。如果系统提示,请授权 Cloud Shell 使用您的凭据进行 Google Cloud API 调用。

配置 Rust

Cloud Shell 预安装了 rustup。完成以下步骤,以配置和验证 Rust 工具链:

  1. 将稳定的 Rust 工具链配置为默认工具链:

    rustup default stable
    
  2. 验证 Cargo 和 Rust 安装:

    cargo --version
    

在 Cloud Shell 中安装客户端库

如需启用 API、添加依赖项并运行示例程序,请完成以下步骤:

  1. 在项目中启用 Secret Manager API:

    gcloud services enable secretmanager.googleapis.com
    
  2. 创建一个二进制 crate 并切换到其目录:

    cargo new my-project
    cd my-project
    
  3. 将 Secret Manager 客户端库、google-cloud-gax 和 tokio 添加到您的项目中:

    cargo add google-cloud-secretmanager-v1 google-cloud-gax
    cargo add tokio --features macros,rt-multi-thread
    
  4. 将 src/main.rs 的内容替换为以下代码:

    #[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(())
    }

  5. 运行程序,将您的 Google Cloud 项目 ID 作为参数传递:

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

    该程序会输出项目中的 Secret 名称。如果您的项目还没有任何 Secret,请创建 Secret,然后再次运行该命令,以便在输出中看到它。

清理

为避免因本文档中使用的资源导致您的 Google Cloud 账号产生费用,请在完成后删除您创建的所有测试 Secret,并从 Cloud Shell 主目录中移除 my-project 目录。