登录
首页 >  Golang >  Go问答

如何使用 Go 列出 Google Cloud Platform 上正在运行的实例

来源:stackoverflow

时间:2024-03-16 21:18:27 288浏览 收藏

**文章首段摘要** 本文介绍了如何使用 Go 语言列出 Google Cloud Platform 上正在运行的实例。它涵盖了设置、权限授予和环境变量配置等先决条件,并提供了一个 Go 应用程序示例,用于获取实例列表并打印其详细信息,包括区域、名称、机器类型和启动时间。该示例还演示了如何过滤结果以排除不感兴趣的实例。

问题内容

我正在尝试通过管理 google cloud platform 来学习 go。我不明白如何使用compute的相关功能。目标是列出带有一些 go 代码的实例。

这是https://godoc.org/google.golang.org/api/compute/v1#instancesservice。列出相关函数。

func (r *InstancesService) List(project string, zone string) *InstancesListCall

有两个结构体,instancesservice 和 instanceslistcall

据我了解,我应该定义这些结构,但不清楚应该在结构中定义哪些内容。我搜索了示例,但其中许多使用 rest 调用而不是 golang api。知道如何使用 go 列出实例吗?


解决方案


我今天不得不写这样的东西,但谷歌搜索的例子却出奇的少。我已经在下面写下了我学到的东西,但是,我对 golang 还很陌生,所以也许聪明的人可以提出改进建议。

我正在进行的工作位于:https://github.com/grenade/rubberneck

如果您想从不在 google 计算平台上的开发电脑运行 go 程序:

package main

import (

  "golang.org/x/net/context"
  "google.golang.org/api/compute/v1"
  "golang.org/x/oauth2/google"

  "fmt"
  "strings"
)

func main() {
  projects := [...]string{
    "my-project-one",
    "my-project-two",
  }
  filters := [...]string{
    "status = RUNNING",
    "name != my-uninteresting-instance-one",
    "name != my-uninteresting-instance-two",
  }

  ctx := context.Background()
  client, err := google.DefaultClient(ctx,compute.ComputeScope)
  if err != nil {
    fmt.Println(err)
  }
  computeService, err := compute.New(client)
  for _, project := range projects {
    zoneListCall := computeService.Zones.List(project)
    zoneList, err := zoneListCall.Do()
    if err != nil {
      fmt.Println("Error", err)
    } else {
      for _, zone := range zoneList.Items {
        instanceListCall := computeService.Instances.List(project, zone.Name)
        instanceListCall.Filter(strings.Join(filters[:], " "))
        instanceList, err := instanceListCall.Do()
        if err != nil {
          fmt.Println("Error", err)
        } else {
          for _, instance := range instanceList.Items {
            if workerType, isWorker := instance.Labels["worker-type"]; isWorker {
              m := strings.Split(instance.MachineType, "/")
              fmt.Printf("cloud: gcp, zone: %v, name: %v, instance id: %v, machine type: %v, worker type: %v, launch time: %v\n",
                zone.Name,
                instance.Name,
                instance.Id,
                m[len(m)-1],
                workerType,
                instance.CreationTimestamp)
            }
          }
        }
      }
    }
  }
}

以上就是《如何使用 Go 列出 Google Cloud Platform 上正在运行的实例》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>