Skip to content

Instantly share code, notes, and snippets.

@mvanholsteijn
Last active May 6, 2020 18:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mvanholsteijn/83eb3b857f796c0c15cf46a024c9facf to your computer and use it in GitHub Desktop.
Save mvanholsteijn/83eb3b857f796c0c15cf46a024c9facf to your computer and use it in GitHub Desktop.
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