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