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

标签 go

我正在尝试通过管理 Google Cloud Platform 来学习 Go。 Compute相关的函数怎么用我没看懂。目标是列出带有一些 go 代码的实例。

这是 https://godoc.org/google.golang.org/api/compute/v1#InstancesService.List相关功能。

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

有两个结构,InstancesService 和 InstancesListCall

据我所知,我应该定义这些结构,但尚不清楚应该在结构中定义的东西。我已经搜索过示例,但其中许多示例使用 rest 调用而不是 golang api。知道如何使用 go 列出实例吗?

最佳答案

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

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


如果你想从不在谷歌计算平台上的开发电脑上运行你的 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 - 如何使用 Go 列出 Google Cloud Platform 上正在运行的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55569036/

相关文章:

regex - golang正则表达式获取包含搜索字符的字符串

mongodb - 使用 Go 检索 MongoDB 文档时出现问题

在 go 模式 emacs session 中找不到 Godef

json - 无法解析 Golang 中的 AVRO 模式

http - 如何获取刚在Go中设置的HTTP header 的字符串值?

go - 对结构进行分组的最惯用的方法?

go - 复杂数据类型作为 Go map 中的键

image - 将多个图像打包成 GOLANG 二进制文件

docker - 通过 'revel build <testapp>' 的 run.sh 二进制文件未在 docker 容器内运行

design-patterns - Go walk trees的Erlang翻译