我正在尝试通过管理 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 程序:
- 设置 gcloud cli 以在您的电脑上运行(说明:https://cloud.google.com/sdk/gcloud)
- 为您的 go 应用程序创建一个服务帐户以在其下运行(说明:https://cloud.google.com/docs/authentication/production#creating_a_service_account)
- 授予服务帐户权限(使用上面相同的说明链接)
- 创建一个包含您的新服务帐户凭据的本地 key 文件(使用上面相同的说明链接)
- 将
GOOGLE_APPLICATION_CREDENTIALS
环境变量设置为本地 key 文件的路径 - 编写您的 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/