Skip to content

Instantly share code, notes, and snippets.

@salrashid123
Last active June 11, 2022 14:12
Show Gist options
  • Save salrashid123/de857ddc24407a14e7655861cd224bd0 to your computer and use it in GitHub Desktop.
Save salrashid123/de857ddc24407a14e7655861cd224bd0 to your computer and use it in GitHub Desktop.
Create and manage google api keys in go (https://blog.salrashid.dev/articles/2022/google_api_keys/)
package main
import (
"encoding/json"
"flag"
"fmt"
"time"
"golang.org/x/net/context"
apikeys "google.golang.org/api/apikeys/v2"
)
var (
projectID = flag.String("projectID", "", "projectID")
)
const (
location = "global"
)
func main() {
flag.Parse()
if *projectID == "" {
fmt.Printf("specify a projectID")
return
}
ctx := context.Background()
apikeysService, err := apikeys.NewService(ctx)
if err != nil {
panic(fmt.Errorf("%v", err))
}
parent := fmt.Sprintf("projects/%s/locations/%s", *projectID, location)
fmt.Println("Creating Key")
op, err := apikeysService.Projects.Locations.Keys.Create(parent, &apikeys.V2Key{
DisplayName: "my first key",
Annotations: map[string]string{"k1": "v1", "k2": "v2"},
}).Do()
if err != nil {
panic(fmt.Errorf("%v", err))
}
for {
if op.Done {
break
}
opGetCall := apikeysService.Operations.Get(op.Name)
op, err = opGetCall.Do()
if err != nil {
panic(fmt.Errorf("%v", err))
}
fmt.Printf("creating key ... %s\n", op.Name)
time.Sleep(1 * time.Second)
}
jsonBytes, err := op.Response.MarshalJSON()
if err != nil {
panic(fmt.Errorf("%v", err))
}
b := &apikeys.V2Key{}
err = json.Unmarshal(jsonBytes, b)
if err != nil {
fmt.Println("error:", err)
}
fmt.Printf("Key String %s\n", b.KeyString)
apiKey := b.KeyString
// list all api keys in a project
fmt.Println("Iterating keys")
pageToken := ""
for {
kr, err := apikeysService.Projects.Locations.Keys.List(parent).PageToken(pageToken).Do()
if err != nil {
panic(fmt.Errorf("%v", err))
}
for _, k := range kr.Keys {
fmt.Printf("key: %v\n", k.Name)
ks, err := apikeysService.Projects.Locations.Keys.GetKeyString(k.Name).Do()
if err != nil {
panic(fmt.Errorf("%v", err))
}
fmt.Printf(" KeyString %s\n", ks.KeyString)
}
pageToken = kr.NextPageToken
if pageToken == "" {
break
}
}
// get key given the keystring
kl := apikeysService.Keys.LookupKey().KeyString(apiKey)
lr, err := kl.Do()
if err != nil {
panic(fmt.Errorf("%v", err))
}
fmt.Printf("API Key raw project %s\n", lr.Parent)
// add ip restrictions to a given key
fmt.Printf("Adding IP Restrict for key %s\n", lr.Name)
op, err = apikeysService.Projects.Locations.Keys.Patch(lr.Name, &apikeys.V2Key{
Restrictions: &apikeys.V2Restrictions{
ApiTargets: []*apikeys.V2ApiTarget{
{
Service: "geocoding-backend.googleapis.com",
},
},
ServerKeyRestrictions: &apikeys.V2ServerKeyRestrictions{
AllowedIps: []string{"71.126.189.22/32", "2600:4040:2098:a700:a927:617b:3d94:c3b6"},
},
},
}).Do()
if err != nil {
panic(fmt.Errorf("%v", err))
}
for {
if op.Done {
break
}
opGetCall := apikeysService.Operations.Get(op.Name)
op, err = opGetCall.Do()
if err != nil {
panic(fmt.Errorf("%v", err))
}
fmt.Printf("updating key... %s\n", op.Name)
time.Sleep(1 * time.Second)
}
fmt.Printf("Key updated :%v\n", op.Done)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment