Skip to content

Commit

Permalink
clusterapi: refresh kubeconfig bearer tokens for management and workl…
Browse files Browse the repository at this point in the history
…oad kubeconfigs dynamically
  • Loading branch information
cnmcavoy committed Jul 13, 2023
1 parent ec783d2 commit 911efe7
Showing 1 changed file with 30 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,13 @@ limitations under the License.
package clusterapi

import (
"fmt"
"net/http"
"reflect"

corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
utilnet "k8s.io/apimachinery/pkg/util/net"
"k8s.io/client-go/discovery"
"k8s.io/client-go/discovery/cached/memory"
"k8s.io/client-go/dynamic"
Expand Down Expand Up @@ -158,13 +161,22 @@ func BuildClusterAPI(opts config.AutoscalingOptions, do cloudprovider.NodeGroupD
if err != nil {
klog.Fatalf("cannot build management cluster config: %v", err)
}
if managementConfig.BearerToken != "" && !opts.ClusterAPICloudConfigAuthoritative {
managementConfig.Wrap(func(rt http.RoundTripper) http.RoundTripper {
return &bearerAuthRoundTripper{rt: rt, kubeconfigPath: managementKubeconfig}
})
}

workloadKubeconfig := opts.KubeConfigPath

workloadConfig, err := clientcmd.BuildConfigFromFlags("", workloadKubeconfig)
if err != nil {
klog.Fatalf("cannot build workload cluster config: %v", err)
}
if workloadConfig.BearerToken != "" {
workloadConfig.Wrap(func(rt http.RoundTripper) http.RoundTripper {
return &bearerAuthRoundTripper{rt: rt, kubeconfigPath: workloadKubeconfig}
})
}

// Grab a dynamic interface that we can create informers from
managementClient, err := dynamic.NewForConfig(managementConfig)
Expand Down Expand Up @@ -207,3 +219,20 @@ func BuildClusterAPI(opts config.AutoscalingOptions, do cloudprovider.NodeGroupD

return newProvider(cloudprovider.ClusterAPIProviderName, rl, controller)
}

type bearerAuthRoundTripper struct {
kubeconfigPath string
rt http.RoundTripper
}

func (rt bearerAuthRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
req = utilnet.CloneRequest(req)
kubeConfig, err := clientcmd.BuildConfigFromFlags("", rt.kubeconfigPath)
if err != nil {
return nil, fmt.Errorf("cannot build kube cluster config: %w", err)
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", kubeConfig.BearerToken))
return rt.rt.RoundTrip(req)
}

var _ http.RoundTripper = &bearerAuthRoundTripper{}

0 comments on commit 911efe7

Please sign in to comment.