如何使用 Go 列出 Google Cloud Platform 上正在运行的实例
时间:2024-03-16
浏览: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 程序:
- 设置 gcloud cli 以在您的电脑上运行(说明:https://cloud.google.com/sdk/gcloud)
- 为您的 go 应用程序创建一个服务帐户来运行(说明:https://cloud.google.com/docs/authentication/production#creating_a_service_account)
- 向服务帐户授予权限(使用上面相同的说明链接)
- 创建包含新服务帐户凭据的本地密钥文件(使用上面相同的说明链接)
- 将
google_application_credentials环境变量设置为本地密钥文件的路径 - 编写您的 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学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
站内热门
最新文章
11.27
11.27
11.27
热门专题
