Created
August 21, 2020 04:34
-
-
Save ahmetb/e0d567bbfc09feb666790b0eeaaedd6a to your computer and use it in GitHub Desktop.
Authenticate Knative on GKE using Cloud Run API client library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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