@@ -89,33 +89,17 @@ func NewCmd(params *types.CmdParams) *cobra.Command {
8989 return GetAndOutputKubeconfig (ctx , params .Printer , apiClient , clusterConfig , false , nil )
9090 }
9191
92- certPem , _ := pem .Decode (cachedKubeconfig .CertData )
93- if certPem == nil {
92+ isValid , notAfter := checkKubeconfigExpiry (cachedKubeconfig .CertData )
93+ if ! isValid {
94+ // cert is expired or invalid, request new
9495 _ = cache .DeleteObject (clusterConfig .cacheKey )
9596 return GetAndOutputKubeconfig (ctx , params .Printer , apiClient , clusterConfig , false , nil )
96- }
97-
98- certificate , err := x509 .ParseCertificate (certPem .Bytes )
99- if err != nil {
100- _ = cache .DeleteObject (clusterConfig .cacheKey )
101- return GetAndOutputKubeconfig (ctx , params .Printer , apiClient , clusterConfig , false , nil )
102- }
103-
104- // cert is expired, request new
105- if time .Now ().After (certificate .NotAfter .UTC ()) {
106- _ = cache .DeleteObject (clusterConfig .cacheKey )
107- return GetAndOutputKubeconfig (ctx , params .Printer , apiClient , clusterConfig , false , nil )
108- }
109- // cert expires within the next 15min, refresh (try to get a new, use cache on failure)
110- if time .Now ().Add (refreshBeforeDuration ).After (certificate .NotAfter .UTC ()) {
97+ } else if time .Now ().Add (refreshBeforeDuration ).After (notAfter .UTC ()) {
98+ // cert expires within the next 15min, refresh (try to get a new, use cache on failure)
11199 return GetAndOutputKubeconfig (ctx , params .Printer , apiClient , clusterConfig , true , cachedKubeconfig )
112100 }
113-
114101 // cert not expired, nor will it expire in the next 15min; therefore, use the cached kubeconfig
115- if err := output (params .Printer , clusterConfig .cacheKey , cachedKubeconfig ); err != nil {
116- return err
117- }
118- return nil
102+ return output (params .Printer , clusterConfig .cacheKey , cachedKubeconfig )
119103 },
120104 }
121105 return cmd
@@ -186,6 +170,24 @@ func getCachedKubeConfig(key string) *rest.Config {
186170 return restConfig
187171}
188172
173+ func checkKubeconfigExpiry (certData []byte ) (bool , time.Time ) {
174+ certPem , _ := pem .Decode (certData )
175+ if certPem == nil {
176+ return false , time.Time {}
177+ }
178+
179+ certificate , err := x509 .ParseCertificate (certPem .Bytes )
180+ if err != nil {
181+ return false , time.Time {}
182+ }
183+
184+ // cert is expired
185+ if time .Now ().After (certificate .NotAfter .UTC ()) {
186+ return false , time.Time {}
187+ }
188+ return true , certificate .NotAfter .UTC ()
189+ }
190+
189191func GetAndOutputKubeconfig (ctx context.Context , p * print.Printer , apiClient * ske.APIClient , clusterConfig * clusterConfig , fallbackToCache bool , cachedKubeconfig * rest.Config ) error {
190192 req := buildRequest (ctx , apiClient , clusterConfig )
191193 kubeconfigResponse , err := req .Execute ()
0 commit comments