无法使用Golang停止GCP实例

时间:2019-06-14 22:43:25

标签: go google-cloud-platform

我正在尝试学习golang,并决定构建一个简单的应用程序来停止我的gcloud项目中的实例。以下是相关片段。

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()

1 个答案:

答案 0 :(得分:1)

更改此行代码:

result := svc.Instances.Stop(project, zone, v.Name)

收件人:

result, err := svc.Instances.Stop(project, zone, v.Name).Context(ctx).Do()
相关问题