doujue6196 2019-06-14 22:43
浏览 40
已采纳

无法使用Golang停止GCP实例

I'm trying to learn golang, and decided to build a simple app to stop instances in my gcloud project. Relevant snippets below.

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
", 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
}

When I run with go run main.go I get output that the machine was found in state running (so I know I've reached the stop line). However, the machine is never stopped. I'm a bit confused as to what could be going wrong here, or (more importantly) how to find resources that could help me.

Is there some logical flaw in my code? How would a more experienced go developer find more information on this method and it's usage? Docs seem pretty sparse from what I can find.


Answered: Updated code Snippets...

Call stopTaggedMachines like this

stopTaggedMachines(ctx, computeService, "my-project", "us-west1-b", "gcp-idler-managed")

Call Stop like this

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

1条回答 默认 最新

  • dousiyou1058 2019-06-15 21:38
    关注

    Change this line of code:

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

    To:

    result, err := svc.Instances.Stop(project, zone, v.Name).Context(ctx).Do()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作