【问题标题】:Unable to stop a GCP instance with golang无法使用 golang 停止 GCP 实例
【发布时间】: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()

【问题讨论】:

    标签: go google-cloud-platform


    【解决方案1】:

    更改这行代码:

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

    收件人:

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

    【讨论】:

    • 您是否有机会详细说明为什么必须这样称呼它?我正在阅读上下文并且遇到了一些麻烦......在我看来,我已经在这一行的上下文中传递了.. computeService, err := compute.NewService(ctx) 为什么我需要再次将它传递给 stopTaggedMachines 函数,然后传递给Context()函数?
    • 要回答您的问题,请创建另一个问题。答案太详细,无法发表评论。这对于 Google Cloud Go 开发人员来说也是一个很好的问题。
    • 在此处跟进问题 -> stackoverflow.com/questions/56766872/… 谢谢!
    • @thisguy123 - 我发布了一个答案。我不明白为什么你的问题被否决了。也许问题势利,这是一种耻辱。
    猜你喜欢
    • 2020-01-19
    • 2021-01-20
    • 2017-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-26
    • 2014-05-16
    • 2023-01-22
    相关资源
    最近更新 更多