【发布时间】:2019-06-14 22:43:25
【问题描述】:
我正在尝试学习 golang,并决定构建一个简单的应用程序来停止我的 gcloud 项目中的实例。相关sn-ps如下。
func stopTaggedMachines(svc *compute.Service, project, zone, tag string) ([]string, error) {
//result := computeService.Instances.List("my-project", "us-west1-b")
var instances []string
f := func(page *compute.InstanceList) error {
for _, v := range page.Items {
if v.Labels["gcp-idler-managed"] == "true" {
result := svc.Instances.Stop(project, zone, v.Name)
fmt.Printf("[INFO] gcp-machine-idler: Instance in state %v, Stopping %v... Result - %v\n", v.Status, v.Name, result)
instances.append(result)
}
}
return nil
}
call := svc.Instances.List("my-project", "us-west1-b")
if err := call.Pages(oauth2.NoContext, f); err != nil {
return instances, nil
}
return instances, nil
}
func main() {
// Use oauth2.NoContext if there isn't a good context to pass in.
ctx := context.Background()
computeService, err := compute.NewService(ctx)
if err != nil {
log.Fatal(err)
}
stopTaggedMachines(computeService, "my-project", "us-west1-b", "gcp-idler-managed")
return
}
当我使用go run main.go 运行时,我得到的输出表明机器处于运行状态(所以我知道我已经到达停止线)。但是,机器从未停止过。我有点困惑这里可能出了什么问题,或者(更重要的是)如何找到可以帮助我的资源。
我的代码中是否存在一些逻辑缺陷?更有经验的 Go 开发人员如何找到有关此方法及其用法的更多信息?我能找到的文档似乎很少。
已回答:更新的代码片段...
像这样拨打stopTaggedMachines
stopTaggedMachines(ctx, computeService, "my-project", "us-west1-b", "gcp-idler-managed")
像这样拨打Stop
result, err := svc.Instances.Stop(project, zone, v.Name).Context(ctx).Do()
【问题讨论】: