Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
list all gce instances authenticating with the current gcloud configuration
package main
import (
"context"
"flag"
"fmt"
"github.com/binxio/gcloudconfig"
"golang.org/x/oauth2/google"
"google.golang.org/api/compute/v1"
"google.golang.org/api/option"
"log"
)
// list instances
func main() {
var err error
var credentials *google.Credentials
name := flag.String("configuration", "", "`name` of the configuration to use")
project := flag.String("project", "", "`id` of the project to query")
flag.Parse()
if credentials, err = gcloudconfig.GetCredentials(*name); err != nil {
log.Fatal(err)
}
if project == nil || *project == "" {
project = &credentials.ProjectID
}
if *project == "" {
log.Printf("%v", credentials)
log.Fatal("no -project specified")
}
computeService, err := compute.NewService(context.Background(), option.WithCredentials(credentials))
if err != nil {
log.Fatal(err)
}
fmt.Printf("instances in %s\n", *project)
token := ""
for {
var list *compute.InstanceAggregatedList
if list, err = computeService.Instances.AggregatedList(*project).PageToken(token).Do(); err != nil {
log.Fatal(err)
}
for zone, instances := range list.Items {
for _, instance := range instances.Instances {
fmt.Printf("%s %s %s\n", instance.Name, zone, instance.Status)
}
}
if token = list.NextPageToken; token == "" {
break
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.