mirror of
https://github.com/k3s-io/kubernetes.git
synced 2025-09-14 05:36:12 +00:00
Make kubectl work inside a container in k8s
This commit is contained in:
@@ -17,6 +17,7 @@ limitations under the License.
|
||||
package clientcmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
@@ -284,3 +285,32 @@ func (config DirectClientConfig) getCluster() clientcmdapi.Cluster {
|
||||
|
||||
return mergedClusterInfo
|
||||
}
|
||||
|
||||
// inClusterClientConfig makes a config that will work from within a kubernetes cluster container environment.
|
||||
type inClusterClientConfig struct{}
|
||||
|
||||
func (inClusterClientConfig) RawConfig() (clientcmdapi.Config, error) {
|
||||
return clientcmdapi.Config{}, fmt.Errorf("inCluster environment config doesn't support multiple clusters")
|
||||
}
|
||||
|
||||
func (inClusterClientConfig) ClientConfig() (*client.Config, error) {
|
||||
return client.InClusterConfig()
|
||||
}
|
||||
|
||||
func (inClusterClientConfig) Namespace() (string, error) {
|
||||
// TODO: generic way to figure out what namespace you are running in?
|
||||
// This way assumes you've set the POD_NAMESPACE environment variable
|
||||
// using the downward API.
|
||||
if ns := os.Getenv("POD_NAMESPACE"); ns != "" {
|
||||
return ns, nil
|
||||
}
|
||||
return "default", nil
|
||||
}
|
||||
|
||||
// Possible returns true if loading an inside-kubernetes-cluster is possible.
|
||||
func (inClusterClientConfig) Possible() bool {
|
||||
fi, err := os.Stat("/var/run/secrets/kubernetes.io/serviceaccount/token")
|
||||
return os.Getenv("KUBERNETES_SERVICE_HOST") != "" &&
|
||||
os.Getenv("KUBERNETES_SERVICE_PORT") != "" &&
|
||||
err == nil && !fi.IsDir()
|
||||
}
|
||||
|
@@ -45,6 +45,11 @@ func NewInteractiveDeferredLoadingClientConfig(loadingRules *ClientConfigLoading
|
||||
}
|
||||
|
||||
func (config DeferredLoadingClientConfig) createClientConfig() (ClientConfig, error) {
|
||||
// Are we running in a cluster? If so, use that.
|
||||
icc := inClusterClientConfig{}
|
||||
if icc.Possible() {
|
||||
return icc, nil
|
||||
}
|
||||
mergedConfig, err := config.loadingRules.Load()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
Reference in New Issue
Block a user