Search code examples
kubernetesgoogle-cloud-platformoauth-2.0oauthgoogle-iam

Accessing GKE resources through kubectl (or client-go) after OAuth authentication to Google Cloud


I have successfully completed an OAuth 2.0 flow to Google Cloud using the https://www.googleapis.com/auth/cloud-platform scope.

I am now in possession of a token.

I want to be able to access kubernetes resources in GKE using kubectl or (preferably) through client-go library.

How can I use this token to

  • get the credentials for a specific cluster that resides in a specific project?
  • run something in the likes of creating / accessing a secret, e.g.
createdSecret, _ := clientset.CoreV1().Secrets(secret.Namespace).Create(ctx, secret, metav1.CreateOptions{})

Solution

  • The answer complements the one suggested by @DazWilkin

    Assuming token is the *oauth2.Token object already retrieved via the OAuth2.0 flow. The dynamic in-memory kube config objects should be constructed as follows

     apiConfig := api.Config{
            APIVersion: "v1",
            Kind:       "Config",
            Clusters: map[string]*api.Cluster{
                clusterName: {
                    CertificateAuthorityData: cert,
                    Server:                   server,
                },
            },
            Contexts: map[string]*api.Context{
                clusterName: {
                    Cluster:  clusterName,
                    AuthInfo: clusterName,
                },
            },
            // CurrentContext: clusterName,
            AuthInfos: map[string]*api.AuthInfo{
                Token: token.AccessToken,
                clusterName: {
                    AuthProvider: &api.AuthProviderConfig{
                        Name: "gcp",
                        Config: map[string]string{
                            "scopes": scopes,
                        },
                    },
                },
            },
        }
    

    Notice the addition of Token: token.AccessToken, in the api.AuthInfo struct.