Skip to content

Instantly share code, notes, and snippets.

@ahmetb

ahmetb/main.go

Created Aug 21, 2020
Embed
What would you like to do?
Authenticate Knative on GKE using Cloud Run API client library
package main
import (
"context"
"crypto/x509"
"encoding/base64"
"fmt"
"net/http"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/container/v1"
"google.golang.org/api/option"
"google.golang.org/api/run/v1"
)
func main() {
ctx := context.Background()
caCert, masterIP, err := gkeClusterInfo(ctx, "project-id", "gke-cluster-name", "gke-cluster-zone")
if err != nil {
panic(err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM([]byte(caCert))
t := http.DefaultTransport.(*http.Transport).Clone()
t.TLSClientConfig.RootCAs = caCertPool
ts, err := google.DefaultTokenSource(ctx, "cloud-platform")
if err != nil {
panic(err)
}
tt := &oauth2.Transport{
Base: t,
Source: ts}
hc := &http.Client{Transport: tt}
runService, err := run.NewService(ctx,
option.WithHTTPClient(hc),
option.WithEndpoint("https://"+masterIP))
if err != nil {
panic(err)
}
// List Service
resp, err := runService.Namespaces.Services.List("namespaces/default").Do()
if err != nil {
panic(err)
}
fmt.Printf("%d kservices found\n", len(resp.Items))
// Get service
ksvc, err := runService.Namespaces.Services.Get("namespaces/default/services/hello").Do()
if err != nil {
panic(err)
}
// Replace service
_, err = runService.Namespaces.Services.ReplaceService("namespaces/default/services/hello", ksvc).Do()
if err != nil {
panic(err)
}
}
func gkeClusterInfo(ctx context.Context, projectID, clusterName, zone string) ([]byte, string, error) {
s, err := container.NewService(ctx)
if err != nil {
return nil, "", fmt.Errorf("failed to initialize gke api client: %w", err)
}
cluster, err := s.Projects.Zones.Clusters.Get(projectID, zone, clusterName).Do()
if err != nil {
return nil, "", fmt.Errorf("failed to get GKE cluster: %w", err)
}
cert, err := base64.StdEncoding.DecodeString(cluster.MasterAuth.ClusterCaCertificate)
if err != nil {
return nil, "", fmt.Errorf("error decoding cert: %v", err)
}
return cert, cluster.Endpoint, nil
}
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.