Skip to content

Instantly share code, notes, and snippets.

@droyo
Created December 26, 2019 23:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save droyo/440e15b8dfd2163304d6235caddc1aab to your computer and use it in GitHub Desktop.
Save droyo/440e15b8dfd2163304d6235caddc1aab to your computer and use it in GitHub Desktop.
GCP iamcredentials.googleapis.com GenerateAccessToken GRPC example
package main
import (
"log"
"flag"
"path"
"time"
"context"
"github.com/kr/pretty"
pb "google.golang.org/genproto/googleapis/iam/credentials/v1"
// "google.golang.org/grpc"
// "google.golang.org/grpc/codes"
"google.golang.org/api/option"
"github.com/golang/protobuf/ptypes"
gtransport "google.golang.org/api/transport/grpc"
)
var (
credentialsFile = flag.String("c", "credentials.json", "Path to credentials file")
svcAccount = flag.String("a", "", "service account email or unique ID to obtain token for")
lifetime = flag.Duration("d", time.Minute, "lifetime of token")
)
func main() {
flag.Parse()
if *svcAccount == "" {
log.Fatal("-a option required")
}
ctx := context.Background()
conn, err := gtransport.Dial(ctx,
option.WithEndpoint("iamcredentials.googleapis.com:443"),
option.WithScopes("https://www.googleapis.com/auth/cloud-platform"),
option.WithCredentialsFile(*credentialsFile))
if err != nil {
log.Fatal("Failed to dial API: ", err)
}
client := pb.NewIAMCredentialsClient(conn)
req := pb.GenerateAccessTokenRequest{
Name: path.Join("projects/-/serviceAccounts", *svcAccount),
Scope: []string{"https://www.googleapis.com/auth/cloud-platform"},
Lifetime: ptypes.DurationProto(*lifetime),
}
log.Print("request: ", pretty.Sprint(req))
rsp, err := client.GenerateAccessToken(ctx, &req)
if err != nil {
log.Fatal("Failed to call GenerateAccessToken: ", err)
}
pretty.Print(rsp)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment