快速入门:将 Compute Engine 与 Rust 搭配使用

借助 Compute Engine API,您可以在 Google Cloud上创建和运行虚拟机 (VM)。

本指南介绍了如何初始化适用于 Rust 的 Compute Engine 客户端库,以及如何使用该库执行基本操作。

前提条件

在开始本指南之前,请确保您有一个已启用结算功能的现有 Google Cloud 项目。

将客户端库添加为依赖项

使用 cargo 将 google-cloud-compute-v1 crate 添加到 Cargo.toml 文件中:

cargo add google-cloud-compute-v1

列出虚拟机

用于创建和管理虚拟机的客户端称为 Instances。您可以使用此类型的 list() 方法列出项目和可用区中的虚拟机:

pub async fn sample(project_id: &str) -> anyhow::Result<()> {
    use google_cloud_compute_v1::client::Instances;
    use google_cloud_gax::paginator::ItemPaginator;

    const ZONE: &str = "us-central1-a";

    let client = Instances::builder().build().await?;
    println!("Listing instances for project {project_id}");
    let mut instances = client
        .list()
        .set_project(project_id)
        .set_zone(ZONE)
        .by_item();
    while let Some(item) = instances.next().await.transpose()? {
        println!("  {:?}", item.name);
    }
    println!("DONE");
    Ok(())
}

后续步骤